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/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw_wchar_t:
145   case tok::kw_bool:
146   case tok::kw___underlying_type:
147   case tok::kw___auto_type:
148     return true;
149 
150   case tok::annot_typename:
151   case tok::kw_char16_t:
152   case tok::kw_char32_t:
153   case tok::kw_typeof:
154   case tok::annot_decltype:
155   case tok::kw_decltype:
156     return getLangOpts().CPlusPlus;
157 
158   case tok::kw_char8_t:
159     return getLangOpts().Char8;
160 
161   default:
162     break;
163   }
164 
165   return false;
166 }
167 
168 namespace {
169 enum class UnqualifiedTypeNameLookupResult {
170   NotFound,
171   FoundNonType,
172   FoundType
173 };
174 } // end anonymous namespace
175 
176 /// Tries to perform unqualified lookup of the type decls in bases for
177 /// dependent class.
178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179 /// type decl, \a FoundType if only type decls are found.
180 static UnqualifiedTypeNameLookupResult
181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182                                 SourceLocation NameLoc,
183                                 const CXXRecordDecl *RD) {
184   if (!RD->hasDefinition())
185     return UnqualifiedTypeNameLookupResult::NotFound;
186   // Look for type decls in base classes.
187   UnqualifiedTypeNameLookupResult FoundTypeDecl =
188       UnqualifiedTypeNameLookupResult::NotFound;
189   for (const auto &Base : RD->bases()) {
190     const CXXRecordDecl *BaseRD = nullptr;
191     if (auto *BaseTT = Base.getType()->getAs<TagType>())
192       BaseRD = BaseTT->getAsCXXRecordDecl();
193     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194       // Look for type decls in dependent base classes that have known primary
195       // templates.
196       if (!TST || !TST->isDependentType())
197         continue;
198       auto *TD = TST->getTemplateName().getAsTemplateDecl();
199       if (!TD)
200         continue;
201       if (auto *BasePrimaryTemplate =
202           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204           BaseRD = BasePrimaryTemplate;
205         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206           if (const ClassTemplatePartialSpecializationDecl *PS =
207                   CTD->findPartialSpecialization(Base.getType()))
208             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209               BaseRD = PS;
210         }
211       }
212     }
213     if (BaseRD) {
214       for (NamedDecl *ND : BaseRD->lookup(&II)) {
215         if (!isa<TypeDecl>(ND))
216           return UnqualifiedTypeNameLookupResult::FoundNonType;
217         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218       }
219       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221         case UnqualifiedTypeNameLookupResult::FoundNonType:
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         case UnqualifiedTypeNameLookupResult::FoundType:
224           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225           break;
226         case UnqualifiedTypeNameLookupResult::NotFound:
227           break;
228         }
229       }
230     }
231   }
232 
233   return FoundTypeDecl;
234 }
235 
236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237                                                       const IdentifierInfo &II,
238                                                       SourceLocation NameLoc) {
239   // Lookup in the parent class template context, if any.
240   const CXXRecordDecl *RD = nullptr;
241   UnqualifiedTypeNameLookupResult FoundTypeDecl =
242       UnqualifiedTypeNameLookupResult::NotFound;
243   for (DeclContext *DC = S.CurContext;
244        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245        DC = DC->getParent()) {
246     // Look for type decls in dependent base classes that have known primary
247     // templates.
248     RD = dyn_cast<CXXRecordDecl>(DC);
249     if (RD && RD->getDescribedClassTemplate())
250       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251   }
252   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253     return nullptr;
254 
255   // We found some types in dependent base classes.  Recover as if the user
256   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257   // lookup during template instantiation.
258   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259 
260   ASTContext &Context = S.Context;
261   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262                                           cast<Type>(Context.getRecordType(RD)));
263   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264 
265   CXXScopeSpec SS;
266   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267 
268   TypeLocBuilder Builder;
269   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270   DepTL.setNameLoc(NameLoc);
271   DepTL.setElaboratedKeywordLoc(SourceLocation());
272   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274 }
275 
276 /// If the identifier refers to a type name within this scope,
277 /// return the declaration of that type.
278 ///
279 /// This routine performs ordinary name lookup of the identifier II
280 /// within the given scope, with optional C++ scope specifier SS, to
281 /// determine whether the name refers to a type. If so, returns an
282 /// opaque pointer (actually a QualType) corresponding to that
283 /// type. Otherwise, returns NULL.
284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285                              Scope *S, CXXScopeSpec *SS,
286                              bool isClassName, bool HasTrailingDot,
287                              ParsedType ObjectTypePtr,
288                              bool IsCtorOrDtorName,
289                              bool WantNontrivialTypeSourceInfo,
290                              bool IsClassTemplateDeductionContext,
291                              IdentifierInfo **CorrectedII) {
292   // FIXME: Consider allowing this outside C++1z mode as an extension.
293   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295                               !isClassName && !HasTrailingDot;
296 
297   // Determine where we will perform name lookup.
298   DeclContext *LookupCtx = nullptr;
299   if (ObjectTypePtr) {
300     QualType ObjectType = ObjectTypePtr.get();
301     if (ObjectType->isRecordType())
302       LookupCtx = computeDeclContext(ObjectType);
303   } else if (SS && SS->isNotEmpty()) {
304     LookupCtx = computeDeclContext(*SS, false);
305 
306     if (!LookupCtx) {
307       if (isDependentScopeSpecifier(*SS)) {
308         // C++ [temp.res]p3:
309         //   A qualified-id that refers to a type and in which the
310         //   nested-name-specifier depends on a template-parameter (14.6.2)
311         //   shall be prefixed by the keyword typename to indicate that the
312         //   qualified-id denotes a type, forming an
313         //   elaborated-type-specifier (7.1.5.3).
314         //
315         // We therefore do not perform any name lookup if the result would
316         // refer to a member of an unknown specialization.
317         if (!isClassName && !IsCtorOrDtorName)
318           return nullptr;
319 
320         // We know from the grammar that this name refers to a type,
321         // so build a dependent node to describe the type.
322         if (WantNontrivialTypeSourceInfo)
323           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324 
325         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327                                        II, NameLoc);
328         return ParsedType::make(T);
329       }
330 
331       return nullptr;
332     }
333 
334     if (!LookupCtx->isDependentContext() &&
335         RequireCompleteDeclContext(*SS, LookupCtx))
336       return nullptr;
337   }
338 
339   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340   // lookup for class-names.
341   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342                                       LookupOrdinaryName;
343   LookupResult Result(*this, &II, NameLoc, Kind);
344   if (LookupCtx) {
345     // Perform "qualified" name lookup into the declaration context we
346     // computed, which is either the type of the base of a member access
347     // expression or the declaration context associated with a prior
348     // nested-name-specifier.
349     LookupQualifiedName(Result, LookupCtx);
350 
351     if (ObjectTypePtr && Result.empty()) {
352       // C++ [basic.lookup.classref]p3:
353       //   If the unqualified-id is ~type-name, the type-name is looked up
354       //   in the context of the entire postfix-expression. If the type T of
355       //   the object expression is of a class type C, the type-name is also
356       //   looked up in the scope of class C. At least one of the lookups shall
357       //   find a name that refers to (possibly cv-qualified) T.
358       LookupName(Result, S);
359     }
360   } else {
361     // Perform unqualified name lookup.
362     LookupName(Result, S);
363 
364     // For unqualified lookup in a class template in MSVC mode, look into
365     // dependent base classes where the primary class template is known.
366     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367       if (ParsedType TypeInBase =
368               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369         return TypeInBase;
370     }
371   }
372 
373   NamedDecl *IIDecl = nullptr;
374   switch (Result.getResultKind()) {
375   case LookupResult::NotFound:
376   case LookupResult::NotFoundInCurrentInstantiation:
377     if (CorrectedII) {
378       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379                                AllowDeducedTemplate);
380       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381                                               S, SS, CCC, CTK_ErrorRecovery);
382       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383       TemplateTy Template;
384       bool MemberOfUnknownSpecialization;
385       UnqualifiedId TemplateName;
386       TemplateName.setIdentifier(NewII, NameLoc);
387       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388       CXXScopeSpec NewSS, *NewSSPtr = SS;
389       if (SS && NNS) {
390         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391         NewSSPtr = &NewSS;
392       }
393       if (Correction && (NNS || NewII != &II) &&
394           // Ignore a correction to a template type as the to-be-corrected
395           // identifier is not a template (typo correction for template names
396           // is handled elsewhere).
397           !(getLangOpts().CPlusPlus && NewSSPtr &&
398             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399                            Template, MemberOfUnknownSpecialization))) {
400         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401                                     isClassName, HasTrailingDot, ObjectTypePtr,
402                                     IsCtorOrDtorName,
403                                     WantNontrivialTypeSourceInfo,
404                                     IsClassTemplateDeductionContext);
405         if (Ty) {
406           diagnoseTypo(Correction,
407                        PDiag(diag::err_unknown_type_or_class_name_suggest)
408                          << Result.getLookupName() << isClassName);
409           if (SS && NNS)
410             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411           *CorrectedII = NewII;
412           return Ty;
413         }
414       }
415     }
416     // If typo correction failed or was not performed, fall through
417     LLVM_FALLTHROUGH;
418   case LookupResult::FoundOverloaded:
419   case LookupResult::FoundUnresolvedValue:
420     Result.suppressDiagnostics();
421     return nullptr;
422 
423   case LookupResult::Ambiguous:
424     // Recover from type-hiding ambiguities by hiding the type.  We'll
425     // do the lookup again when looking for an object, and we can
426     // diagnose the error then.  If we don't do this, then the error
427     // about hiding the type will be immediately followed by an error
428     // that only makes sense if the identifier was treated like a type.
429     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430       Result.suppressDiagnostics();
431       return nullptr;
432     }
433 
434     // Look to see if we have a type anywhere in the list of results.
435     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436          Res != ResEnd; ++Res) {
437       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
438       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
439               RealRes) ||
440           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
441         if (!IIDecl ||
442             // Make the selection of the recovery decl deterministic.
443             RealRes->getLocation() < IIDecl->getLocation())
444           IIDecl = RealRes;
445       }
446     }
447 
448     if (!IIDecl) {
449       // None of the entities we found is a type, so there is no way
450       // to even assume that the result is a type. In this case, don't
451       // complain about the ambiguity. The parser will either try to
452       // perform this lookup again (e.g., as an object name), which
453       // will produce the ambiguity, or will complain that it expected
454       // a type name.
455       Result.suppressDiagnostics();
456       return nullptr;
457     }
458 
459     // We found a type within the ambiguous lookup; diagnose the
460     // ambiguity and then return that type. This might be the right
461     // answer, or it might not be, but it suppresses any attempt to
462     // perform the name lookup again.
463     break;
464 
465   case LookupResult::Found:
466     IIDecl = Result.getFoundDecl();
467     break;
468   }
469 
470   assert(IIDecl && "Didn't find decl");
471 
472   QualType T;
473   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
474     // C++ [class.qual]p2: A lookup that would find the injected-class-name
475     // instead names the constructors of the class, except when naming a class.
476     // This is ill-formed when we're not actually forming a ctor or dtor name.
477     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
478     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
479     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
480         FoundRD->isInjectedClassName() &&
481         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
482       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
483           << &II << /*Type*/1;
484 
485     DiagnoseUseOfDecl(IIDecl, NameLoc);
486 
487     T = Context.getTypeDeclType(TD);
488     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
489   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
490     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
491     if (!HasTrailingDot)
492       T = Context.getObjCInterfaceType(IDecl);
493   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
494     (void)DiagnoseUseOfDecl(UD, NameLoc);
495     // Recover with 'int'
496     T = Context.IntTy;
497   } else if (AllowDeducedTemplate) {
498     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
499       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
500                                                        QualType(), false);
501   }
502 
503   if (T.isNull()) {
504     // If it's not plausibly a type, suppress diagnostics.
505     Result.suppressDiagnostics();
506     return nullptr;
507   }
508 
509   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
510   // constructor or destructor name (in such a case, the scope specifier
511   // will be attached to the enclosing Expr or Decl node).
512   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
513       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
514     if (WantNontrivialTypeSourceInfo) {
515       // Construct a type with type-source information.
516       TypeLocBuilder Builder;
517       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
518 
519       T = getElaboratedType(ETK_None, *SS, T);
520       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
521       ElabTL.setElaboratedKeywordLoc(SourceLocation());
522       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
523       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
524     } else {
525       T = getElaboratedType(ETK_None, *SS, T);
526     }
527   }
528 
529   return ParsedType::make(T);
530 }
531 
532 // Builds a fake NNS for the given decl context.
533 static NestedNameSpecifier *
534 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
535   for (;; DC = DC->getLookupParent()) {
536     DC = DC->getPrimaryContext();
537     auto *ND = dyn_cast<NamespaceDecl>(DC);
538     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
539       return NestedNameSpecifier::Create(Context, nullptr, ND);
540     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
541       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
542                                          RD->getTypeForDecl());
543     else if (isa<TranslationUnitDecl>(DC))
544       return NestedNameSpecifier::GlobalSpecifier(Context);
545   }
546   llvm_unreachable("something isn't in TU scope?");
547 }
548 
549 /// Find the parent class with dependent bases of the innermost enclosing method
550 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
551 /// up allowing unqualified dependent type names at class-level, which MSVC
552 /// correctly rejects.
553 static const CXXRecordDecl *
554 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
555   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
556     DC = DC->getPrimaryContext();
557     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
558       if (MD->getParent()->hasAnyDependentBases())
559         return MD->getParent();
560   }
561   return nullptr;
562 }
563 
564 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
565                                           SourceLocation NameLoc,
566                                           bool IsTemplateTypeArg) {
567   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
568 
569   NestedNameSpecifier *NNS = nullptr;
570   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
571     // If we weren't able to parse a default template argument, delay lookup
572     // until instantiation time by making a non-dependent DependentTypeName. We
573     // pretend we saw a NestedNameSpecifier referring to the current scope, and
574     // lookup is retried.
575     // FIXME: This hurts our diagnostic quality, since we get errors like "no
576     // type named 'Foo' in 'current_namespace'" when the user didn't write any
577     // name specifiers.
578     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
579     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
580   } else if (const CXXRecordDecl *RD =
581                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
582     // Build a DependentNameType that will perform lookup into RD at
583     // instantiation time.
584     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
585                                       RD->getTypeForDecl());
586 
587     // Diagnose that this identifier was undeclared, and retry the lookup during
588     // template instantiation.
589     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
590                                                                       << RD;
591   } else {
592     // This is not a situation that we should recover from.
593     return ParsedType();
594   }
595 
596   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
597 
598   // Build type location information.  We synthesized the qualifier, so we have
599   // to build a fake NestedNameSpecifierLoc.
600   NestedNameSpecifierLocBuilder NNSLocBuilder;
601   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
602   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
603 
604   TypeLocBuilder Builder;
605   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
606   DepTL.setNameLoc(NameLoc);
607   DepTL.setElaboratedKeywordLoc(SourceLocation());
608   DepTL.setQualifierLoc(QualifierLoc);
609   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
610 }
611 
612 /// isTagName() - This method is called *for error recovery purposes only*
613 /// to determine if the specified name is a valid tag name ("struct foo").  If
614 /// so, this returns the TST for the tag corresponding to it (TST_enum,
615 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
616 /// cases in C where the user forgot to specify the tag.
617 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
618   // Do a tag name lookup in this scope.
619   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
620   LookupName(R, S, false);
621   R.suppressDiagnostics();
622   if (R.getResultKind() == LookupResult::Found)
623     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
624       switch (TD->getTagKind()) {
625       case TTK_Struct: return DeclSpec::TST_struct;
626       case TTK_Interface: return DeclSpec::TST_interface;
627       case TTK_Union:  return DeclSpec::TST_union;
628       case TTK_Class:  return DeclSpec::TST_class;
629       case TTK_Enum:   return DeclSpec::TST_enum;
630       }
631     }
632 
633   return DeclSpec::TST_unspecified;
634 }
635 
636 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
637 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
638 /// then downgrade the missing typename error to a warning.
639 /// This is needed for MSVC compatibility; Example:
640 /// @code
641 /// template<class T> class A {
642 /// public:
643 ///   typedef int TYPE;
644 /// };
645 /// template<class T> class B : public A<T> {
646 /// public:
647 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
648 /// };
649 /// @endcode
650 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
651   if (CurContext->isRecord()) {
652     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
653       return true;
654 
655     const Type *Ty = SS->getScopeRep()->getAsType();
656 
657     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
658     for (const auto &Base : RD->bases())
659       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
660         return true;
661     return S->isFunctionPrototypeScope();
662   }
663   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
664 }
665 
666 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
667                                    SourceLocation IILoc,
668                                    Scope *S,
669                                    CXXScopeSpec *SS,
670                                    ParsedType &SuggestedType,
671                                    bool IsTemplateName) {
672   // Don't report typename errors for editor placeholders.
673   if (II->isEditorPlaceholder())
674     return;
675   // We don't have anything to suggest (yet).
676   SuggestedType = nullptr;
677 
678   // There may have been a typo in the name of the type. Look up typo
679   // results, in case we have something that we can suggest.
680   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
681                            /*AllowTemplates=*/IsTemplateName,
682                            /*AllowNonTemplates=*/!IsTemplateName);
683   if (TypoCorrection Corrected =
684           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
685                       CCC, CTK_ErrorRecovery)) {
686     // FIXME: Support error recovery for the template-name case.
687     bool CanRecover = !IsTemplateName;
688     if (Corrected.isKeyword()) {
689       // We corrected to a keyword.
690       diagnoseTypo(Corrected,
691                    PDiag(IsTemplateName ? diag::err_no_template_suggest
692                                         : diag::err_unknown_typename_suggest)
693                        << II);
694       II = Corrected.getCorrectionAsIdentifierInfo();
695     } else {
696       // We found a similarly-named type or interface; suggest that.
697       if (!SS || !SS->isSet()) {
698         diagnoseTypo(Corrected,
699                      PDiag(IsTemplateName ? diag::err_no_template_suggest
700                                           : diag::err_unknown_typename_suggest)
701                          << II, CanRecover);
702       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
703         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
704         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
705                                 II->getName().equals(CorrectedStr);
706         diagnoseTypo(Corrected,
707                      PDiag(IsTemplateName
708                                ? diag::err_no_member_template_suggest
709                                : diag::err_unknown_nested_typename_suggest)
710                          << II << DC << DroppedSpecifier << SS->getRange(),
711                      CanRecover);
712       } else {
713         llvm_unreachable("could not have corrected a typo here");
714       }
715 
716       if (!CanRecover)
717         return;
718 
719       CXXScopeSpec tmpSS;
720       if (Corrected.getCorrectionSpecifier())
721         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
722                           SourceRange(IILoc));
723       // FIXME: Support class template argument deduction here.
724       SuggestedType =
725           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
726                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
727                       /*IsCtorOrDtorName=*/false,
728                       /*WantNontrivialTypeSourceInfo=*/true);
729     }
730     return;
731   }
732 
733   if (getLangOpts().CPlusPlus && !IsTemplateName) {
734     // See if II is a class template that the user forgot to pass arguments to.
735     UnqualifiedId Name;
736     Name.setIdentifier(II, IILoc);
737     CXXScopeSpec EmptySS;
738     TemplateTy TemplateResult;
739     bool MemberOfUnknownSpecialization;
740     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
741                        Name, nullptr, true, TemplateResult,
742                        MemberOfUnknownSpecialization) == TNK_Type_template) {
743       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
744       return;
745     }
746   }
747 
748   // FIXME: Should we move the logic that tries to recover from a missing tag
749   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
750 
751   if (!SS || (!SS->isSet() && !SS->isInvalid()))
752     Diag(IILoc, IsTemplateName ? diag::err_no_template
753                                : diag::err_unknown_typename)
754         << II;
755   else if (DeclContext *DC = computeDeclContext(*SS, false))
756     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
757                                : diag::err_typename_nested_not_found)
758         << II << DC << SS->getRange();
759   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
760     SuggestedType =
761         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
762   } else if (isDependentScopeSpecifier(*SS)) {
763     unsigned DiagID = diag::err_typename_missing;
764     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
765       DiagID = diag::ext_typename_missing;
766 
767     Diag(SS->getRange().getBegin(), DiagID)
768       << SS->getScopeRep() << II->getName()
769       << SourceRange(SS->getRange().getBegin(), IILoc)
770       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
771     SuggestedType = ActOnTypenameType(S, SourceLocation(),
772                                       *SS, *II, IILoc).get();
773   } else {
774     assert(SS && SS->isInvalid() &&
775            "Invalid scope specifier has already been diagnosed");
776   }
777 }
778 
779 /// Determine whether the given result set contains either a type name
780 /// or
781 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
782   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
783                        NextToken.is(tok::less);
784 
785   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
786     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
787       return true;
788 
789     if (CheckTemplate && isa<TemplateDecl>(*I))
790       return true;
791   }
792 
793   return false;
794 }
795 
796 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
797                                     Scope *S, CXXScopeSpec &SS,
798                                     IdentifierInfo *&Name,
799                                     SourceLocation NameLoc) {
800   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
801   SemaRef.LookupParsedName(R, S, &SS);
802   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
803     StringRef FixItTagName;
804     switch (Tag->getTagKind()) {
805       case TTK_Class:
806         FixItTagName = "class ";
807         break;
808 
809       case TTK_Enum:
810         FixItTagName = "enum ";
811         break;
812 
813       case TTK_Struct:
814         FixItTagName = "struct ";
815         break;
816 
817       case TTK_Interface:
818         FixItTagName = "__interface ";
819         break;
820 
821       case TTK_Union:
822         FixItTagName = "union ";
823         break;
824     }
825 
826     StringRef TagName = FixItTagName.drop_back();
827     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
828       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
829       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
830 
831     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
832          I != IEnd; ++I)
833       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
834         << Name << TagName;
835 
836     // Replace lookup results with just the tag decl.
837     Result.clear(Sema::LookupTagName);
838     SemaRef.LookupParsedName(Result, S, &SS);
839     return true;
840   }
841 
842   return false;
843 }
844 
845 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
846 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
847                                   QualType T, SourceLocation NameLoc) {
848   ASTContext &Context = S.Context;
849 
850   TypeLocBuilder Builder;
851   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
852 
853   T = S.getElaboratedType(ETK_None, SS, T);
854   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
855   ElabTL.setElaboratedKeywordLoc(SourceLocation());
856   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
857   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
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   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1137   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1138     DiagnoseUseOfDecl(Type, NameLoc);
1139     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1140     QualType T = Context.getTypeDeclType(Type);
1141     if (SS.isNotEmpty())
1142       return buildNestedType(*this, SS, T, NameLoc);
1143     return ParsedType::make(T);
1144   }
1145 
1146   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1147   if (!Class) {
1148     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1149     if (ObjCCompatibleAliasDecl *Alias =
1150             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1151       Class = Alias->getClassInterface();
1152   }
1153 
1154   if (Class) {
1155     DiagnoseUseOfDecl(Class, NameLoc);
1156 
1157     if (NextToken.is(tok::period)) {
1158       // Interface. <something> is parsed as a property reference expression.
1159       // Just return "unknown" as a fall-through for now.
1160       Result.suppressDiagnostics();
1161       return NameClassification::Unknown();
1162     }
1163 
1164     QualType T = Context.getObjCInterfaceType(Class);
1165     return ParsedType::make(T);
1166   }
1167 
1168   if (isa<ConceptDecl>(FirstDecl))
1169     return NameClassification::Concept(
1170         TemplateName(cast<TemplateDecl>(FirstDecl)));
1171 
1172   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1173     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1174     return NameClassification::Error();
1175   }
1176 
1177   // We can have a type template here if we're classifying a template argument.
1178   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1179       !isa<VarTemplateDecl>(FirstDecl))
1180     return NameClassification::TypeTemplate(
1181         TemplateName(cast<TemplateDecl>(FirstDecl)));
1182 
1183   // Check for a tag type hidden by a non-type decl in a few cases where it
1184   // seems likely a type is wanted instead of the non-type that was found.
1185   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1186   if ((NextToken.is(tok::identifier) ||
1187        (NextIsOp &&
1188         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1189       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1190     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1191     DiagnoseUseOfDecl(Type, NameLoc);
1192     QualType T = Context.getTypeDeclType(Type);
1193     if (SS.isNotEmpty())
1194       return buildNestedType(*this, SS, T, NameLoc);
1195     return ParsedType::make(T);
1196   }
1197 
1198   // If we already know which single declaration is referenced, just annotate
1199   // that declaration directly. Defer resolving even non-overloaded class
1200   // member accesses, as we need to defer certain access checks until we know
1201   // the context.
1202   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1203   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1204     return NameClassification::NonType(Result.getRepresentativeDecl());
1205 
1206   // Otherwise, this is an overload set that we will need to resolve later.
1207   Result.suppressDiagnostics();
1208   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1209       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1210       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1211       Result.begin(), Result.end()));
1212 }
1213 
1214 ExprResult
1215 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1216                                              SourceLocation NameLoc) {
1217   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1218   CXXScopeSpec SS;
1219   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1220   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1221 }
1222 
1223 ExprResult
1224 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1225                                             IdentifierInfo *Name,
1226                                             SourceLocation NameLoc,
1227                                             bool IsAddressOfOperand) {
1228   DeclarationNameInfo NameInfo(Name, NameLoc);
1229   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1230                                     NameInfo, IsAddressOfOperand,
1231                                     /*TemplateArgs=*/nullptr);
1232 }
1233 
1234 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1235                                               NamedDecl *Found,
1236                                               SourceLocation NameLoc,
1237                                               const Token &NextToken) {
1238   if (getCurMethodDecl() && SS.isEmpty())
1239     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1240       return BuildIvarRefExpr(S, NameLoc, Ivar);
1241 
1242   // Reconstruct the lookup result.
1243   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1244   Result.addDecl(Found);
1245   Result.resolveKind();
1246 
1247   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1248   return BuildDeclarationNameExpr(SS, Result, ADL);
1249 }
1250 
1251 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1252   // For an implicit class member access, transform the result into a member
1253   // access expression if necessary.
1254   auto *ULE = cast<UnresolvedLookupExpr>(E);
1255   if ((*ULE->decls_begin())->isCXXClassMember()) {
1256     CXXScopeSpec SS;
1257     SS.Adopt(ULE->getQualifierLoc());
1258 
1259     // Reconstruct the lookup result.
1260     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1261                         LookupOrdinaryName);
1262     Result.setNamingClass(ULE->getNamingClass());
1263     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1264       Result.addDecl(*I, I.getAccess());
1265     Result.resolveKind();
1266     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1267                                            nullptr, S);
1268   }
1269 
1270   // Otherwise, this is already in the form we needed, and no further checks
1271   // are necessary.
1272   return ULE;
1273 }
1274 
1275 Sema::TemplateNameKindForDiagnostics
1276 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1277   auto *TD = Name.getAsTemplateDecl();
1278   if (!TD)
1279     return TemplateNameKindForDiagnostics::DependentTemplate;
1280   if (isa<ClassTemplateDecl>(TD))
1281     return TemplateNameKindForDiagnostics::ClassTemplate;
1282   if (isa<FunctionTemplateDecl>(TD))
1283     return TemplateNameKindForDiagnostics::FunctionTemplate;
1284   if (isa<VarTemplateDecl>(TD))
1285     return TemplateNameKindForDiagnostics::VarTemplate;
1286   if (isa<TypeAliasTemplateDecl>(TD))
1287     return TemplateNameKindForDiagnostics::AliasTemplate;
1288   if (isa<TemplateTemplateParmDecl>(TD))
1289     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1290   if (isa<ConceptDecl>(TD))
1291     return TemplateNameKindForDiagnostics::Concept;
1292   return TemplateNameKindForDiagnostics::DependentTemplate;
1293 }
1294 
1295 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1296   assert(DC->getLexicalParent() == CurContext &&
1297       "The next DeclContext should be lexically contained in the current one.");
1298   CurContext = DC;
1299   S->setEntity(DC);
1300 }
1301 
1302 void Sema::PopDeclContext() {
1303   assert(CurContext && "DeclContext imbalance!");
1304 
1305   CurContext = CurContext->getLexicalParent();
1306   assert(CurContext && "Popped translation unit!");
1307 }
1308 
1309 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1310                                                                     Decl *D) {
1311   // Unlike PushDeclContext, the context to which we return is not necessarily
1312   // the containing DC of TD, because the new context will be some pre-existing
1313   // TagDecl definition instead of a fresh one.
1314   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1315   CurContext = cast<TagDecl>(D)->getDefinition();
1316   assert(CurContext && "skipping definition of undefined tag");
1317   // Start lookups from the parent of the current context; we don't want to look
1318   // into the pre-existing complete definition.
1319   S->setEntity(CurContext->getLookupParent());
1320   return Result;
1321 }
1322 
1323 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1324   CurContext = static_cast<decltype(CurContext)>(Context);
1325 }
1326 
1327 /// EnterDeclaratorContext - Used when we must lookup names in the context
1328 /// of a declarator's nested name specifier.
1329 ///
1330 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1331   // C++0x [basic.lookup.unqual]p13:
1332   //   A name used in the definition of a static data member of class
1333   //   X (after the qualified-id of the static member) is looked up as
1334   //   if the name was used in a member function of X.
1335   // C++0x [basic.lookup.unqual]p14:
1336   //   If a variable member of a namespace is defined outside of the
1337   //   scope of its namespace then any name used in the definition of
1338   //   the variable member (after the declarator-id) is looked up as
1339   //   if the definition of the variable member occurred in its
1340   //   namespace.
1341   // Both of these imply that we should push a scope whose context
1342   // is the semantic context of the declaration.  We can't use
1343   // PushDeclContext here because that context is not necessarily
1344   // lexically contained in the current context.  Fortunately,
1345   // the containing scope should have the appropriate information.
1346 
1347   assert(!S->getEntity() && "scope already has entity");
1348 
1349 #ifndef NDEBUG
1350   Scope *Ancestor = S->getParent();
1351   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1352   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1353 #endif
1354 
1355   CurContext = DC;
1356   S->setEntity(DC);
1357 
1358   if (S->getParent()->isTemplateParamScope()) {
1359     // Also set the corresponding entities for all immediately-enclosing
1360     // template parameter scopes.
1361     EnterTemplatedContext(S->getParent(), DC);
1362   }
1363 }
1364 
1365 void Sema::ExitDeclaratorContext(Scope *S) {
1366   assert(S->getEntity() == CurContext && "Context imbalance!");
1367 
1368   // Switch back to the lexical context.  The safety of this is
1369   // enforced by an assert in EnterDeclaratorContext.
1370   Scope *Ancestor = S->getParent();
1371   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1372   CurContext = Ancestor->getEntity();
1373 
1374   // We don't need to do anything with the scope, which is going to
1375   // disappear.
1376 }
1377 
1378 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1379   assert(S->isTemplateParamScope() &&
1380          "expected to be initializing a template parameter scope");
1381 
1382   // C++20 [temp.local]p7:
1383   //   In the definition of a member of a class template that appears outside
1384   //   of the class template definition, the name of a member of the class
1385   //   template hides the name of a template-parameter of any enclosing class
1386   //   templates (but not a template-parameter of the member if the member is a
1387   //   class or function template).
1388   // C++20 [temp.local]p9:
1389   //   In the definition of a class template or in the definition of a member
1390   //   of such a template that appears outside of the template definition, for
1391   //   each non-dependent base class (13.8.2.1), if the name of the base class
1392   //   or the name of a member of the base class is the same as the name of a
1393   //   template-parameter, the base class name or member name hides the
1394   //   template-parameter name (6.4.10).
1395   //
1396   // This means that a template parameter scope should be searched immediately
1397   // after searching the DeclContext for which it is a template parameter
1398   // scope. For example, for
1399   //   template<typename T> template<typename U> template<typename V>
1400   //     void N::A<T>::B<U>::f(...)
1401   // we search V then B<U> (and base classes) then U then A<T> (and base
1402   // classes) then T then N then ::.
1403   unsigned ScopeDepth = getTemplateDepth(S);
1404   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1405     DeclContext *SearchDCAfterScope = DC;
1406     for (; DC; DC = DC->getLookupParent()) {
1407       if (const TemplateParameterList *TPL =
1408               cast<Decl>(DC)->getDescribedTemplateParams()) {
1409         unsigned DCDepth = TPL->getDepth() + 1;
1410         if (DCDepth > ScopeDepth)
1411           continue;
1412         if (ScopeDepth == DCDepth)
1413           SearchDCAfterScope = DC = DC->getLookupParent();
1414         break;
1415       }
1416     }
1417     S->setLookupEntity(SearchDCAfterScope);
1418   }
1419 }
1420 
1421 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1422   // We assume that the caller has already called
1423   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1424   FunctionDecl *FD = D->getAsFunction();
1425   if (!FD)
1426     return;
1427 
1428   // Same implementation as PushDeclContext, but enters the context
1429   // from the lexical parent, rather than the top-level class.
1430   assert(CurContext == FD->getLexicalParent() &&
1431     "The next DeclContext should be lexically contained in the current one.");
1432   CurContext = FD;
1433   S->setEntity(CurContext);
1434 
1435   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1436     ParmVarDecl *Param = FD->getParamDecl(P);
1437     // If the parameter has an identifier, then add it to the scope
1438     if (Param->getIdentifier()) {
1439       S->AddDecl(Param);
1440       IdResolver.AddDecl(Param);
1441     }
1442   }
1443 }
1444 
1445 void Sema::ActOnExitFunctionContext() {
1446   // Same implementation as PopDeclContext, but returns to the lexical parent,
1447   // rather than the top-level class.
1448   assert(CurContext && "DeclContext imbalance!");
1449   CurContext = CurContext->getLexicalParent();
1450   assert(CurContext && "Popped translation unit!");
1451 }
1452 
1453 /// Determine whether we allow overloading of the function
1454 /// PrevDecl with another declaration.
1455 ///
1456 /// This routine determines whether overloading is possible, not
1457 /// whether some new function is actually an overload. It will return
1458 /// true in C++ (where we can always provide overloads) or, as an
1459 /// extension, in C when the previous function is already an
1460 /// overloaded function declaration or has the "overloadable"
1461 /// attribute.
1462 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1463                                        ASTContext &Context,
1464                                        const FunctionDecl *New) {
1465   if (Context.getLangOpts().CPlusPlus)
1466     return true;
1467 
1468   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1469     return true;
1470 
1471   return Previous.getResultKind() == LookupResult::Found &&
1472          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1473           New->hasAttr<OverloadableAttr>());
1474 }
1475 
1476 /// Add this decl to the scope shadowed decl chains.
1477 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1478   // Move up the scope chain until we find the nearest enclosing
1479   // non-transparent context. The declaration will be introduced into this
1480   // scope.
1481   while (S->getEntity() && S->getEntity()->isTransparentContext())
1482     S = S->getParent();
1483 
1484   // Add scoped declarations into their context, so that they can be
1485   // found later. Declarations without a context won't be inserted
1486   // into any context.
1487   if (AddToContext)
1488     CurContext->addDecl(D);
1489 
1490   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1491   // are function-local declarations.
1492   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1493     return;
1494 
1495   // Template instantiations should also not be pushed into scope.
1496   if (isa<FunctionDecl>(D) &&
1497       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1498     return;
1499 
1500   // If this replaces anything in the current scope,
1501   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1502                                IEnd = IdResolver.end();
1503   for (; I != IEnd; ++I) {
1504     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1505       S->RemoveDecl(*I);
1506       IdResolver.RemoveDecl(*I);
1507 
1508       // Should only need to replace one decl.
1509       break;
1510     }
1511   }
1512 
1513   S->AddDecl(D);
1514 
1515   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1516     // Implicitly-generated labels may end up getting generated in an order that
1517     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1518     // the label at the appropriate place in the identifier chain.
1519     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1520       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1521       if (IDC == CurContext) {
1522         if (!S->isDeclScope(*I))
1523           continue;
1524       } else if (IDC->Encloses(CurContext))
1525         break;
1526     }
1527 
1528     IdResolver.InsertDeclAfter(I, D);
1529   } else {
1530     IdResolver.AddDecl(D);
1531   }
1532   warnOnReservedIdentifier(D);
1533 }
1534 
1535 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1536                          bool AllowInlineNamespace) {
1537   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1538 }
1539 
1540 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1541   DeclContext *TargetDC = DC->getPrimaryContext();
1542   do {
1543     if (DeclContext *ScopeDC = S->getEntity())
1544       if (ScopeDC->getPrimaryContext() == TargetDC)
1545         return S;
1546   } while ((S = S->getParent()));
1547 
1548   return nullptr;
1549 }
1550 
1551 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1552                                             DeclContext*,
1553                                             ASTContext&);
1554 
1555 /// Filters out lookup results that don't fall within the given scope
1556 /// as determined by isDeclInScope.
1557 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1558                                 bool ConsiderLinkage,
1559                                 bool AllowInlineNamespace) {
1560   LookupResult::Filter F = R.makeFilter();
1561   while (F.hasNext()) {
1562     NamedDecl *D = F.next();
1563 
1564     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1565       continue;
1566 
1567     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1568       continue;
1569 
1570     F.erase();
1571   }
1572 
1573   F.done();
1574 }
1575 
1576 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1577 /// have compatible owning modules.
1578 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1579   // FIXME: The Modules TS is not clear about how friend declarations are
1580   // to be treated. It's not meaningful to have different owning modules for
1581   // linkage in redeclarations of the same entity, so for now allow the
1582   // redeclaration and change the owning modules to match.
1583   if (New->getFriendObjectKind() &&
1584       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1585     New->setLocalOwningModule(Old->getOwningModule());
1586     makeMergedDefinitionVisible(New);
1587     return false;
1588   }
1589 
1590   Module *NewM = New->getOwningModule();
1591   Module *OldM = Old->getOwningModule();
1592 
1593   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1594     NewM = NewM->Parent;
1595   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1596     OldM = OldM->Parent;
1597 
1598   if (NewM == OldM)
1599     return false;
1600 
1601   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1602   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1603   if (NewIsModuleInterface || OldIsModuleInterface) {
1604     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1605     //   if a declaration of D [...] appears in the purview of a module, all
1606     //   other such declarations shall appear in the purview of the same module
1607     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1608       << New
1609       << NewIsModuleInterface
1610       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1611       << OldIsModuleInterface
1612       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1613     Diag(Old->getLocation(), diag::note_previous_declaration);
1614     New->setInvalidDecl();
1615     return true;
1616   }
1617 
1618   return false;
1619 }
1620 
1621 static bool isUsingDecl(NamedDecl *D) {
1622   return isa<UsingShadowDecl>(D) ||
1623          isa<UnresolvedUsingTypenameDecl>(D) ||
1624          isa<UnresolvedUsingValueDecl>(D);
1625 }
1626 
1627 /// Removes using shadow declarations from the lookup results.
1628 static void RemoveUsingDecls(LookupResult &R) {
1629   LookupResult::Filter F = R.makeFilter();
1630   while (F.hasNext())
1631     if (isUsingDecl(F.next()))
1632       F.erase();
1633 
1634   F.done();
1635 }
1636 
1637 /// Check for this common pattern:
1638 /// @code
1639 /// class S {
1640 ///   S(const S&); // DO NOT IMPLEMENT
1641 ///   void operator=(const S&); // DO NOT IMPLEMENT
1642 /// };
1643 /// @endcode
1644 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1645   // FIXME: Should check for private access too but access is set after we get
1646   // the decl here.
1647   if (D->doesThisDeclarationHaveABody())
1648     return false;
1649 
1650   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1651     return CD->isCopyConstructor();
1652   return D->isCopyAssignmentOperator();
1653 }
1654 
1655 // We need this to handle
1656 //
1657 // typedef struct {
1658 //   void *foo() { return 0; }
1659 // } A;
1660 //
1661 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1662 // for example. If 'A', foo will have external linkage. If we have '*A',
1663 // foo will have no linkage. Since we can't know until we get to the end
1664 // of the typedef, this function finds out if D might have non-external linkage.
1665 // Callers should verify at the end of the TU if it D has external linkage or
1666 // not.
1667 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1668   const DeclContext *DC = D->getDeclContext();
1669   while (!DC->isTranslationUnit()) {
1670     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1671       if (!RD->hasNameForLinkage())
1672         return true;
1673     }
1674     DC = DC->getParent();
1675   }
1676 
1677   return !D->isExternallyVisible();
1678 }
1679 
1680 // FIXME: This needs to be refactored; some other isInMainFile users want
1681 // these semantics.
1682 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1683   if (S.TUKind != TU_Complete)
1684     return false;
1685   return S.SourceMgr.isInMainFile(Loc);
1686 }
1687 
1688 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1689   assert(D);
1690 
1691   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1692     return false;
1693 
1694   // Ignore all entities declared within templates, and out-of-line definitions
1695   // of members of class templates.
1696   if (D->getDeclContext()->isDependentContext() ||
1697       D->getLexicalDeclContext()->isDependentContext())
1698     return false;
1699 
1700   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1701     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1702       return false;
1703     // A non-out-of-line declaration of a member specialization was implicitly
1704     // instantiated; it's the out-of-line declaration that we're interested in.
1705     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1706         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1707       return false;
1708 
1709     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1710       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1711         return false;
1712     } else {
1713       // 'static inline' functions are defined in headers; don't warn.
1714       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1715         return false;
1716     }
1717 
1718     if (FD->doesThisDeclarationHaveABody() &&
1719         Context.DeclMustBeEmitted(FD))
1720       return false;
1721   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1722     // Constants and utility variables are defined in headers with internal
1723     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1724     // like "inline".)
1725     if (!isMainFileLoc(*this, VD->getLocation()))
1726       return false;
1727 
1728     if (Context.DeclMustBeEmitted(VD))
1729       return false;
1730 
1731     if (VD->isStaticDataMember() &&
1732         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1733       return false;
1734     if (VD->isStaticDataMember() &&
1735         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1736         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1737       return false;
1738 
1739     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1740       return false;
1741   } else {
1742     return false;
1743   }
1744 
1745   // Only warn for unused decls internal to the translation unit.
1746   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1747   // for inline functions defined in the main source file, for instance.
1748   return mightHaveNonExternalLinkage(D);
1749 }
1750 
1751 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1752   if (!D)
1753     return;
1754 
1755   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1756     const FunctionDecl *First = FD->getFirstDecl();
1757     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1758       return; // First should already be in the vector.
1759   }
1760 
1761   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1762     const VarDecl *First = VD->getFirstDecl();
1763     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1764       return; // First should already be in the vector.
1765   }
1766 
1767   if (ShouldWarnIfUnusedFileScopedDecl(D))
1768     UnusedFileScopedDecls.push_back(D);
1769 }
1770 
1771 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1772   if (D->isInvalidDecl())
1773     return false;
1774 
1775   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1776     // For a decomposition declaration, warn if none of the bindings are
1777     // referenced, instead of if the variable itself is referenced (which
1778     // it is, by the bindings' expressions).
1779     for (auto *BD : DD->bindings())
1780       if (BD->isReferenced())
1781         return false;
1782   } else if (!D->getDeclName()) {
1783     return false;
1784   } else if (D->isReferenced() || D->isUsed()) {
1785     return false;
1786   }
1787 
1788   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1789     return false;
1790 
1791   if (isa<LabelDecl>(D))
1792     return true;
1793 
1794   // Except for labels, we only care about unused decls that are local to
1795   // functions.
1796   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1797   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1798     // For dependent types, the diagnostic is deferred.
1799     WithinFunction =
1800         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1801   if (!WithinFunction)
1802     return false;
1803 
1804   if (isa<TypedefNameDecl>(D))
1805     return true;
1806 
1807   // White-list anything that isn't a local variable.
1808   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1809     return false;
1810 
1811   // Types of valid local variables should be complete, so this should succeed.
1812   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1813 
1814     // White-list anything with an __attribute__((unused)) type.
1815     const auto *Ty = VD->getType().getTypePtr();
1816 
1817     // Only look at the outermost level of typedef.
1818     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1819       if (TT->getDecl()->hasAttr<UnusedAttr>())
1820         return false;
1821     }
1822 
1823     // If we failed to complete the type for some reason, or if the type is
1824     // dependent, don't diagnose the variable.
1825     if (Ty->isIncompleteType() || Ty->isDependentType())
1826       return false;
1827 
1828     // Look at the element type to ensure that the warning behaviour is
1829     // consistent for both scalars and arrays.
1830     Ty = Ty->getBaseElementTypeUnsafe();
1831 
1832     if (const TagType *TT = Ty->getAs<TagType>()) {
1833       const TagDecl *Tag = TT->getDecl();
1834       if (Tag->hasAttr<UnusedAttr>())
1835         return false;
1836 
1837       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1838         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1839           return false;
1840 
1841         if (const Expr *Init = VD->getInit()) {
1842           if (const ExprWithCleanups *Cleanups =
1843                   dyn_cast<ExprWithCleanups>(Init))
1844             Init = Cleanups->getSubExpr();
1845           const CXXConstructExpr *Construct =
1846             dyn_cast<CXXConstructExpr>(Init);
1847           if (Construct && !Construct->isElidable()) {
1848             CXXConstructorDecl *CD = Construct->getConstructor();
1849             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1850                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1851               return false;
1852           }
1853 
1854           // Suppress the warning if we don't know how this is constructed, and
1855           // it could possibly be non-trivial constructor.
1856           if (Init->isTypeDependent())
1857             for (const CXXConstructorDecl *Ctor : RD->ctors())
1858               if (!Ctor->isTrivial())
1859                 return false;
1860         }
1861       }
1862     }
1863 
1864     // TODO: __attribute__((unused)) templates?
1865   }
1866 
1867   return true;
1868 }
1869 
1870 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1871                                      FixItHint &Hint) {
1872   if (isa<LabelDecl>(D)) {
1873     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1874         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1875         true);
1876     if (AfterColon.isInvalid())
1877       return;
1878     Hint = FixItHint::CreateRemoval(
1879         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1880   }
1881 }
1882 
1883 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1884   if (D->getTypeForDecl()->isDependentType())
1885     return;
1886 
1887   for (auto *TmpD : D->decls()) {
1888     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1889       DiagnoseUnusedDecl(T);
1890     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1891       DiagnoseUnusedNestedTypedefs(R);
1892   }
1893 }
1894 
1895 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1896 /// unless they are marked attr(unused).
1897 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1898   if (!ShouldDiagnoseUnusedDecl(D))
1899     return;
1900 
1901   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1902     // typedefs can be referenced later on, so the diagnostics are emitted
1903     // at end-of-translation-unit.
1904     UnusedLocalTypedefNameCandidates.insert(TD);
1905     return;
1906   }
1907 
1908   FixItHint Hint;
1909   GenerateFixForUnusedDecl(D, Context, Hint);
1910 
1911   unsigned DiagID;
1912   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1913     DiagID = diag::warn_unused_exception_param;
1914   else if (isa<LabelDecl>(D))
1915     DiagID = diag::warn_unused_label;
1916   else
1917     DiagID = diag::warn_unused_variable;
1918 
1919   Diag(D->getLocation(), DiagID) << D << Hint;
1920 }
1921 
1922 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1923   // If it's not referenced, it can't be set.
1924   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>())
1925     return;
1926 
1927   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1928 
1929   if (Ty->isReferenceType() || Ty->isDependentType())
1930     return;
1931 
1932   if (const TagType *TT = Ty->getAs<TagType>()) {
1933     const TagDecl *Tag = TT->getDecl();
1934     if (Tag->hasAttr<UnusedAttr>())
1935       return;
1936     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1937     // mimic gcc's behavior.
1938     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1939       if (!RD->hasAttr<WarnUnusedAttr>())
1940         return;
1941     }
1942   }
1943 
1944   auto iter = RefsMinusAssignments.find(VD);
1945   if (iter == RefsMinusAssignments.end())
1946     return;
1947 
1948   assert(iter->getSecond() >= 0 &&
1949          "Found a negative number of references to a VarDecl");
1950   if (iter->getSecond() != 0)
1951     return;
1952   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1953                                          : diag::warn_unused_but_set_variable;
1954   Diag(VD->getLocation(), DiagID) << VD;
1955 }
1956 
1957 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1958   // Verify that we have no forward references left.  If so, there was a goto
1959   // or address of a label taken, but no definition of it.  Label fwd
1960   // definitions are indicated with a null substmt which is also not a resolved
1961   // MS inline assembly label name.
1962   bool Diagnose = false;
1963   if (L->isMSAsmLabel())
1964     Diagnose = !L->isResolvedMSAsmLabel();
1965   else
1966     Diagnose = L->getStmt() == nullptr;
1967   if (Diagnose)
1968     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1969 }
1970 
1971 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1972   S->mergeNRVOIntoParent();
1973 
1974   if (S->decl_empty()) return;
1975   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1976          "Scope shouldn't contain decls!");
1977 
1978   for (auto *TmpD : S->decls()) {
1979     assert(TmpD && "This decl didn't get pushed??");
1980 
1981     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1982     NamedDecl *D = cast<NamedDecl>(TmpD);
1983 
1984     // Diagnose unused variables in this scope.
1985     if (!S->hasUnrecoverableErrorOccurred()) {
1986       DiagnoseUnusedDecl(D);
1987       if (const auto *RD = dyn_cast<RecordDecl>(D))
1988         DiagnoseUnusedNestedTypedefs(RD);
1989       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1990         DiagnoseUnusedButSetDecl(VD);
1991         RefsMinusAssignments.erase(VD);
1992       }
1993     }
1994 
1995     if (!D->getDeclName()) continue;
1996 
1997     // If this was a forward reference to a label, verify it was defined.
1998     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1999       CheckPoppedLabel(LD, *this);
2000 
2001     // Remove this name from our lexical scope, and warn on it if we haven't
2002     // already.
2003     IdResolver.RemoveDecl(D);
2004     auto ShadowI = ShadowingDecls.find(D);
2005     if (ShadowI != ShadowingDecls.end()) {
2006       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2007         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2008             << D << FD << FD->getParent();
2009         Diag(FD->getLocation(), diag::note_previous_declaration);
2010       }
2011       ShadowingDecls.erase(ShadowI);
2012     }
2013   }
2014 }
2015 
2016 /// Look for an Objective-C class in the translation unit.
2017 ///
2018 /// \param Id The name of the Objective-C class we're looking for. If
2019 /// typo-correction fixes this name, the Id will be updated
2020 /// to the fixed name.
2021 ///
2022 /// \param IdLoc The location of the name in the translation unit.
2023 ///
2024 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2025 /// if there is no class with the given name.
2026 ///
2027 /// \returns The declaration of the named Objective-C class, or NULL if the
2028 /// class could not be found.
2029 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2030                                               SourceLocation IdLoc,
2031                                               bool DoTypoCorrection) {
2032   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2033   // creation from this context.
2034   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2035 
2036   if (!IDecl && DoTypoCorrection) {
2037     // Perform typo correction at the given location, but only if we
2038     // find an Objective-C class name.
2039     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2040     if (TypoCorrection C =
2041             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2042                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2043       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2044       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2045       Id = IDecl->getIdentifier();
2046     }
2047   }
2048   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2049   // This routine must always return a class definition, if any.
2050   if (Def && Def->getDefinition())
2051       Def = Def->getDefinition();
2052   return Def;
2053 }
2054 
2055 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2056 /// from S, where a non-field would be declared. This routine copes
2057 /// with the difference between C and C++ scoping rules in structs and
2058 /// unions. For example, the following code is well-formed in C but
2059 /// ill-formed in C++:
2060 /// @code
2061 /// struct S6 {
2062 ///   enum { BAR } e;
2063 /// };
2064 ///
2065 /// void test_S6() {
2066 ///   struct S6 a;
2067 ///   a.e = BAR;
2068 /// }
2069 /// @endcode
2070 /// For the declaration of BAR, this routine will return a different
2071 /// scope. The scope S will be the scope of the unnamed enumeration
2072 /// within S6. In C++, this routine will return the scope associated
2073 /// with S6, because the enumeration's scope is a transparent
2074 /// context but structures can contain non-field names. In C, this
2075 /// routine will return the translation unit scope, since the
2076 /// enumeration's scope is a transparent context and structures cannot
2077 /// contain non-field names.
2078 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2079   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2080          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2081          (S->isClassScope() && !getLangOpts().CPlusPlus))
2082     S = S->getParent();
2083   return S;
2084 }
2085 
2086 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2087                                ASTContext::GetBuiltinTypeError Error) {
2088   switch (Error) {
2089   case ASTContext::GE_None:
2090     return "";
2091   case ASTContext::GE_Missing_type:
2092     return BuiltinInfo.getHeaderName(ID);
2093   case ASTContext::GE_Missing_stdio:
2094     return "stdio.h";
2095   case ASTContext::GE_Missing_setjmp:
2096     return "setjmp.h";
2097   case ASTContext::GE_Missing_ucontext:
2098     return "ucontext.h";
2099   }
2100   llvm_unreachable("unhandled error kind");
2101 }
2102 
2103 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2104                                   unsigned ID, SourceLocation Loc) {
2105   DeclContext *Parent = Context.getTranslationUnitDecl();
2106 
2107   if (getLangOpts().CPlusPlus) {
2108     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2109         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2110     CLinkageDecl->setImplicit();
2111     Parent->addDecl(CLinkageDecl);
2112     Parent = CLinkageDecl;
2113   }
2114 
2115   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2116                                            /*TInfo=*/nullptr, SC_Extern, false,
2117                                            Type->isFunctionProtoType());
2118   New->setImplicit();
2119   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2120 
2121   // Create Decl objects for each parameter, adding them to the
2122   // FunctionDecl.
2123   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2124     SmallVector<ParmVarDecl *, 16> Params;
2125     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2126       ParmVarDecl *parm = ParmVarDecl::Create(
2127           Context, New, SourceLocation(), SourceLocation(), nullptr,
2128           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2129       parm->setScopeInfo(0, i);
2130       Params.push_back(parm);
2131     }
2132     New->setParams(Params);
2133   }
2134 
2135   AddKnownFunctionAttributes(New);
2136   return New;
2137 }
2138 
2139 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2140 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2141 /// if we're creating this built-in in anticipation of redeclaring the
2142 /// built-in.
2143 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2144                                      Scope *S, bool ForRedeclaration,
2145                                      SourceLocation Loc) {
2146   LookupNecessaryTypesForBuiltin(S, ID);
2147 
2148   ASTContext::GetBuiltinTypeError Error;
2149   QualType R = Context.GetBuiltinType(ID, Error);
2150   if (Error) {
2151     if (!ForRedeclaration)
2152       return nullptr;
2153 
2154     // If we have a builtin without an associated type we should not emit a
2155     // warning when we were not able to find a type for it.
2156     if (Error == ASTContext::GE_Missing_type ||
2157         Context.BuiltinInfo.allowTypeMismatch(ID))
2158       return nullptr;
2159 
2160     // If we could not find a type for setjmp it is because the jmp_buf type was
2161     // not defined prior to the setjmp declaration.
2162     if (Error == ASTContext::GE_Missing_setjmp) {
2163       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2164           << Context.BuiltinInfo.getName(ID);
2165       return nullptr;
2166     }
2167 
2168     // Generally, we emit a warning that the declaration requires the
2169     // appropriate header.
2170     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2171         << getHeaderName(Context.BuiltinInfo, ID, Error)
2172         << Context.BuiltinInfo.getName(ID);
2173     return nullptr;
2174   }
2175 
2176   if (!ForRedeclaration &&
2177       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2178        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2179     Diag(Loc, diag::ext_implicit_lib_function_decl)
2180         << Context.BuiltinInfo.getName(ID) << R;
2181     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2182       Diag(Loc, diag::note_include_header_or_declare)
2183           << Header << Context.BuiltinInfo.getName(ID);
2184   }
2185 
2186   if (R.isNull())
2187     return nullptr;
2188 
2189   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2190   RegisterLocallyScopedExternCDecl(New, S);
2191 
2192   // TUScope is the translation-unit scope to insert this function into.
2193   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2194   // relate Scopes to DeclContexts, and probably eliminate CurContext
2195   // entirely, but we're not there yet.
2196   DeclContext *SavedContext = CurContext;
2197   CurContext = New->getDeclContext();
2198   PushOnScopeChains(New, TUScope);
2199   CurContext = SavedContext;
2200   return New;
2201 }
2202 
2203 /// Typedef declarations don't have linkage, but they still denote the same
2204 /// entity if their types are the same.
2205 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2206 /// isSameEntity.
2207 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2208                                                      TypedefNameDecl *Decl,
2209                                                      LookupResult &Previous) {
2210   // This is only interesting when modules are enabled.
2211   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2212     return;
2213 
2214   // Empty sets are uninteresting.
2215   if (Previous.empty())
2216     return;
2217 
2218   LookupResult::Filter Filter = Previous.makeFilter();
2219   while (Filter.hasNext()) {
2220     NamedDecl *Old = Filter.next();
2221 
2222     // Non-hidden declarations are never ignored.
2223     if (S.isVisible(Old))
2224       continue;
2225 
2226     // Declarations of the same entity are not ignored, even if they have
2227     // different linkages.
2228     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2229       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2230                                 Decl->getUnderlyingType()))
2231         continue;
2232 
2233       // If both declarations give a tag declaration a typedef name for linkage
2234       // purposes, then they declare the same entity.
2235       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2236           Decl->getAnonDeclWithTypedefName())
2237         continue;
2238     }
2239 
2240     Filter.erase();
2241   }
2242 
2243   Filter.done();
2244 }
2245 
2246 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2247   QualType OldType;
2248   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2249     OldType = OldTypedef->getUnderlyingType();
2250   else
2251     OldType = Context.getTypeDeclType(Old);
2252   QualType NewType = New->getUnderlyingType();
2253 
2254   if (NewType->isVariablyModifiedType()) {
2255     // Must not redefine a typedef with a variably-modified type.
2256     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2257     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2258       << Kind << NewType;
2259     if (Old->getLocation().isValid())
2260       notePreviousDefinition(Old, New->getLocation());
2261     New->setInvalidDecl();
2262     return true;
2263   }
2264 
2265   if (OldType != NewType &&
2266       !OldType->isDependentType() &&
2267       !NewType->isDependentType() &&
2268       !Context.hasSameType(OldType, NewType)) {
2269     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2270     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2271       << Kind << NewType << OldType;
2272     if (Old->getLocation().isValid())
2273       notePreviousDefinition(Old, New->getLocation());
2274     New->setInvalidDecl();
2275     return true;
2276   }
2277   return false;
2278 }
2279 
2280 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2281 /// same name and scope as a previous declaration 'Old'.  Figure out
2282 /// how to resolve this situation, merging decls or emitting
2283 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2284 ///
2285 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2286                                 LookupResult &OldDecls) {
2287   // If the new decl is known invalid already, don't bother doing any
2288   // merging checks.
2289   if (New->isInvalidDecl()) return;
2290 
2291   // Allow multiple definitions for ObjC built-in typedefs.
2292   // FIXME: Verify the underlying types are equivalent!
2293   if (getLangOpts().ObjC) {
2294     const IdentifierInfo *TypeID = New->getIdentifier();
2295     switch (TypeID->getLength()) {
2296     default: break;
2297     case 2:
2298       {
2299         if (!TypeID->isStr("id"))
2300           break;
2301         QualType T = New->getUnderlyingType();
2302         if (!T->isPointerType())
2303           break;
2304         if (!T->isVoidPointerType()) {
2305           QualType PT = T->castAs<PointerType>()->getPointeeType();
2306           if (!PT->isStructureType())
2307             break;
2308         }
2309         Context.setObjCIdRedefinitionType(T);
2310         // Install the built-in type for 'id', ignoring the current definition.
2311         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2312         return;
2313       }
2314     case 5:
2315       if (!TypeID->isStr("Class"))
2316         break;
2317       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2318       // Install the built-in type for 'Class', ignoring the current definition.
2319       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2320       return;
2321     case 3:
2322       if (!TypeID->isStr("SEL"))
2323         break;
2324       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2325       // Install the built-in type for 'SEL', ignoring the current definition.
2326       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2327       return;
2328     }
2329     // Fall through - the typedef name was not a builtin type.
2330   }
2331 
2332   // Verify the old decl was also a type.
2333   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2334   if (!Old) {
2335     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2336       << New->getDeclName();
2337 
2338     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2339     if (OldD->getLocation().isValid())
2340       notePreviousDefinition(OldD, New->getLocation());
2341 
2342     return New->setInvalidDecl();
2343   }
2344 
2345   // If the old declaration is invalid, just give up here.
2346   if (Old->isInvalidDecl())
2347     return New->setInvalidDecl();
2348 
2349   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2350     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2351     auto *NewTag = New->getAnonDeclWithTypedefName();
2352     NamedDecl *Hidden = nullptr;
2353     if (OldTag && NewTag &&
2354         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2355         !hasVisibleDefinition(OldTag, &Hidden)) {
2356       // There is a definition of this tag, but it is not visible. Use it
2357       // instead of our tag.
2358       New->setTypeForDecl(OldTD->getTypeForDecl());
2359       if (OldTD->isModed())
2360         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2361                                     OldTD->getUnderlyingType());
2362       else
2363         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2364 
2365       // Make the old tag definition visible.
2366       makeMergedDefinitionVisible(Hidden);
2367 
2368       // If this was an unscoped enumeration, yank all of its enumerators
2369       // out of the scope.
2370       if (isa<EnumDecl>(NewTag)) {
2371         Scope *EnumScope = getNonFieldDeclScope(S);
2372         for (auto *D : NewTag->decls()) {
2373           auto *ED = cast<EnumConstantDecl>(D);
2374           assert(EnumScope->isDeclScope(ED));
2375           EnumScope->RemoveDecl(ED);
2376           IdResolver.RemoveDecl(ED);
2377           ED->getLexicalDeclContext()->removeDecl(ED);
2378         }
2379       }
2380     }
2381   }
2382 
2383   // If the typedef types are not identical, reject them in all languages and
2384   // with any extensions enabled.
2385   if (isIncompatibleTypedef(Old, New))
2386     return;
2387 
2388   // The types match.  Link up the redeclaration chain and merge attributes if
2389   // the old declaration was a typedef.
2390   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2391     New->setPreviousDecl(Typedef);
2392     mergeDeclAttributes(New, Old);
2393   }
2394 
2395   if (getLangOpts().MicrosoftExt)
2396     return;
2397 
2398   if (getLangOpts().CPlusPlus) {
2399     // C++ [dcl.typedef]p2:
2400     //   In a given non-class scope, a typedef specifier can be used to
2401     //   redefine the name of any type declared in that scope to refer
2402     //   to the type to which it already refers.
2403     if (!isa<CXXRecordDecl>(CurContext))
2404       return;
2405 
2406     // C++0x [dcl.typedef]p4:
2407     //   In a given class scope, a typedef specifier can be used to redefine
2408     //   any class-name declared in that scope that is not also a typedef-name
2409     //   to refer to the type to which it already refers.
2410     //
2411     // This wording came in via DR424, which was a correction to the
2412     // wording in DR56, which accidentally banned code like:
2413     //
2414     //   struct S {
2415     //     typedef struct A { } A;
2416     //   };
2417     //
2418     // in the C++03 standard. We implement the C++0x semantics, which
2419     // allow the above but disallow
2420     //
2421     //   struct S {
2422     //     typedef int I;
2423     //     typedef int I;
2424     //   };
2425     //
2426     // since that was the intent of DR56.
2427     if (!isa<TypedefNameDecl>(Old))
2428       return;
2429 
2430     Diag(New->getLocation(), diag::err_redefinition)
2431       << New->getDeclName();
2432     notePreviousDefinition(Old, New->getLocation());
2433     return New->setInvalidDecl();
2434   }
2435 
2436   // Modules always permit redefinition of typedefs, as does C11.
2437   if (getLangOpts().Modules || getLangOpts().C11)
2438     return;
2439 
2440   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2441   // is normally mapped to an error, but can be controlled with
2442   // -Wtypedef-redefinition.  If either the original or the redefinition is
2443   // in a system header, don't emit this for compatibility with GCC.
2444   if (getDiagnostics().getSuppressSystemWarnings() &&
2445       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2446       (Old->isImplicit() ||
2447        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2448        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2449     return;
2450 
2451   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2452     << New->getDeclName();
2453   notePreviousDefinition(Old, New->getLocation());
2454 }
2455 
2456 /// DeclhasAttr - returns true if decl Declaration already has the target
2457 /// attribute.
2458 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2459   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2460   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2461   for (const auto *i : D->attrs())
2462     if (i->getKind() == A->getKind()) {
2463       if (Ann) {
2464         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2465           return true;
2466         continue;
2467       }
2468       // FIXME: Don't hardcode this check
2469       if (OA && isa<OwnershipAttr>(i))
2470         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2471       return true;
2472     }
2473 
2474   return false;
2475 }
2476 
2477 static bool isAttributeTargetADefinition(Decl *D) {
2478   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2479     return VD->isThisDeclarationADefinition();
2480   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2481     return TD->isCompleteDefinition() || TD->isBeingDefined();
2482   return true;
2483 }
2484 
2485 /// Merge alignment attributes from \p Old to \p New, taking into account the
2486 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2487 ///
2488 /// \return \c true if any attributes were added to \p New.
2489 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2490   // Look for alignas attributes on Old, and pick out whichever attribute
2491   // specifies the strictest alignment requirement.
2492   AlignedAttr *OldAlignasAttr = nullptr;
2493   AlignedAttr *OldStrictestAlignAttr = nullptr;
2494   unsigned OldAlign = 0;
2495   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2496     // FIXME: We have no way of representing inherited dependent alignments
2497     // in a case like:
2498     //   template<int A, int B> struct alignas(A) X;
2499     //   template<int A, int B> struct alignas(B) X {};
2500     // For now, we just ignore any alignas attributes which are not on the
2501     // definition in such a case.
2502     if (I->isAlignmentDependent())
2503       return false;
2504 
2505     if (I->isAlignas())
2506       OldAlignasAttr = I;
2507 
2508     unsigned Align = I->getAlignment(S.Context);
2509     if (Align > OldAlign) {
2510       OldAlign = Align;
2511       OldStrictestAlignAttr = I;
2512     }
2513   }
2514 
2515   // Look for alignas attributes on New.
2516   AlignedAttr *NewAlignasAttr = nullptr;
2517   unsigned NewAlign = 0;
2518   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2519     if (I->isAlignmentDependent())
2520       return false;
2521 
2522     if (I->isAlignas())
2523       NewAlignasAttr = I;
2524 
2525     unsigned Align = I->getAlignment(S.Context);
2526     if (Align > NewAlign)
2527       NewAlign = Align;
2528   }
2529 
2530   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2531     // Both declarations have 'alignas' attributes. We require them to match.
2532     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2533     // fall short. (If two declarations both have alignas, they must both match
2534     // every definition, and so must match each other if there is a definition.)
2535 
2536     // If either declaration only contains 'alignas(0)' specifiers, then it
2537     // specifies the natural alignment for the type.
2538     if (OldAlign == 0 || NewAlign == 0) {
2539       QualType Ty;
2540       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2541         Ty = VD->getType();
2542       else
2543         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2544 
2545       if (OldAlign == 0)
2546         OldAlign = S.Context.getTypeAlign(Ty);
2547       if (NewAlign == 0)
2548         NewAlign = S.Context.getTypeAlign(Ty);
2549     }
2550 
2551     if (OldAlign != NewAlign) {
2552       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2553         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2554         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2555       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2556     }
2557   }
2558 
2559   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2560     // C++11 [dcl.align]p6:
2561     //   if any declaration of an entity has an alignment-specifier,
2562     //   every defining declaration of that entity shall specify an
2563     //   equivalent alignment.
2564     // C11 6.7.5/7:
2565     //   If the definition of an object does not have an alignment
2566     //   specifier, any other declaration of that object shall also
2567     //   have no alignment specifier.
2568     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2569       << OldAlignasAttr;
2570     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2571       << OldAlignasAttr;
2572   }
2573 
2574   bool AnyAdded = false;
2575 
2576   // Ensure we have an attribute representing the strictest alignment.
2577   if (OldAlign > NewAlign) {
2578     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2579     Clone->setInherited(true);
2580     New->addAttr(Clone);
2581     AnyAdded = true;
2582   }
2583 
2584   // Ensure we have an alignas attribute if the old declaration had one.
2585   if (OldAlignasAttr && !NewAlignasAttr &&
2586       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2587     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2588     Clone->setInherited(true);
2589     New->addAttr(Clone);
2590     AnyAdded = true;
2591   }
2592 
2593   return AnyAdded;
2594 }
2595 
2596 #define WANT_DECL_MERGE_LOGIC
2597 #include "clang/Sema/AttrParsedAttrImpl.inc"
2598 #undef WANT_DECL_MERGE_LOGIC
2599 
2600 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2601                                const InheritableAttr *Attr,
2602                                Sema::AvailabilityMergeKind AMK) {
2603   // Diagnose any mutual exclusions between the attribute that we want to add
2604   // and attributes that already exist on the declaration.
2605   if (!DiagnoseMutualExclusions(S, D, Attr))
2606     return false;
2607 
2608   // This function copies an attribute Attr from a previous declaration to the
2609   // new declaration D if the new declaration doesn't itself have that attribute
2610   // yet or if that attribute allows duplicates.
2611   // If you're adding a new attribute that requires logic different from
2612   // "use explicit attribute on decl if present, else use attribute from
2613   // previous decl", for example if the attribute needs to be consistent
2614   // between redeclarations, you need to call a custom merge function here.
2615   InheritableAttr *NewAttr = nullptr;
2616   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2617     NewAttr = S.mergeAvailabilityAttr(
2618         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2619         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2620         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2621         AA->getPriority());
2622   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2623     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2624   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2625     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2626   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2627     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2628   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2629     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2630   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2631     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2632                                 FA->getFirstArg());
2633   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2634     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2635   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2636     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2637   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2638     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2639                                        IA->getInheritanceModel());
2640   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2641     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2642                                       &S.Context.Idents.get(AA->getSpelling()));
2643   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2644            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2645             isa<CUDAGlobalAttr>(Attr))) {
2646     // CUDA target attributes are part of function signature for
2647     // overloading purposes and must not be merged.
2648     return false;
2649   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2650     NewAttr = S.mergeMinSizeAttr(D, *MA);
2651   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2652     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2653   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2654     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2655   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2656     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2657   else if (isa<AlignedAttr>(Attr))
2658     // AlignedAttrs are handled separately, because we need to handle all
2659     // such attributes on a declaration at the same time.
2660     NewAttr = nullptr;
2661   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2662            (AMK == Sema::AMK_Override ||
2663             AMK == Sema::AMK_ProtocolImplementation ||
2664             AMK == Sema::AMK_OptionalProtocolImplementation))
2665     NewAttr = nullptr;
2666   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2667     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2668   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2669     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2670   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2671     NewAttr = S.mergeImportNameAttr(D, *INA);
2672   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2673     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2674   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2675     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2676   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2677     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2678 
2679   if (NewAttr) {
2680     NewAttr->setInherited(true);
2681     D->addAttr(NewAttr);
2682     if (isa<MSInheritanceAttr>(NewAttr))
2683       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2684     return true;
2685   }
2686 
2687   return false;
2688 }
2689 
2690 static const NamedDecl *getDefinition(const Decl *D) {
2691   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2692     return TD->getDefinition();
2693   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2694     const VarDecl *Def = VD->getDefinition();
2695     if (Def)
2696       return Def;
2697     return VD->getActingDefinition();
2698   }
2699   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2700     const FunctionDecl *Def = nullptr;
2701     if (FD->isDefined(Def, true))
2702       return Def;
2703   }
2704   return nullptr;
2705 }
2706 
2707 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2708   for (const auto *Attribute : D->attrs())
2709     if (Attribute->getKind() == Kind)
2710       return true;
2711   return false;
2712 }
2713 
2714 /// checkNewAttributesAfterDef - If we already have a definition, check that
2715 /// there are no new attributes in this declaration.
2716 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2717   if (!New->hasAttrs())
2718     return;
2719 
2720   const NamedDecl *Def = getDefinition(Old);
2721   if (!Def || Def == New)
2722     return;
2723 
2724   AttrVec &NewAttributes = New->getAttrs();
2725   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2726     const Attr *NewAttribute = NewAttributes[I];
2727 
2728     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2729       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2730         Sema::SkipBodyInfo SkipBody;
2731         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2732 
2733         // If we're skipping this definition, drop the "alias" attribute.
2734         if (SkipBody.ShouldSkip) {
2735           NewAttributes.erase(NewAttributes.begin() + I);
2736           --E;
2737           continue;
2738         }
2739       } else {
2740         VarDecl *VD = cast<VarDecl>(New);
2741         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2742                                 VarDecl::TentativeDefinition
2743                             ? diag::err_alias_after_tentative
2744                             : diag::err_redefinition;
2745         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2746         if (Diag == diag::err_redefinition)
2747           S.notePreviousDefinition(Def, VD->getLocation());
2748         else
2749           S.Diag(Def->getLocation(), diag::note_previous_definition);
2750         VD->setInvalidDecl();
2751       }
2752       ++I;
2753       continue;
2754     }
2755 
2756     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2757       // Tentative definitions are only interesting for the alias check above.
2758       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2759         ++I;
2760         continue;
2761       }
2762     }
2763 
2764     if (hasAttribute(Def, NewAttribute->getKind())) {
2765       ++I;
2766       continue; // regular attr merging will take care of validating this.
2767     }
2768 
2769     if (isa<C11NoReturnAttr>(NewAttribute)) {
2770       // C's _Noreturn is allowed to be added to a function after it is defined.
2771       ++I;
2772       continue;
2773     } else if (isa<UuidAttr>(NewAttribute)) {
2774       // msvc will allow a subsequent definition to add an uuid to a class
2775       ++I;
2776       continue;
2777     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2778       if (AA->isAlignas()) {
2779         // C++11 [dcl.align]p6:
2780         //   if any declaration of an entity has an alignment-specifier,
2781         //   every defining declaration of that entity shall specify an
2782         //   equivalent alignment.
2783         // C11 6.7.5/7:
2784         //   If the definition of an object does not have an alignment
2785         //   specifier, any other declaration of that object shall also
2786         //   have no alignment specifier.
2787         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2788           << AA;
2789         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2790           << AA;
2791         NewAttributes.erase(NewAttributes.begin() + I);
2792         --E;
2793         continue;
2794       }
2795     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2796       // If there is a C definition followed by a redeclaration with this
2797       // attribute then there are two different definitions. In C++, prefer the
2798       // standard diagnostics.
2799       if (!S.getLangOpts().CPlusPlus) {
2800         S.Diag(NewAttribute->getLocation(),
2801                diag::err_loader_uninitialized_redeclaration);
2802         S.Diag(Def->getLocation(), diag::note_previous_definition);
2803         NewAttributes.erase(NewAttributes.begin() + I);
2804         --E;
2805         continue;
2806       }
2807     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2808                cast<VarDecl>(New)->isInline() &&
2809                !cast<VarDecl>(New)->isInlineSpecified()) {
2810       // Don't warn about applying selectany to implicitly inline variables.
2811       // Older compilers and language modes would require the use of selectany
2812       // to make such variables inline, and it would have no effect if we
2813       // honored it.
2814       ++I;
2815       continue;
2816     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2817       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2818       // declarations after defintions.
2819       ++I;
2820       continue;
2821     }
2822 
2823     S.Diag(NewAttribute->getLocation(),
2824            diag::warn_attribute_precede_definition);
2825     S.Diag(Def->getLocation(), diag::note_previous_definition);
2826     NewAttributes.erase(NewAttributes.begin() + I);
2827     --E;
2828   }
2829 }
2830 
2831 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2832                                      const ConstInitAttr *CIAttr,
2833                                      bool AttrBeforeInit) {
2834   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2835 
2836   // Figure out a good way to write this specifier on the old declaration.
2837   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2838   // enough of the attribute list spelling information to extract that without
2839   // heroics.
2840   std::string SuitableSpelling;
2841   if (S.getLangOpts().CPlusPlus20)
2842     SuitableSpelling = std::string(
2843         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2844   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2845     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2846         InsertLoc, {tok::l_square, tok::l_square,
2847                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2848                     S.PP.getIdentifierInfo("require_constant_initialization"),
2849                     tok::r_square, tok::r_square}));
2850   if (SuitableSpelling.empty())
2851     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2852         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2853                     S.PP.getIdentifierInfo("require_constant_initialization"),
2854                     tok::r_paren, tok::r_paren}));
2855   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2856     SuitableSpelling = "constinit";
2857   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2858     SuitableSpelling = "[[clang::require_constant_initialization]]";
2859   if (SuitableSpelling.empty())
2860     SuitableSpelling = "__attribute__((require_constant_initialization))";
2861   SuitableSpelling += " ";
2862 
2863   if (AttrBeforeInit) {
2864     // extern constinit int a;
2865     // int a = 0; // error (missing 'constinit'), accepted as extension
2866     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2867     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2868         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2869     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2870   } else {
2871     // int a = 0;
2872     // constinit extern int a; // error (missing 'constinit')
2873     S.Diag(CIAttr->getLocation(),
2874            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2875                                  : diag::warn_require_const_init_added_too_late)
2876         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2877     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2878         << CIAttr->isConstinit()
2879         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2880   }
2881 }
2882 
2883 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2884 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2885                                AvailabilityMergeKind AMK) {
2886   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2887     UsedAttr *NewAttr = OldAttr->clone(Context);
2888     NewAttr->setInherited(true);
2889     New->addAttr(NewAttr);
2890   }
2891   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2892     RetainAttr *NewAttr = OldAttr->clone(Context);
2893     NewAttr->setInherited(true);
2894     New->addAttr(NewAttr);
2895   }
2896 
2897   if (!Old->hasAttrs() && !New->hasAttrs())
2898     return;
2899 
2900   // [dcl.constinit]p1:
2901   //   If the [constinit] specifier is applied to any declaration of a
2902   //   variable, it shall be applied to the initializing declaration.
2903   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2904   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2905   if (bool(OldConstInit) != bool(NewConstInit)) {
2906     const auto *OldVD = cast<VarDecl>(Old);
2907     auto *NewVD = cast<VarDecl>(New);
2908 
2909     // Find the initializing declaration. Note that we might not have linked
2910     // the new declaration into the redeclaration chain yet.
2911     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2912     if (!InitDecl &&
2913         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2914       InitDecl = NewVD;
2915 
2916     if (InitDecl == NewVD) {
2917       // This is the initializing declaration. If it would inherit 'constinit',
2918       // that's ill-formed. (Note that we do not apply this to the attribute
2919       // form).
2920       if (OldConstInit && OldConstInit->isConstinit())
2921         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2922                                  /*AttrBeforeInit=*/true);
2923     } else if (NewConstInit) {
2924       // This is the first time we've been told that this declaration should
2925       // have a constant initializer. If we already saw the initializing
2926       // declaration, this is too late.
2927       if (InitDecl && InitDecl != NewVD) {
2928         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2929                                  /*AttrBeforeInit=*/false);
2930         NewVD->dropAttr<ConstInitAttr>();
2931       }
2932     }
2933   }
2934 
2935   // Attributes declared post-definition are currently ignored.
2936   checkNewAttributesAfterDef(*this, New, Old);
2937 
2938   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2939     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2940       if (!OldA->isEquivalent(NewA)) {
2941         // This redeclaration changes __asm__ label.
2942         Diag(New->getLocation(), diag::err_different_asm_label);
2943         Diag(OldA->getLocation(), diag::note_previous_declaration);
2944       }
2945     } else if (Old->isUsed()) {
2946       // This redeclaration adds an __asm__ label to a declaration that has
2947       // already been ODR-used.
2948       Diag(New->getLocation(), diag::err_late_asm_label_name)
2949         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2950     }
2951   }
2952 
2953   // Re-declaration cannot add abi_tag's.
2954   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2955     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2956       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2957         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2958                       NewTag) == OldAbiTagAttr->tags_end()) {
2959           Diag(NewAbiTagAttr->getLocation(),
2960                diag::err_new_abi_tag_on_redeclaration)
2961               << NewTag;
2962           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2963         }
2964       }
2965     } else {
2966       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2967       Diag(Old->getLocation(), diag::note_previous_declaration);
2968     }
2969   }
2970 
2971   // This redeclaration adds a section attribute.
2972   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2973     if (auto *VD = dyn_cast<VarDecl>(New)) {
2974       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2975         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2976         Diag(Old->getLocation(), diag::note_previous_declaration);
2977       }
2978     }
2979   }
2980 
2981   // Redeclaration adds code-seg attribute.
2982   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2983   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2984       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2985     Diag(New->getLocation(), diag::warn_mismatched_section)
2986          << 0 /*codeseg*/;
2987     Diag(Old->getLocation(), diag::note_previous_declaration);
2988   }
2989 
2990   if (!Old->hasAttrs())
2991     return;
2992 
2993   bool foundAny = New->hasAttrs();
2994 
2995   // Ensure that any moving of objects within the allocated map is done before
2996   // we process them.
2997   if (!foundAny) New->setAttrs(AttrVec());
2998 
2999   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3000     // Ignore deprecated/unavailable/availability attributes if requested.
3001     AvailabilityMergeKind LocalAMK = AMK_None;
3002     if (isa<DeprecatedAttr>(I) ||
3003         isa<UnavailableAttr>(I) ||
3004         isa<AvailabilityAttr>(I)) {
3005       switch (AMK) {
3006       case AMK_None:
3007         continue;
3008 
3009       case AMK_Redeclaration:
3010       case AMK_Override:
3011       case AMK_ProtocolImplementation:
3012       case AMK_OptionalProtocolImplementation:
3013         LocalAMK = AMK;
3014         break;
3015       }
3016     }
3017 
3018     // Already handled.
3019     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3020       continue;
3021 
3022     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3023       foundAny = true;
3024   }
3025 
3026   if (mergeAlignedAttrs(*this, New, Old))
3027     foundAny = true;
3028 
3029   if (!foundAny) New->dropAttrs();
3030 }
3031 
3032 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3033 /// to the new one.
3034 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3035                                      const ParmVarDecl *oldDecl,
3036                                      Sema &S) {
3037   // C++11 [dcl.attr.depend]p2:
3038   //   The first declaration of a function shall specify the
3039   //   carries_dependency attribute for its declarator-id if any declaration
3040   //   of the function specifies the carries_dependency attribute.
3041   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3042   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3043     S.Diag(CDA->getLocation(),
3044            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3045     // Find the first declaration of the parameter.
3046     // FIXME: Should we build redeclaration chains for function parameters?
3047     const FunctionDecl *FirstFD =
3048       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3049     const ParmVarDecl *FirstVD =
3050       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3051     S.Diag(FirstVD->getLocation(),
3052            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3053   }
3054 
3055   if (!oldDecl->hasAttrs())
3056     return;
3057 
3058   bool foundAny = newDecl->hasAttrs();
3059 
3060   // Ensure that any moving of objects within the allocated map is
3061   // done before we process them.
3062   if (!foundAny) newDecl->setAttrs(AttrVec());
3063 
3064   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3065     if (!DeclHasAttr(newDecl, I)) {
3066       InheritableAttr *newAttr =
3067         cast<InheritableParamAttr>(I->clone(S.Context));
3068       newAttr->setInherited(true);
3069       newDecl->addAttr(newAttr);
3070       foundAny = true;
3071     }
3072   }
3073 
3074   if (!foundAny) newDecl->dropAttrs();
3075 }
3076 
3077 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3078                                 const ParmVarDecl *OldParam,
3079                                 Sema &S) {
3080   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3081     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3082       if (*Oldnullability != *Newnullability) {
3083         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3084           << DiagNullabilityKind(
3085                *Newnullability,
3086                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3087                 != 0))
3088           << DiagNullabilityKind(
3089                *Oldnullability,
3090                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3091                 != 0));
3092         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3093       }
3094     } else {
3095       QualType NewT = NewParam->getType();
3096       NewT = S.Context.getAttributedType(
3097                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3098                          NewT, NewT);
3099       NewParam->setType(NewT);
3100     }
3101   }
3102 }
3103 
3104 namespace {
3105 
3106 /// Used in MergeFunctionDecl to keep track of function parameters in
3107 /// C.
3108 struct GNUCompatibleParamWarning {
3109   ParmVarDecl *OldParm;
3110   ParmVarDecl *NewParm;
3111   QualType PromotedType;
3112 };
3113 
3114 } // end anonymous namespace
3115 
3116 // Determine whether the previous declaration was a definition, implicit
3117 // declaration, or a declaration.
3118 template <typename T>
3119 static std::pair<diag::kind, SourceLocation>
3120 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3121   diag::kind PrevDiag;
3122   SourceLocation OldLocation = Old->getLocation();
3123   if (Old->isThisDeclarationADefinition())
3124     PrevDiag = diag::note_previous_definition;
3125   else if (Old->isImplicit()) {
3126     PrevDiag = diag::note_previous_implicit_declaration;
3127     if (OldLocation.isInvalid())
3128       OldLocation = New->getLocation();
3129   } else
3130     PrevDiag = diag::note_previous_declaration;
3131   return std::make_pair(PrevDiag, OldLocation);
3132 }
3133 
3134 /// canRedefineFunction - checks if a function can be redefined. Currently,
3135 /// only extern inline functions can be redefined, and even then only in
3136 /// GNU89 mode.
3137 static bool canRedefineFunction(const FunctionDecl *FD,
3138                                 const LangOptions& LangOpts) {
3139   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3140           !LangOpts.CPlusPlus &&
3141           FD->isInlineSpecified() &&
3142           FD->getStorageClass() == SC_Extern);
3143 }
3144 
3145 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3146   const AttributedType *AT = T->getAs<AttributedType>();
3147   while (AT && !AT->isCallingConv())
3148     AT = AT->getModifiedType()->getAs<AttributedType>();
3149   return AT;
3150 }
3151 
3152 template <typename T>
3153 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3154   const DeclContext *DC = Old->getDeclContext();
3155   if (DC->isRecord())
3156     return false;
3157 
3158   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3159   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3160     return true;
3161   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3162     return true;
3163   return false;
3164 }
3165 
3166 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3167 static bool isExternC(VarTemplateDecl *) { return false; }
3168 
3169 /// Check whether a redeclaration of an entity introduced by a
3170 /// using-declaration is valid, given that we know it's not an overload
3171 /// (nor a hidden tag declaration).
3172 template<typename ExpectedDecl>
3173 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3174                                    ExpectedDecl *New) {
3175   // C++11 [basic.scope.declarative]p4:
3176   //   Given a set of declarations in a single declarative region, each of
3177   //   which specifies the same unqualified name,
3178   //   -- they shall all refer to the same entity, or all refer to functions
3179   //      and function templates; or
3180   //   -- exactly one declaration shall declare a class name or enumeration
3181   //      name that is not a typedef name and the other declarations shall all
3182   //      refer to the same variable or enumerator, or all refer to functions
3183   //      and function templates; in this case the class name or enumeration
3184   //      name is hidden (3.3.10).
3185 
3186   // C++11 [namespace.udecl]p14:
3187   //   If a function declaration in namespace scope or block scope has the
3188   //   same name and the same parameter-type-list as a function introduced
3189   //   by a using-declaration, and the declarations do not declare the same
3190   //   function, the program is ill-formed.
3191 
3192   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3193   if (Old &&
3194       !Old->getDeclContext()->getRedeclContext()->Equals(
3195           New->getDeclContext()->getRedeclContext()) &&
3196       !(isExternC(Old) && isExternC(New)))
3197     Old = nullptr;
3198 
3199   if (!Old) {
3200     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3201     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3202     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3203     return true;
3204   }
3205   return false;
3206 }
3207 
3208 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3209                                             const FunctionDecl *B) {
3210   assert(A->getNumParams() == B->getNumParams());
3211 
3212   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3213     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3214     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3215     if (AttrA == AttrB)
3216       return true;
3217     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3218            AttrA->isDynamic() == AttrB->isDynamic();
3219   };
3220 
3221   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3222 }
3223 
3224 /// If necessary, adjust the semantic declaration context for a qualified
3225 /// declaration to name the correct inline namespace within the qualifier.
3226 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3227                                                DeclaratorDecl *OldD) {
3228   // The only case where we need to update the DeclContext is when
3229   // redeclaration lookup for a qualified name finds a declaration
3230   // in an inline namespace within the context named by the qualifier:
3231   //
3232   //   inline namespace N { int f(); }
3233   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3234   //
3235   // For unqualified declarations, the semantic context *can* change
3236   // along the redeclaration chain (for local extern declarations,
3237   // extern "C" declarations, and friend declarations in particular).
3238   if (!NewD->getQualifier())
3239     return;
3240 
3241   // NewD is probably already in the right context.
3242   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3243   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3244   if (NamedDC->Equals(SemaDC))
3245     return;
3246 
3247   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3248           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3249          "unexpected context for redeclaration");
3250 
3251   auto *LexDC = NewD->getLexicalDeclContext();
3252   auto FixSemaDC = [=](NamedDecl *D) {
3253     if (!D)
3254       return;
3255     D->setDeclContext(SemaDC);
3256     D->setLexicalDeclContext(LexDC);
3257   };
3258 
3259   FixSemaDC(NewD);
3260   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3261     FixSemaDC(FD->getDescribedFunctionTemplate());
3262   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3263     FixSemaDC(VD->getDescribedVarTemplate());
3264 }
3265 
3266 /// MergeFunctionDecl - We just parsed a function 'New' from
3267 /// declarator D which has the same name and scope as a previous
3268 /// declaration 'Old'.  Figure out how to resolve this situation,
3269 /// merging decls or emitting diagnostics as appropriate.
3270 ///
3271 /// In C++, New and Old must be declarations that are not
3272 /// overloaded. Use IsOverload to determine whether New and Old are
3273 /// overloaded, and to select the Old declaration that New should be
3274 /// merged with.
3275 ///
3276 /// Returns true if there was an error, false otherwise.
3277 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3278                              Scope *S, bool MergeTypeWithOld) {
3279   // Verify the old decl was also a function.
3280   FunctionDecl *Old = OldD->getAsFunction();
3281   if (!Old) {
3282     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3283       if (New->getFriendObjectKind()) {
3284         Diag(New->getLocation(), diag::err_using_decl_friend);
3285         Diag(Shadow->getTargetDecl()->getLocation(),
3286              diag::note_using_decl_target);
3287         Diag(Shadow->getUsingDecl()->getLocation(),
3288              diag::note_using_decl) << 0;
3289         return true;
3290       }
3291 
3292       // Check whether the two declarations might declare the same function.
3293       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3294         return true;
3295       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3296     } else {
3297       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3298         << New->getDeclName();
3299       notePreviousDefinition(OldD, New->getLocation());
3300       return true;
3301     }
3302   }
3303 
3304   // If the old declaration was found in an inline namespace and the new
3305   // declaration was qualified, update the DeclContext to match.
3306   adjustDeclContextForDeclaratorDecl(New, Old);
3307 
3308   // If the old declaration is invalid, just give up here.
3309   if (Old->isInvalidDecl())
3310     return true;
3311 
3312   // Disallow redeclaration of some builtins.
3313   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3314     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3315     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3316         << Old << Old->getType();
3317     return true;
3318   }
3319 
3320   diag::kind PrevDiag;
3321   SourceLocation OldLocation;
3322   std::tie(PrevDiag, OldLocation) =
3323       getNoteDiagForInvalidRedeclaration(Old, New);
3324 
3325   // Don't complain about this if we're in GNU89 mode and the old function
3326   // is an extern inline function.
3327   // Don't complain about specializations. They are not supposed to have
3328   // storage classes.
3329   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3330       New->getStorageClass() == SC_Static &&
3331       Old->hasExternalFormalLinkage() &&
3332       !New->getTemplateSpecializationInfo() &&
3333       !canRedefineFunction(Old, getLangOpts())) {
3334     if (getLangOpts().MicrosoftExt) {
3335       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3336       Diag(OldLocation, PrevDiag);
3337     } else {
3338       Diag(New->getLocation(), diag::err_static_non_static) << New;
3339       Diag(OldLocation, PrevDiag);
3340       return true;
3341     }
3342   }
3343 
3344   if (New->hasAttr<InternalLinkageAttr>() &&
3345       !Old->hasAttr<InternalLinkageAttr>()) {
3346     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3347         << New->getDeclName();
3348     notePreviousDefinition(Old, New->getLocation());
3349     New->dropAttr<InternalLinkageAttr>();
3350   }
3351 
3352   if (CheckRedeclarationModuleOwnership(New, Old))
3353     return true;
3354 
3355   if (!getLangOpts().CPlusPlus) {
3356     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3357     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3358       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3359         << New << OldOvl;
3360 
3361       // Try our best to find a decl that actually has the overloadable
3362       // attribute for the note. In most cases (e.g. programs with only one
3363       // broken declaration/definition), this won't matter.
3364       //
3365       // FIXME: We could do this if we juggled some extra state in
3366       // OverloadableAttr, rather than just removing it.
3367       const Decl *DiagOld = Old;
3368       if (OldOvl) {
3369         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3370           const auto *A = D->getAttr<OverloadableAttr>();
3371           return A && !A->isImplicit();
3372         });
3373         // If we've implicitly added *all* of the overloadable attrs to this
3374         // chain, emitting a "previous redecl" note is pointless.
3375         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3376       }
3377 
3378       if (DiagOld)
3379         Diag(DiagOld->getLocation(),
3380              diag::note_attribute_overloadable_prev_overload)
3381           << OldOvl;
3382 
3383       if (OldOvl)
3384         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3385       else
3386         New->dropAttr<OverloadableAttr>();
3387     }
3388   }
3389 
3390   // If a function is first declared with a calling convention, but is later
3391   // declared or defined without one, all following decls assume the calling
3392   // convention of the first.
3393   //
3394   // It's OK if a function is first declared without a calling convention,
3395   // but is later declared or defined with the default calling convention.
3396   //
3397   // To test if either decl has an explicit calling convention, we look for
3398   // AttributedType sugar nodes on the type as written.  If they are missing or
3399   // were canonicalized away, we assume the calling convention was implicit.
3400   //
3401   // Note also that we DO NOT return at this point, because we still have
3402   // other tests to run.
3403   QualType OldQType = Context.getCanonicalType(Old->getType());
3404   QualType NewQType = Context.getCanonicalType(New->getType());
3405   const FunctionType *OldType = cast<FunctionType>(OldQType);
3406   const FunctionType *NewType = cast<FunctionType>(NewQType);
3407   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3408   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3409   bool RequiresAdjustment = false;
3410 
3411   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3412     FunctionDecl *First = Old->getFirstDecl();
3413     const FunctionType *FT =
3414         First->getType().getCanonicalType()->castAs<FunctionType>();
3415     FunctionType::ExtInfo FI = FT->getExtInfo();
3416     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3417     if (!NewCCExplicit) {
3418       // Inherit the CC from the previous declaration if it was specified
3419       // there but not here.
3420       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3421       RequiresAdjustment = true;
3422     } else if (Old->getBuiltinID()) {
3423       // Builtin attribute isn't propagated to the new one yet at this point,
3424       // so we check if the old one is a builtin.
3425 
3426       // Calling Conventions on a Builtin aren't really useful and setting a
3427       // default calling convention and cdecl'ing some builtin redeclarations is
3428       // common, so warn and ignore the calling convention on the redeclaration.
3429       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3430           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3431           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3432       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3433       RequiresAdjustment = true;
3434     } else {
3435       // Calling conventions aren't compatible, so complain.
3436       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3437       Diag(New->getLocation(), diag::err_cconv_change)
3438         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3439         << !FirstCCExplicit
3440         << (!FirstCCExplicit ? "" :
3441             FunctionType::getNameForCallConv(FI.getCC()));
3442 
3443       // Put the note on the first decl, since it is the one that matters.
3444       Diag(First->getLocation(), diag::note_previous_declaration);
3445       return true;
3446     }
3447   }
3448 
3449   // FIXME: diagnose the other way around?
3450   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3451     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3452     RequiresAdjustment = true;
3453   }
3454 
3455   // Merge regparm attribute.
3456   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3457       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3458     if (NewTypeInfo.getHasRegParm()) {
3459       Diag(New->getLocation(), diag::err_regparm_mismatch)
3460         << NewType->getRegParmType()
3461         << OldType->getRegParmType();
3462       Diag(OldLocation, diag::note_previous_declaration);
3463       return true;
3464     }
3465 
3466     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3467     RequiresAdjustment = true;
3468   }
3469 
3470   // Merge ns_returns_retained attribute.
3471   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3472     if (NewTypeInfo.getProducesResult()) {
3473       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3474           << "'ns_returns_retained'";
3475       Diag(OldLocation, diag::note_previous_declaration);
3476       return true;
3477     }
3478 
3479     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3480     RequiresAdjustment = true;
3481   }
3482 
3483   if (OldTypeInfo.getNoCallerSavedRegs() !=
3484       NewTypeInfo.getNoCallerSavedRegs()) {
3485     if (NewTypeInfo.getNoCallerSavedRegs()) {
3486       AnyX86NoCallerSavedRegistersAttr *Attr =
3487         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3488       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3489       Diag(OldLocation, diag::note_previous_declaration);
3490       return true;
3491     }
3492 
3493     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3494     RequiresAdjustment = true;
3495   }
3496 
3497   if (RequiresAdjustment) {
3498     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3499     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3500     New->setType(QualType(AdjustedType, 0));
3501     NewQType = Context.getCanonicalType(New->getType());
3502   }
3503 
3504   // If this redeclaration makes the function inline, we may need to add it to
3505   // UndefinedButUsed.
3506   if (!Old->isInlined() && New->isInlined() &&
3507       !New->hasAttr<GNUInlineAttr>() &&
3508       !getLangOpts().GNUInline &&
3509       Old->isUsed(false) &&
3510       !Old->isDefined() && !New->isThisDeclarationADefinition())
3511     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3512                                            SourceLocation()));
3513 
3514   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3515   // about it.
3516   if (New->hasAttr<GNUInlineAttr>() &&
3517       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3518     UndefinedButUsed.erase(Old->getCanonicalDecl());
3519   }
3520 
3521   // If pass_object_size params don't match up perfectly, this isn't a valid
3522   // redeclaration.
3523   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3524       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3525     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3526         << New->getDeclName();
3527     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3528     return true;
3529   }
3530 
3531   if (getLangOpts().CPlusPlus) {
3532     // C++1z [over.load]p2
3533     //   Certain function declarations cannot be overloaded:
3534     //     -- Function declarations that differ only in the return type,
3535     //        the exception specification, or both cannot be overloaded.
3536 
3537     // Check the exception specifications match. This may recompute the type of
3538     // both Old and New if it resolved exception specifications, so grab the
3539     // types again after this. Because this updates the type, we do this before
3540     // any of the other checks below, which may update the "de facto" NewQType
3541     // but do not necessarily update the type of New.
3542     if (CheckEquivalentExceptionSpec(Old, New))
3543       return true;
3544     OldQType = Context.getCanonicalType(Old->getType());
3545     NewQType = Context.getCanonicalType(New->getType());
3546 
3547     // Go back to the type source info to compare the declared return types,
3548     // per C++1y [dcl.type.auto]p13:
3549     //   Redeclarations or specializations of a function or function template
3550     //   with a declared return type that uses a placeholder type shall also
3551     //   use that placeholder, not a deduced type.
3552     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3553     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3554     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3555         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3556                                        OldDeclaredReturnType)) {
3557       QualType ResQT;
3558       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3559           OldDeclaredReturnType->isObjCObjectPointerType())
3560         // FIXME: This does the wrong thing for a deduced return type.
3561         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3562       if (ResQT.isNull()) {
3563         if (New->isCXXClassMember() && New->isOutOfLine())
3564           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3565               << New << New->getReturnTypeSourceRange();
3566         else
3567           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3568               << New->getReturnTypeSourceRange();
3569         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3570                                     << Old->getReturnTypeSourceRange();
3571         return true;
3572       }
3573       else
3574         NewQType = ResQT;
3575     }
3576 
3577     QualType OldReturnType = OldType->getReturnType();
3578     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3579     if (OldReturnType != NewReturnType) {
3580       // If this function has a deduced return type and has already been
3581       // defined, copy the deduced value from the old declaration.
3582       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3583       if (OldAT && OldAT->isDeduced()) {
3584         New->setType(
3585             SubstAutoType(New->getType(),
3586                           OldAT->isDependentType() ? Context.DependentTy
3587                                                    : OldAT->getDeducedType()));
3588         NewQType = Context.getCanonicalType(
3589             SubstAutoType(NewQType,
3590                           OldAT->isDependentType() ? Context.DependentTy
3591                                                    : OldAT->getDeducedType()));
3592       }
3593     }
3594 
3595     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3596     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3597     if (OldMethod && NewMethod) {
3598       // Preserve triviality.
3599       NewMethod->setTrivial(OldMethod->isTrivial());
3600 
3601       // MSVC allows explicit template specialization at class scope:
3602       // 2 CXXMethodDecls referring to the same function will be injected.
3603       // We don't want a redeclaration error.
3604       bool IsClassScopeExplicitSpecialization =
3605                               OldMethod->isFunctionTemplateSpecialization() &&
3606                               NewMethod->isFunctionTemplateSpecialization();
3607       bool isFriend = NewMethod->getFriendObjectKind();
3608 
3609       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3610           !IsClassScopeExplicitSpecialization) {
3611         //    -- Member function declarations with the same name and the
3612         //       same parameter types cannot be overloaded if any of them
3613         //       is a static member function declaration.
3614         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3615           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3616           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3617           return true;
3618         }
3619 
3620         // C++ [class.mem]p1:
3621         //   [...] A member shall not be declared twice in the
3622         //   member-specification, except that a nested class or member
3623         //   class template can be declared and then later defined.
3624         if (!inTemplateInstantiation()) {
3625           unsigned NewDiag;
3626           if (isa<CXXConstructorDecl>(OldMethod))
3627             NewDiag = diag::err_constructor_redeclared;
3628           else if (isa<CXXDestructorDecl>(NewMethod))
3629             NewDiag = diag::err_destructor_redeclared;
3630           else if (isa<CXXConversionDecl>(NewMethod))
3631             NewDiag = diag::err_conv_function_redeclared;
3632           else
3633             NewDiag = diag::err_member_redeclared;
3634 
3635           Diag(New->getLocation(), NewDiag);
3636         } else {
3637           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3638             << New << New->getType();
3639         }
3640         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3641         return true;
3642 
3643       // Complain if this is an explicit declaration of a special
3644       // member that was initially declared implicitly.
3645       //
3646       // As an exception, it's okay to befriend such methods in order
3647       // to permit the implicit constructor/destructor/operator calls.
3648       } else if (OldMethod->isImplicit()) {
3649         if (isFriend) {
3650           NewMethod->setImplicit();
3651         } else {
3652           Diag(NewMethod->getLocation(),
3653                diag::err_definition_of_implicitly_declared_member)
3654             << New << getSpecialMember(OldMethod);
3655           return true;
3656         }
3657       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3658         Diag(NewMethod->getLocation(),
3659              diag::err_definition_of_explicitly_defaulted_member)
3660           << getSpecialMember(OldMethod);
3661         return true;
3662       }
3663     }
3664 
3665     // C++11 [dcl.attr.noreturn]p1:
3666     //   The first declaration of a function shall specify the noreturn
3667     //   attribute if any declaration of that function specifies the noreturn
3668     //   attribute.
3669     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3670     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3671       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3672       Diag(Old->getFirstDecl()->getLocation(),
3673            diag::note_noreturn_missing_first_decl);
3674     }
3675 
3676     // C++11 [dcl.attr.depend]p2:
3677     //   The first declaration of a function shall specify the
3678     //   carries_dependency attribute for its declarator-id if any declaration
3679     //   of the function specifies the carries_dependency attribute.
3680     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3681     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3682       Diag(CDA->getLocation(),
3683            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3684       Diag(Old->getFirstDecl()->getLocation(),
3685            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3686     }
3687 
3688     // (C++98 8.3.5p3):
3689     //   All declarations for a function shall agree exactly in both the
3690     //   return type and the parameter-type-list.
3691     // We also want to respect all the extended bits except noreturn.
3692 
3693     // noreturn should now match unless the old type info didn't have it.
3694     QualType OldQTypeForComparison = OldQType;
3695     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3696       auto *OldType = OldQType->castAs<FunctionProtoType>();
3697       const FunctionType *OldTypeForComparison
3698         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3699       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3700       assert(OldQTypeForComparison.isCanonical());
3701     }
3702 
3703     if (haveIncompatibleLanguageLinkages(Old, New)) {
3704       // As a special case, retain the language linkage from previous
3705       // declarations of a friend function as an extension.
3706       //
3707       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3708       // and is useful because there's otherwise no way to specify language
3709       // linkage within class scope.
3710       //
3711       // Check cautiously as the friend object kind isn't yet complete.
3712       if (New->getFriendObjectKind() != Decl::FOK_None) {
3713         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3714         Diag(OldLocation, PrevDiag);
3715       } else {
3716         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3717         Diag(OldLocation, PrevDiag);
3718         return true;
3719       }
3720     }
3721 
3722     // If the function types are compatible, merge the declarations. Ignore the
3723     // exception specifier because it was already checked above in
3724     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3725     // about incompatible types under -fms-compatibility.
3726     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3727                                                          NewQType))
3728       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3729 
3730     // If the types are imprecise (due to dependent constructs in friends or
3731     // local extern declarations), it's OK if they differ. We'll check again
3732     // during instantiation.
3733     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3734       return false;
3735 
3736     // Fall through for conflicting redeclarations and redefinitions.
3737   }
3738 
3739   // C: Function types need to be compatible, not identical. This handles
3740   // duplicate function decls like "void f(int); void f(enum X);" properly.
3741   if (!getLangOpts().CPlusPlus &&
3742       Context.typesAreCompatible(OldQType, NewQType)) {
3743     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3744     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3745     const FunctionProtoType *OldProto = nullptr;
3746     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3747         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3748       // The old declaration provided a function prototype, but the
3749       // new declaration does not. Merge in the prototype.
3750       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3751       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3752       NewQType =
3753           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3754                                   OldProto->getExtProtoInfo());
3755       New->setType(NewQType);
3756       New->setHasInheritedPrototype();
3757 
3758       // Synthesize parameters with the same types.
3759       SmallVector<ParmVarDecl*, 16> Params;
3760       for (const auto &ParamType : OldProto->param_types()) {
3761         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3762                                                  SourceLocation(), nullptr,
3763                                                  ParamType, /*TInfo=*/nullptr,
3764                                                  SC_None, nullptr);
3765         Param->setScopeInfo(0, Params.size());
3766         Param->setImplicit();
3767         Params.push_back(Param);
3768       }
3769 
3770       New->setParams(Params);
3771     }
3772 
3773     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3774   }
3775 
3776   // Check if the function types are compatible when pointer size address
3777   // spaces are ignored.
3778   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3779     return false;
3780 
3781   // GNU C permits a K&R definition to follow a prototype declaration
3782   // if the declared types of the parameters in the K&R definition
3783   // match the types in the prototype declaration, even when the
3784   // promoted types of the parameters from the K&R definition differ
3785   // from the types in the prototype. GCC then keeps the types from
3786   // the prototype.
3787   //
3788   // If a variadic prototype is followed by a non-variadic K&R definition,
3789   // the K&R definition becomes variadic.  This is sort of an edge case, but
3790   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3791   // C99 6.9.1p8.
3792   if (!getLangOpts().CPlusPlus &&
3793       Old->hasPrototype() && !New->hasPrototype() &&
3794       New->getType()->getAs<FunctionProtoType>() &&
3795       Old->getNumParams() == New->getNumParams()) {
3796     SmallVector<QualType, 16> ArgTypes;
3797     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3798     const FunctionProtoType *OldProto
3799       = Old->getType()->getAs<FunctionProtoType>();
3800     const FunctionProtoType *NewProto
3801       = New->getType()->getAs<FunctionProtoType>();
3802 
3803     // Determine whether this is the GNU C extension.
3804     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3805                                                NewProto->getReturnType());
3806     bool LooseCompatible = !MergedReturn.isNull();
3807     for (unsigned Idx = 0, End = Old->getNumParams();
3808          LooseCompatible && Idx != End; ++Idx) {
3809       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3810       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3811       if (Context.typesAreCompatible(OldParm->getType(),
3812                                      NewProto->getParamType(Idx))) {
3813         ArgTypes.push_back(NewParm->getType());
3814       } else if (Context.typesAreCompatible(OldParm->getType(),
3815                                             NewParm->getType(),
3816                                             /*CompareUnqualified=*/true)) {
3817         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3818                                            NewProto->getParamType(Idx) };
3819         Warnings.push_back(Warn);
3820         ArgTypes.push_back(NewParm->getType());
3821       } else
3822         LooseCompatible = false;
3823     }
3824 
3825     if (LooseCompatible) {
3826       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3827         Diag(Warnings[Warn].NewParm->getLocation(),
3828              diag::ext_param_promoted_not_compatible_with_prototype)
3829           << Warnings[Warn].PromotedType
3830           << Warnings[Warn].OldParm->getType();
3831         if (Warnings[Warn].OldParm->getLocation().isValid())
3832           Diag(Warnings[Warn].OldParm->getLocation(),
3833                diag::note_previous_declaration);
3834       }
3835 
3836       if (MergeTypeWithOld)
3837         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3838                                              OldProto->getExtProtoInfo()));
3839       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3840     }
3841 
3842     // Fall through to diagnose conflicting types.
3843   }
3844 
3845   // A function that has already been declared has been redeclared or
3846   // defined with a different type; show an appropriate diagnostic.
3847 
3848   // If the previous declaration was an implicitly-generated builtin
3849   // declaration, then at the very least we should use a specialized note.
3850   unsigned BuiltinID;
3851   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3852     // If it's actually a library-defined builtin function like 'malloc'
3853     // or 'printf', just warn about the incompatible redeclaration.
3854     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3855       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3856       Diag(OldLocation, diag::note_previous_builtin_declaration)
3857         << Old << Old->getType();
3858       return false;
3859     }
3860 
3861     PrevDiag = diag::note_previous_builtin_declaration;
3862   }
3863 
3864   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3865   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3866   return true;
3867 }
3868 
3869 /// Completes the merge of two function declarations that are
3870 /// known to be compatible.
3871 ///
3872 /// This routine handles the merging of attributes and other
3873 /// properties of function declarations from the old declaration to
3874 /// the new declaration, once we know that New is in fact a
3875 /// redeclaration of Old.
3876 ///
3877 /// \returns false
3878 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3879                                         Scope *S, bool MergeTypeWithOld) {
3880   // Merge the attributes
3881   mergeDeclAttributes(New, Old);
3882 
3883   // Merge "pure" flag.
3884   if (Old->isPure())
3885     New->setPure();
3886 
3887   // Merge "used" flag.
3888   if (Old->getMostRecentDecl()->isUsed(false))
3889     New->setIsUsed();
3890 
3891   // Merge attributes from the parameters.  These can mismatch with K&R
3892   // declarations.
3893   if (New->getNumParams() == Old->getNumParams())
3894       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3895         ParmVarDecl *NewParam = New->getParamDecl(i);
3896         ParmVarDecl *OldParam = Old->getParamDecl(i);
3897         mergeParamDeclAttributes(NewParam, OldParam, *this);
3898         mergeParamDeclTypes(NewParam, OldParam, *this);
3899       }
3900 
3901   if (getLangOpts().CPlusPlus)
3902     return MergeCXXFunctionDecl(New, Old, S);
3903 
3904   // Merge the function types so the we get the composite types for the return
3905   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3906   // was visible.
3907   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3908   if (!Merged.isNull() && MergeTypeWithOld)
3909     New->setType(Merged);
3910 
3911   return false;
3912 }
3913 
3914 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3915                                 ObjCMethodDecl *oldMethod) {
3916   // Merge the attributes, including deprecated/unavailable
3917   AvailabilityMergeKind MergeKind =
3918       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3919           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3920                                      : AMK_ProtocolImplementation)
3921           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3922                                                            : AMK_Override;
3923 
3924   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3925 
3926   // Merge attributes from the parameters.
3927   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3928                                        oe = oldMethod->param_end();
3929   for (ObjCMethodDecl::param_iterator
3930          ni = newMethod->param_begin(), ne = newMethod->param_end();
3931        ni != ne && oi != oe; ++ni, ++oi)
3932     mergeParamDeclAttributes(*ni, *oi, *this);
3933 
3934   CheckObjCMethodOverride(newMethod, oldMethod);
3935 }
3936 
3937 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3938   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3939 
3940   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3941          ? diag::err_redefinition_different_type
3942          : diag::err_redeclaration_different_type)
3943     << New->getDeclName() << New->getType() << Old->getType();
3944 
3945   diag::kind PrevDiag;
3946   SourceLocation OldLocation;
3947   std::tie(PrevDiag, OldLocation)
3948     = getNoteDiagForInvalidRedeclaration(Old, New);
3949   S.Diag(OldLocation, PrevDiag);
3950   New->setInvalidDecl();
3951 }
3952 
3953 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3954 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3955 /// emitting diagnostics as appropriate.
3956 ///
3957 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3958 /// to here in AddInitializerToDecl. We can't check them before the initializer
3959 /// is attached.
3960 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3961                              bool MergeTypeWithOld) {
3962   if (New->isInvalidDecl() || Old->isInvalidDecl())
3963     return;
3964 
3965   QualType MergedT;
3966   if (getLangOpts().CPlusPlus) {
3967     if (New->getType()->isUndeducedType()) {
3968       // We don't know what the new type is until the initializer is attached.
3969       return;
3970     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3971       // These could still be something that needs exception specs checked.
3972       return MergeVarDeclExceptionSpecs(New, Old);
3973     }
3974     // C++ [basic.link]p10:
3975     //   [...] the types specified by all declarations referring to a given
3976     //   object or function shall be identical, except that declarations for an
3977     //   array object can specify array types that differ by the presence or
3978     //   absence of a major array bound (8.3.4).
3979     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3980       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3981       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3982 
3983       // We are merging a variable declaration New into Old. If it has an array
3984       // bound, and that bound differs from Old's bound, we should diagnose the
3985       // mismatch.
3986       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3987         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3988              PrevVD = PrevVD->getPreviousDecl()) {
3989           QualType PrevVDTy = PrevVD->getType();
3990           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3991             continue;
3992 
3993           if (!Context.hasSameType(New->getType(), PrevVDTy))
3994             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3995         }
3996       }
3997 
3998       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3999         if (Context.hasSameType(OldArray->getElementType(),
4000                                 NewArray->getElementType()))
4001           MergedT = New->getType();
4002       }
4003       // FIXME: Check visibility. New is hidden but has a complete type. If New
4004       // has no array bound, it should not inherit one from Old, if Old is not
4005       // visible.
4006       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4007         if (Context.hasSameType(OldArray->getElementType(),
4008                                 NewArray->getElementType()))
4009           MergedT = Old->getType();
4010       }
4011     }
4012     else if (New->getType()->isObjCObjectPointerType() &&
4013                Old->getType()->isObjCObjectPointerType()) {
4014       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4015                                               Old->getType());
4016     }
4017   } else {
4018     // C 6.2.7p2:
4019     //   All declarations that refer to the same object or function shall have
4020     //   compatible type.
4021     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4022   }
4023   if (MergedT.isNull()) {
4024     // It's OK if we couldn't merge types if either type is dependent, for a
4025     // block-scope variable. In other cases (static data members of class
4026     // templates, variable templates, ...), we require the types to be
4027     // equivalent.
4028     // FIXME: The C++ standard doesn't say anything about this.
4029     if ((New->getType()->isDependentType() ||
4030          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4031       // If the old type was dependent, we can't merge with it, so the new type
4032       // becomes dependent for now. We'll reproduce the original type when we
4033       // instantiate the TypeSourceInfo for the variable.
4034       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4035         New->setType(Context.DependentTy);
4036       return;
4037     }
4038     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4039   }
4040 
4041   // Don't actually update the type on the new declaration if the old
4042   // declaration was an extern declaration in a different scope.
4043   if (MergeTypeWithOld)
4044     New->setType(MergedT);
4045 }
4046 
4047 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4048                                   LookupResult &Previous) {
4049   // C11 6.2.7p4:
4050   //   For an identifier with internal or external linkage declared
4051   //   in a scope in which a prior declaration of that identifier is
4052   //   visible, if the prior declaration specifies internal or
4053   //   external linkage, the type of the identifier at the later
4054   //   declaration becomes the composite type.
4055   //
4056   // If the variable isn't visible, we do not merge with its type.
4057   if (Previous.isShadowed())
4058     return false;
4059 
4060   if (S.getLangOpts().CPlusPlus) {
4061     // C++11 [dcl.array]p3:
4062     //   If there is a preceding declaration of the entity in the same
4063     //   scope in which the bound was specified, an omitted array bound
4064     //   is taken to be the same as in that earlier declaration.
4065     return NewVD->isPreviousDeclInSameBlockScope() ||
4066            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4067             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4068   } else {
4069     // If the old declaration was function-local, don't merge with its
4070     // type unless we're in the same function.
4071     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4072            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4073   }
4074 }
4075 
4076 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4077 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4078 /// situation, merging decls or emitting diagnostics as appropriate.
4079 ///
4080 /// Tentative definition rules (C99 6.9.2p2) are checked by
4081 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4082 /// definitions here, since the initializer hasn't been attached.
4083 ///
4084 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4085   // If the new decl is already invalid, don't do any other checking.
4086   if (New->isInvalidDecl())
4087     return;
4088 
4089   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4090     return;
4091 
4092   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4093 
4094   // Verify the old decl was also a variable or variable template.
4095   VarDecl *Old = nullptr;
4096   VarTemplateDecl *OldTemplate = nullptr;
4097   if (Previous.isSingleResult()) {
4098     if (NewTemplate) {
4099       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4100       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4101 
4102       if (auto *Shadow =
4103               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4104         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4105           return New->setInvalidDecl();
4106     } else {
4107       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4108 
4109       if (auto *Shadow =
4110               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4111         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4112           return New->setInvalidDecl();
4113     }
4114   }
4115   if (!Old) {
4116     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4117         << New->getDeclName();
4118     notePreviousDefinition(Previous.getRepresentativeDecl(),
4119                            New->getLocation());
4120     return New->setInvalidDecl();
4121   }
4122 
4123   // If the old declaration was found in an inline namespace and the new
4124   // declaration was qualified, update the DeclContext to match.
4125   adjustDeclContextForDeclaratorDecl(New, Old);
4126 
4127   // Ensure the template parameters are compatible.
4128   if (NewTemplate &&
4129       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4130                                       OldTemplate->getTemplateParameters(),
4131                                       /*Complain=*/true, TPL_TemplateMatch))
4132     return New->setInvalidDecl();
4133 
4134   // C++ [class.mem]p1:
4135   //   A member shall not be declared twice in the member-specification [...]
4136   //
4137   // Here, we need only consider static data members.
4138   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4139     Diag(New->getLocation(), diag::err_duplicate_member)
4140       << New->getIdentifier();
4141     Diag(Old->getLocation(), diag::note_previous_declaration);
4142     New->setInvalidDecl();
4143   }
4144 
4145   mergeDeclAttributes(New, Old);
4146   // Warn if an already-declared variable is made a weak_import in a subsequent
4147   // declaration
4148   if (New->hasAttr<WeakImportAttr>() &&
4149       Old->getStorageClass() == SC_None &&
4150       !Old->hasAttr<WeakImportAttr>()) {
4151     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4152     notePreviousDefinition(Old, New->getLocation());
4153     // Remove weak_import attribute on new declaration.
4154     New->dropAttr<WeakImportAttr>();
4155   }
4156 
4157   if (New->hasAttr<InternalLinkageAttr>() &&
4158       !Old->hasAttr<InternalLinkageAttr>()) {
4159     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4160         << New->getDeclName();
4161     notePreviousDefinition(Old, New->getLocation());
4162     New->dropAttr<InternalLinkageAttr>();
4163   }
4164 
4165   // Merge the types.
4166   VarDecl *MostRecent = Old->getMostRecentDecl();
4167   if (MostRecent != Old) {
4168     MergeVarDeclTypes(New, MostRecent,
4169                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4170     if (New->isInvalidDecl())
4171       return;
4172   }
4173 
4174   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4175   if (New->isInvalidDecl())
4176     return;
4177 
4178   diag::kind PrevDiag;
4179   SourceLocation OldLocation;
4180   std::tie(PrevDiag, OldLocation) =
4181       getNoteDiagForInvalidRedeclaration(Old, New);
4182 
4183   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4184   if (New->getStorageClass() == SC_Static &&
4185       !New->isStaticDataMember() &&
4186       Old->hasExternalFormalLinkage()) {
4187     if (getLangOpts().MicrosoftExt) {
4188       Diag(New->getLocation(), diag::ext_static_non_static)
4189           << New->getDeclName();
4190       Diag(OldLocation, PrevDiag);
4191     } else {
4192       Diag(New->getLocation(), diag::err_static_non_static)
4193           << New->getDeclName();
4194       Diag(OldLocation, PrevDiag);
4195       return New->setInvalidDecl();
4196     }
4197   }
4198   // C99 6.2.2p4:
4199   //   For an identifier declared with the storage-class specifier
4200   //   extern in a scope in which a prior declaration of that
4201   //   identifier is visible,23) if the prior declaration specifies
4202   //   internal or external linkage, the linkage of the identifier at
4203   //   the later declaration is the same as the linkage specified at
4204   //   the prior declaration. If no prior declaration is visible, or
4205   //   if the prior declaration specifies no linkage, then the
4206   //   identifier has external linkage.
4207   if (New->hasExternalStorage() && Old->hasLinkage())
4208     /* Okay */;
4209   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4210            !New->isStaticDataMember() &&
4211            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4212     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4213     Diag(OldLocation, PrevDiag);
4214     return New->setInvalidDecl();
4215   }
4216 
4217   // Check if extern is followed by non-extern and vice-versa.
4218   if (New->hasExternalStorage() &&
4219       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4220     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4221     Diag(OldLocation, PrevDiag);
4222     return New->setInvalidDecl();
4223   }
4224   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4225       !New->hasExternalStorage()) {
4226     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4227     Diag(OldLocation, PrevDiag);
4228     return New->setInvalidDecl();
4229   }
4230 
4231   if (CheckRedeclarationModuleOwnership(New, Old))
4232     return;
4233 
4234   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4235 
4236   // FIXME: The test for external storage here seems wrong? We still
4237   // need to check for mismatches.
4238   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4239       // Don't complain about out-of-line definitions of static members.
4240       !(Old->getLexicalDeclContext()->isRecord() &&
4241         !New->getLexicalDeclContext()->isRecord())) {
4242     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4243     Diag(OldLocation, PrevDiag);
4244     return New->setInvalidDecl();
4245   }
4246 
4247   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4248     if (VarDecl *Def = Old->getDefinition()) {
4249       // C++1z [dcl.fcn.spec]p4:
4250       //   If the definition of a variable appears in a translation unit before
4251       //   its first declaration as inline, the program is ill-formed.
4252       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4253       Diag(Def->getLocation(), diag::note_previous_definition);
4254     }
4255   }
4256 
4257   // If this redeclaration makes the variable inline, we may need to add it to
4258   // UndefinedButUsed.
4259   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4260       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4261     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4262                                            SourceLocation()));
4263 
4264   if (New->getTLSKind() != Old->getTLSKind()) {
4265     if (!Old->getTLSKind()) {
4266       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4267       Diag(OldLocation, PrevDiag);
4268     } else if (!New->getTLSKind()) {
4269       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4270       Diag(OldLocation, PrevDiag);
4271     } else {
4272       // Do not allow redeclaration to change the variable between requiring
4273       // static and dynamic initialization.
4274       // FIXME: GCC allows this, but uses the TLS keyword on the first
4275       // declaration to determine the kind. Do we need to be compatible here?
4276       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4277         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4278       Diag(OldLocation, PrevDiag);
4279     }
4280   }
4281 
4282   // C++ doesn't have tentative definitions, so go right ahead and check here.
4283   if (getLangOpts().CPlusPlus &&
4284       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4285     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4286         Old->getCanonicalDecl()->isConstexpr()) {
4287       // This definition won't be a definition any more once it's been merged.
4288       Diag(New->getLocation(),
4289            diag::warn_deprecated_redundant_constexpr_static_def);
4290     } else if (VarDecl *Def = Old->getDefinition()) {
4291       if (checkVarDeclRedefinition(Def, New))
4292         return;
4293     }
4294   }
4295 
4296   if (haveIncompatibleLanguageLinkages(Old, New)) {
4297     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4298     Diag(OldLocation, PrevDiag);
4299     New->setInvalidDecl();
4300     return;
4301   }
4302 
4303   // Merge "used" flag.
4304   if (Old->getMostRecentDecl()->isUsed(false))
4305     New->setIsUsed();
4306 
4307   // Keep a chain of previous declarations.
4308   New->setPreviousDecl(Old);
4309   if (NewTemplate)
4310     NewTemplate->setPreviousDecl(OldTemplate);
4311 
4312   // Inherit access appropriately.
4313   New->setAccess(Old->getAccess());
4314   if (NewTemplate)
4315     NewTemplate->setAccess(New->getAccess());
4316 
4317   if (Old->isInline())
4318     New->setImplicitlyInline();
4319 }
4320 
4321 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4322   SourceManager &SrcMgr = getSourceManager();
4323   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4324   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4325   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4326   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4327   auto &HSI = PP.getHeaderSearchInfo();
4328   StringRef HdrFilename =
4329       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4330 
4331   auto noteFromModuleOrInclude = [&](Module *Mod,
4332                                      SourceLocation IncLoc) -> bool {
4333     // Redefinition errors with modules are common with non modular mapped
4334     // headers, example: a non-modular header H in module A that also gets
4335     // included directly in a TU. Pointing twice to the same header/definition
4336     // is confusing, try to get better diagnostics when modules is on.
4337     if (IncLoc.isValid()) {
4338       if (Mod) {
4339         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4340             << HdrFilename.str() << Mod->getFullModuleName();
4341         if (!Mod->DefinitionLoc.isInvalid())
4342           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4343               << Mod->getFullModuleName();
4344       } else {
4345         Diag(IncLoc, diag::note_redefinition_include_same_file)
4346             << HdrFilename.str();
4347       }
4348       return true;
4349     }
4350 
4351     return false;
4352   };
4353 
4354   // Is it the same file and same offset? Provide more information on why
4355   // this leads to a redefinition error.
4356   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4357     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4358     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4359     bool EmittedDiag =
4360         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4361     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4362 
4363     // If the header has no guards, emit a note suggesting one.
4364     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4365       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4366 
4367     if (EmittedDiag)
4368       return;
4369   }
4370 
4371   // Redefinition coming from different files or couldn't do better above.
4372   if (Old->getLocation().isValid())
4373     Diag(Old->getLocation(), diag::note_previous_definition);
4374 }
4375 
4376 /// We've just determined that \p Old and \p New both appear to be definitions
4377 /// of the same variable. Either diagnose or fix the problem.
4378 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4379   if (!hasVisibleDefinition(Old) &&
4380       (New->getFormalLinkage() == InternalLinkage ||
4381        New->isInline() ||
4382        New->getDescribedVarTemplate() ||
4383        New->getNumTemplateParameterLists() ||
4384        New->getDeclContext()->isDependentContext())) {
4385     // The previous definition is hidden, and multiple definitions are
4386     // permitted (in separate TUs). Demote this to a declaration.
4387     New->demoteThisDefinitionToDeclaration();
4388 
4389     // Make the canonical definition visible.
4390     if (auto *OldTD = Old->getDescribedVarTemplate())
4391       makeMergedDefinitionVisible(OldTD);
4392     makeMergedDefinitionVisible(Old);
4393     return false;
4394   } else {
4395     Diag(New->getLocation(), diag::err_redefinition) << New;
4396     notePreviousDefinition(Old, New->getLocation());
4397     New->setInvalidDecl();
4398     return true;
4399   }
4400 }
4401 
4402 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4403 /// no declarator (e.g. "struct foo;") is parsed.
4404 Decl *
4405 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4406                                  RecordDecl *&AnonRecord) {
4407   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4408                                     AnonRecord);
4409 }
4410 
4411 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4412 // disambiguate entities defined in different scopes.
4413 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4414 // compatibility.
4415 // We will pick our mangling number depending on which version of MSVC is being
4416 // targeted.
4417 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4418   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4419              ? S->getMSCurManglingNumber()
4420              : S->getMSLastManglingNumber();
4421 }
4422 
4423 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4424   if (!Context.getLangOpts().CPlusPlus)
4425     return;
4426 
4427   if (isa<CXXRecordDecl>(Tag->getParent())) {
4428     // If this tag is the direct child of a class, number it if
4429     // it is anonymous.
4430     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4431       return;
4432     MangleNumberingContext &MCtx =
4433         Context.getManglingNumberContext(Tag->getParent());
4434     Context.setManglingNumber(
4435         Tag, MCtx.getManglingNumber(
4436                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4437     return;
4438   }
4439 
4440   // If this tag isn't a direct child of a class, number it if it is local.
4441   MangleNumberingContext *MCtx;
4442   Decl *ManglingContextDecl;
4443   std::tie(MCtx, ManglingContextDecl) =
4444       getCurrentMangleNumberContext(Tag->getDeclContext());
4445   if (MCtx) {
4446     Context.setManglingNumber(
4447         Tag, MCtx->getManglingNumber(
4448                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4449   }
4450 }
4451 
4452 namespace {
4453 struct NonCLikeKind {
4454   enum {
4455     None,
4456     BaseClass,
4457     DefaultMemberInit,
4458     Lambda,
4459     Friend,
4460     OtherMember,
4461     Invalid,
4462   } Kind = None;
4463   SourceRange Range;
4464 
4465   explicit operator bool() { return Kind != None; }
4466 };
4467 }
4468 
4469 /// Determine whether a class is C-like, according to the rules of C++
4470 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4471 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4472   if (RD->isInvalidDecl())
4473     return {NonCLikeKind::Invalid, {}};
4474 
4475   // C++ [dcl.typedef]p9: [P1766R1]
4476   //   An unnamed class with a typedef name for linkage purposes shall not
4477   //
4478   //    -- have any base classes
4479   if (RD->getNumBases())
4480     return {NonCLikeKind::BaseClass,
4481             SourceRange(RD->bases_begin()->getBeginLoc(),
4482                         RD->bases_end()[-1].getEndLoc())};
4483   bool Invalid = false;
4484   for (Decl *D : RD->decls()) {
4485     // Don't complain about things we already diagnosed.
4486     if (D->isInvalidDecl()) {
4487       Invalid = true;
4488       continue;
4489     }
4490 
4491     //  -- have any [...] default member initializers
4492     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4493       if (FD->hasInClassInitializer()) {
4494         auto *Init = FD->getInClassInitializer();
4495         return {NonCLikeKind::DefaultMemberInit,
4496                 Init ? Init->getSourceRange() : D->getSourceRange()};
4497       }
4498       continue;
4499     }
4500 
4501     // FIXME: We don't allow friend declarations. This violates the wording of
4502     // P1766, but not the intent.
4503     if (isa<FriendDecl>(D))
4504       return {NonCLikeKind::Friend, D->getSourceRange()};
4505 
4506     //  -- declare any members other than non-static data members, member
4507     //     enumerations, or member classes,
4508     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4509         isa<EnumDecl>(D))
4510       continue;
4511     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4512     if (!MemberRD) {
4513       if (D->isImplicit())
4514         continue;
4515       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4516     }
4517 
4518     //  -- contain a lambda-expression,
4519     if (MemberRD->isLambda())
4520       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4521 
4522     //  and all member classes shall also satisfy these requirements
4523     //  (recursively).
4524     if (MemberRD->isThisDeclarationADefinition()) {
4525       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4526         return Kind;
4527     }
4528   }
4529 
4530   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4531 }
4532 
4533 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4534                                         TypedefNameDecl *NewTD) {
4535   if (TagFromDeclSpec->isInvalidDecl())
4536     return;
4537 
4538   // Do nothing if the tag already has a name for linkage purposes.
4539   if (TagFromDeclSpec->hasNameForLinkage())
4540     return;
4541 
4542   // A well-formed anonymous tag must always be a TUK_Definition.
4543   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4544 
4545   // The type must match the tag exactly;  no qualifiers allowed.
4546   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4547                            Context.getTagDeclType(TagFromDeclSpec))) {
4548     if (getLangOpts().CPlusPlus)
4549       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4550     return;
4551   }
4552 
4553   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4554   //   An unnamed class with a typedef name for linkage purposes shall [be
4555   //   C-like].
4556   //
4557   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4558   // shouldn't happen, but there are constructs that the language rule doesn't
4559   // disallow for which we can't reasonably avoid computing linkage early.
4560   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4561   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4562                              : NonCLikeKind();
4563   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4564   if (NonCLike || ChangesLinkage) {
4565     if (NonCLike.Kind == NonCLikeKind::Invalid)
4566       return;
4567 
4568     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4569     if (ChangesLinkage) {
4570       // If the linkage changes, we can't accept this as an extension.
4571       if (NonCLike.Kind == NonCLikeKind::None)
4572         DiagID = diag::err_typedef_changes_linkage;
4573       else
4574         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4575     }
4576 
4577     SourceLocation FixitLoc =
4578         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4579     llvm::SmallString<40> TextToInsert;
4580     TextToInsert += ' ';
4581     TextToInsert += NewTD->getIdentifier()->getName();
4582 
4583     Diag(FixitLoc, DiagID)
4584       << isa<TypeAliasDecl>(NewTD)
4585       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4586     if (NonCLike.Kind != NonCLikeKind::None) {
4587       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4588         << NonCLike.Kind - 1 << NonCLike.Range;
4589     }
4590     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4591       << NewTD << isa<TypeAliasDecl>(NewTD);
4592 
4593     if (ChangesLinkage)
4594       return;
4595   }
4596 
4597   // Otherwise, set this as the anon-decl typedef for the tag.
4598   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4599 }
4600 
4601 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4602   switch (T) {
4603   case DeclSpec::TST_class:
4604     return 0;
4605   case DeclSpec::TST_struct:
4606     return 1;
4607   case DeclSpec::TST_interface:
4608     return 2;
4609   case DeclSpec::TST_union:
4610     return 3;
4611   case DeclSpec::TST_enum:
4612     return 4;
4613   default:
4614     llvm_unreachable("unexpected type specifier");
4615   }
4616 }
4617 
4618 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4619 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4620 /// parameters to cope with template friend declarations.
4621 Decl *
4622 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4623                                  MultiTemplateParamsArg TemplateParams,
4624                                  bool IsExplicitInstantiation,
4625                                  RecordDecl *&AnonRecord) {
4626   Decl *TagD = nullptr;
4627   TagDecl *Tag = nullptr;
4628   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4629       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4630       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4631       DS.getTypeSpecType() == DeclSpec::TST_union ||
4632       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4633     TagD = DS.getRepAsDecl();
4634 
4635     if (!TagD) // We probably had an error
4636       return nullptr;
4637 
4638     // Note that the above type specs guarantee that the
4639     // type rep is a Decl, whereas in many of the others
4640     // it's a Type.
4641     if (isa<TagDecl>(TagD))
4642       Tag = cast<TagDecl>(TagD);
4643     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4644       Tag = CTD->getTemplatedDecl();
4645   }
4646 
4647   if (Tag) {
4648     handleTagNumbering(Tag, S);
4649     Tag->setFreeStanding();
4650     if (Tag->isInvalidDecl())
4651       return Tag;
4652   }
4653 
4654   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4655     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4656     // or incomplete types shall not be restrict-qualified."
4657     if (TypeQuals & DeclSpec::TQ_restrict)
4658       Diag(DS.getRestrictSpecLoc(),
4659            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4660            << DS.getSourceRange();
4661   }
4662 
4663   if (DS.isInlineSpecified())
4664     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4665         << getLangOpts().CPlusPlus17;
4666 
4667   if (DS.hasConstexprSpecifier()) {
4668     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4669     // and definitions of functions and variables.
4670     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4671     // the declaration of a function or function template
4672     if (Tag)
4673       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4674           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4675           << static_cast<int>(DS.getConstexprSpecifier());
4676     else
4677       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4678           << static_cast<int>(DS.getConstexprSpecifier());
4679     // Don't emit warnings after this error.
4680     return TagD;
4681   }
4682 
4683   DiagnoseFunctionSpecifiers(DS);
4684 
4685   if (DS.isFriendSpecified()) {
4686     // If we're dealing with a decl but not a TagDecl, assume that
4687     // whatever routines created it handled the friendship aspect.
4688     if (TagD && !Tag)
4689       return nullptr;
4690     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4691   }
4692 
4693   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4694   bool IsExplicitSpecialization =
4695     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4696   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4697       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4698       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4699     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4700     // nested-name-specifier unless it is an explicit instantiation
4701     // or an explicit specialization.
4702     //
4703     // FIXME: We allow class template partial specializations here too, per the
4704     // obvious intent of DR1819.
4705     //
4706     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4707     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4708         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4709     return nullptr;
4710   }
4711 
4712   // Track whether this decl-specifier declares anything.
4713   bool DeclaresAnything = true;
4714 
4715   // Handle anonymous struct definitions.
4716   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4717     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4718         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4719       if (getLangOpts().CPlusPlus ||
4720           Record->getDeclContext()->isRecord()) {
4721         // If CurContext is a DeclContext that can contain statements,
4722         // RecursiveASTVisitor won't visit the decls that
4723         // BuildAnonymousStructOrUnion() will put into CurContext.
4724         // Also store them here so that they can be part of the
4725         // DeclStmt that gets created in this case.
4726         // FIXME: Also return the IndirectFieldDecls created by
4727         // BuildAnonymousStructOr union, for the same reason?
4728         if (CurContext->isFunctionOrMethod())
4729           AnonRecord = Record;
4730         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4731                                            Context.getPrintingPolicy());
4732       }
4733 
4734       DeclaresAnything = false;
4735     }
4736   }
4737 
4738   // C11 6.7.2.1p2:
4739   //   A struct-declaration that does not declare an anonymous structure or
4740   //   anonymous union shall contain a struct-declarator-list.
4741   //
4742   // This rule also existed in C89 and C99; the grammar for struct-declaration
4743   // did not permit a struct-declaration without a struct-declarator-list.
4744   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4745       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4746     // Check for Microsoft C extension: anonymous struct/union member.
4747     // Handle 2 kinds of anonymous struct/union:
4748     //   struct STRUCT;
4749     //   union UNION;
4750     // and
4751     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4752     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4753     if ((Tag && Tag->getDeclName()) ||
4754         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4755       RecordDecl *Record = nullptr;
4756       if (Tag)
4757         Record = dyn_cast<RecordDecl>(Tag);
4758       else if (const RecordType *RT =
4759                    DS.getRepAsType().get()->getAsStructureType())
4760         Record = RT->getDecl();
4761       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4762         Record = UT->getDecl();
4763 
4764       if (Record && getLangOpts().MicrosoftExt) {
4765         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4766             << Record->isUnion() << DS.getSourceRange();
4767         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4768       }
4769 
4770       DeclaresAnything = false;
4771     }
4772   }
4773 
4774   // Skip all the checks below if we have a type error.
4775   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4776       (TagD && TagD->isInvalidDecl()))
4777     return TagD;
4778 
4779   if (getLangOpts().CPlusPlus &&
4780       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4781     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4782       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4783           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4784         DeclaresAnything = false;
4785 
4786   if (!DS.isMissingDeclaratorOk()) {
4787     // Customize diagnostic for a typedef missing a name.
4788     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4789       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4790           << DS.getSourceRange();
4791     else
4792       DeclaresAnything = false;
4793   }
4794 
4795   if (DS.isModulePrivateSpecified() &&
4796       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4797     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4798       << Tag->getTagKind()
4799       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4800 
4801   ActOnDocumentableDecl(TagD);
4802 
4803   // C 6.7/2:
4804   //   A declaration [...] shall declare at least a declarator [...], a tag,
4805   //   or the members of an enumeration.
4806   // C++ [dcl.dcl]p3:
4807   //   [If there are no declarators], and except for the declaration of an
4808   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4809   //   names into the program, or shall redeclare a name introduced by a
4810   //   previous declaration.
4811   if (!DeclaresAnything) {
4812     // In C, we allow this as a (popular) extension / bug. Don't bother
4813     // producing further diagnostics for redundant qualifiers after this.
4814     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4815                                ? diag::err_no_declarators
4816                                : diag::ext_no_declarators)
4817         << DS.getSourceRange();
4818     return TagD;
4819   }
4820 
4821   // C++ [dcl.stc]p1:
4822   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4823   //   init-declarator-list of the declaration shall not be empty.
4824   // C++ [dcl.fct.spec]p1:
4825   //   If a cv-qualifier appears in a decl-specifier-seq, the
4826   //   init-declarator-list of the declaration shall not be empty.
4827   //
4828   // Spurious qualifiers here appear to be valid in C.
4829   unsigned DiagID = diag::warn_standalone_specifier;
4830   if (getLangOpts().CPlusPlus)
4831     DiagID = diag::ext_standalone_specifier;
4832 
4833   // Note that a linkage-specification sets a storage class, but
4834   // 'extern "C" struct foo;' is actually valid and not theoretically
4835   // useless.
4836   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4837     if (SCS == DeclSpec::SCS_mutable)
4838       // Since mutable is not a viable storage class specifier in C, there is
4839       // no reason to treat it as an extension. Instead, diagnose as an error.
4840       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4841     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4842       Diag(DS.getStorageClassSpecLoc(), DiagID)
4843         << DeclSpec::getSpecifierName(SCS);
4844   }
4845 
4846   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4847     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4848       << DeclSpec::getSpecifierName(TSCS);
4849   if (DS.getTypeQualifiers()) {
4850     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4851       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4852     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4853       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4854     // Restrict is covered above.
4855     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4856       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4857     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4858       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4859   }
4860 
4861   // Warn about ignored type attributes, for example:
4862   // __attribute__((aligned)) struct A;
4863   // Attributes should be placed after tag to apply to type declaration.
4864   if (!DS.getAttributes().empty()) {
4865     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4866     if (TypeSpecType == DeclSpec::TST_class ||
4867         TypeSpecType == DeclSpec::TST_struct ||
4868         TypeSpecType == DeclSpec::TST_interface ||
4869         TypeSpecType == DeclSpec::TST_union ||
4870         TypeSpecType == DeclSpec::TST_enum) {
4871       for (const ParsedAttr &AL : DS.getAttributes())
4872         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4873             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4874     }
4875   }
4876 
4877   return TagD;
4878 }
4879 
4880 /// We are trying to inject an anonymous member into the given scope;
4881 /// check if there's an existing declaration that can't be overloaded.
4882 ///
4883 /// \return true if this is a forbidden redeclaration
4884 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4885                                          Scope *S,
4886                                          DeclContext *Owner,
4887                                          DeclarationName Name,
4888                                          SourceLocation NameLoc,
4889                                          bool IsUnion) {
4890   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4891                  Sema::ForVisibleRedeclaration);
4892   if (!SemaRef.LookupName(R, S)) return false;
4893 
4894   // Pick a representative declaration.
4895   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4896   assert(PrevDecl && "Expected a non-null Decl");
4897 
4898   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4899     return false;
4900 
4901   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4902     << IsUnion << Name;
4903   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4904 
4905   return true;
4906 }
4907 
4908 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4909 /// anonymous struct or union AnonRecord into the owning context Owner
4910 /// and scope S. This routine will be invoked just after we realize
4911 /// that an unnamed union or struct is actually an anonymous union or
4912 /// struct, e.g.,
4913 ///
4914 /// @code
4915 /// union {
4916 ///   int i;
4917 ///   float f;
4918 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4919 ///    // f into the surrounding scope.x
4920 /// @endcode
4921 ///
4922 /// This routine is recursive, injecting the names of nested anonymous
4923 /// structs/unions into the owning context and scope as well.
4924 static bool
4925 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4926                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4927                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4928   bool Invalid = false;
4929 
4930   // Look every FieldDecl and IndirectFieldDecl with a name.
4931   for (auto *D : AnonRecord->decls()) {
4932     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4933         cast<NamedDecl>(D)->getDeclName()) {
4934       ValueDecl *VD = cast<ValueDecl>(D);
4935       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4936                                        VD->getLocation(),
4937                                        AnonRecord->isUnion())) {
4938         // C++ [class.union]p2:
4939         //   The names of the members of an anonymous union shall be
4940         //   distinct from the names of any other entity in the
4941         //   scope in which the anonymous union is declared.
4942         Invalid = true;
4943       } else {
4944         // C++ [class.union]p2:
4945         //   For the purpose of name lookup, after the anonymous union
4946         //   definition, the members of the anonymous union are
4947         //   considered to have been defined in the scope in which the
4948         //   anonymous union is declared.
4949         unsigned OldChainingSize = Chaining.size();
4950         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4951           Chaining.append(IF->chain_begin(), IF->chain_end());
4952         else
4953           Chaining.push_back(VD);
4954 
4955         assert(Chaining.size() >= 2);
4956         NamedDecl **NamedChain =
4957           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4958         for (unsigned i = 0; i < Chaining.size(); i++)
4959           NamedChain[i] = Chaining[i];
4960 
4961         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4962             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4963             VD->getType(), {NamedChain, Chaining.size()});
4964 
4965         for (const auto *Attr : VD->attrs())
4966           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4967 
4968         IndirectField->setAccess(AS);
4969         IndirectField->setImplicit();
4970         SemaRef.PushOnScopeChains(IndirectField, S);
4971 
4972         // That includes picking up the appropriate access specifier.
4973         if (AS != AS_none) IndirectField->setAccess(AS);
4974 
4975         Chaining.resize(OldChainingSize);
4976       }
4977     }
4978   }
4979 
4980   return Invalid;
4981 }
4982 
4983 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4984 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4985 /// illegal input values are mapped to SC_None.
4986 static StorageClass
4987 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4988   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4989   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4990          "Parser allowed 'typedef' as storage class VarDecl.");
4991   switch (StorageClassSpec) {
4992   case DeclSpec::SCS_unspecified:    return SC_None;
4993   case DeclSpec::SCS_extern:
4994     if (DS.isExternInLinkageSpec())
4995       return SC_None;
4996     return SC_Extern;
4997   case DeclSpec::SCS_static:         return SC_Static;
4998   case DeclSpec::SCS_auto:           return SC_Auto;
4999   case DeclSpec::SCS_register:       return SC_Register;
5000   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5001     // Illegal SCSs map to None: error reporting is up to the caller.
5002   case DeclSpec::SCS_mutable:        // Fall through.
5003   case DeclSpec::SCS_typedef:        return SC_None;
5004   }
5005   llvm_unreachable("unknown storage class specifier");
5006 }
5007 
5008 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5009   assert(Record->hasInClassInitializer());
5010 
5011   for (const auto *I : Record->decls()) {
5012     const auto *FD = dyn_cast<FieldDecl>(I);
5013     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5014       FD = IFD->getAnonField();
5015     if (FD && FD->hasInClassInitializer())
5016       return FD->getLocation();
5017   }
5018 
5019   llvm_unreachable("couldn't find in-class initializer");
5020 }
5021 
5022 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5023                                       SourceLocation DefaultInitLoc) {
5024   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5025     return;
5026 
5027   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5028   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5029 }
5030 
5031 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5032                                       CXXRecordDecl *AnonUnion) {
5033   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5034     return;
5035 
5036   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5037 }
5038 
5039 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5040 /// anonymous structure or union. Anonymous unions are a C++ feature
5041 /// (C++ [class.union]) and a C11 feature; anonymous structures
5042 /// are a C11 feature and GNU C++ extension.
5043 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5044                                         AccessSpecifier AS,
5045                                         RecordDecl *Record,
5046                                         const PrintingPolicy &Policy) {
5047   DeclContext *Owner = Record->getDeclContext();
5048 
5049   // Diagnose whether this anonymous struct/union is an extension.
5050   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5051     Diag(Record->getLocation(), diag::ext_anonymous_union);
5052   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5053     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5054   else if (!Record->isUnion() && !getLangOpts().C11)
5055     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5056 
5057   // C and C++ require different kinds of checks for anonymous
5058   // structs/unions.
5059   bool Invalid = false;
5060   if (getLangOpts().CPlusPlus) {
5061     const char *PrevSpec = nullptr;
5062     if (Record->isUnion()) {
5063       // C++ [class.union]p6:
5064       // C++17 [class.union.anon]p2:
5065       //   Anonymous unions declared in a named namespace or in the
5066       //   global namespace shall be declared static.
5067       unsigned DiagID;
5068       DeclContext *OwnerScope = Owner->getRedeclContext();
5069       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5070           (OwnerScope->isTranslationUnit() ||
5071            (OwnerScope->isNamespace() &&
5072             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5073         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5074           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5075 
5076         // Recover by adding 'static'.
5077         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5078                                PrevSpec, DiagID, Policy);
5079       }
5080       // C++ [class.union]p6:
5081       //   A storage class is not allowed in a declaration of an
5082       //   anonymous union in a class scope.
5083       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5084                isa<RecordDecl>(Owner)) {
5085         Diag(DS.getStorageClassSpecLoc(),
5086              diag::err_anonymous_union_with_storage_spec)
5087           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5088 
5089         // Recover by removing the storage specifier.
5090         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5091                                SourceLocation(),
5092                                PrevSpec, DiagID, Context.getPrintingPolicy());
5093       }
5094     }
5095 
5096     // Ignore const/volatile/restrict qualifiers.
5097     if (DS.getTypeQualifiers()) {
5098       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5099         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5100           << Record->isUnion() << "const"
5101           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5102       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5103         Diag(DS.getVolatileSpecLoc(),
5104              diag::ext_anonymous_struct_union_qualified)
5105           << Record->isUnion() << "volatile"
5106           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5107       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5108         Diag(DS.getRestrictSpecLoc(),
5109              diag::ext_anonymous_struct_union_qualified)
5110           << Record->isUnion() << "restrict"
5111           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5112       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5113         Diag(DS.getAtomicSpecLoc(),
5114              diag::ext_anonymous_struct_union_qualified)
5115           << Record->isUnion() << "_Atomic"
5116           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5117       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5118         Diag(DS.getUnalignedSpecLoc(),
5119              diag::ext_anonymous_struct_union_qualified)
5120           << Record->isUnion() << "__unaligned"
5121           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5122 
5123       DS.ClearTypeQualifiers();
5124     }
5125 
5126     // C++ [class.union]p2:
5127     //   The member-specification of an anonymous union shall only
5128     //   define non-static data members. [Note: nested types and
5129     //   functions cannot be declared within an anonymous union. ]
5130     for (auto *Mem : Record->decls()) {
5131       // Ignore invalid declarations; we already diagnosed them.
5132       if (Mem->isInvalidDecl())
5133         continue;
5134 
5135       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5136         // C++ [class.union]p3:
5137         //   An anonymous union shall not have private or protected
5138         //   members (clause 11).
5139         assert(FD->getAccess() != AS_none);
5140         if (FD->getAccess() != AS_public) {
5141           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5142             << Record->isUnion() << (FD->getAccess() == AS_protected);
5143           Invalid = true;
5144         }
5145 
5146         // C++ [class.union]p1
5147         //   An object of a class with a non-trivial constructor, a non-trivial
5148         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5149         //   assignment operator cannot be a member of a union, nor can an
5150         //   array of such objects.
5151         if (CheckNontrivialField(FD))
5152           Invalid = true;
5153       } else if (Mem->isImplicit()) {
5154         // Any implicit members are fine.
5155       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5156         // This is a type that showed up in an
5157         // elaborated-type-specifier inside the anonymous struct or
5158         // union, but which actually declares a type outside of the
5159         // anonymous struct or union. It's okay.
5160       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5161         if (!MemRecord->isAnonymousStructOrUnion() &&
5162             MemRecord->getDeclName()) {
5163           // Visual C++ allows type definition in anonymous struct or union.
5164           if (getLangOpts().MicrosoftExt)
5165             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5166               << Record->isUnion();
5167           else {
5168             // This is a nested type declaration.
5169             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5170               << Record->isUnion();
5171             Invalid = true;
5172           }
5173         } else {
5174           // This is an anonymous type definition within another anonymous type.
5175           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5176           // not part of standard C++.
5177           Diag(MemRecord->getLocation(),
5178                diag::ext_anonymous_record_with_anonymous_type)
5179             << Record->isUnion();
5180         }
5181       } else if (isa<AccessSpecDecl>(Mem)) {
5182         // Any access specifier is fine.
5183       } else if (isa<StaticAssertDecl>(Mem)) {
5184         // In C++1z, static_assert declarations are also fine.
5185       } else {
5186         // We have something that isn't a non-static data
5187         // member. Complain about it.
5188         unsigned DK = diag::err_anonymous_record_bad_member;
5189         if (isa<TypeDecl>(Mem))
5190           DK = diag::err_anonymous_record_with_type;
5191         else if (isa<FunctionDecl>(Mem))
5192           DK = diag::err_anonymous_record_with_function;
5193         else if (isa<VarDecl>(Mem))
5194           DK = diag::err_anonymous_record_with_static;
5195 
5196         // Visual C++ allows type definition in anonymous struct or union.
5197         if (getLangOpts().MicrosoftExt &&
5198             DK == diag::err_anonymous_record_with_type)
5199           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5200             << Record->isUnion();
5201         else {
5202           Diag(Mem->getLocation(), DK) << Record->isUnion();
5203           Invalid = true;
5204         }
5205       }
5206     }
5207 
5208     // C++11 [class.union]p8 (DR1460):
5209     //   At most one variant member of a union may have a
5210     //   brace-or-equal-initializer.
5211     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5212         Owner->isRecord())
5213       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5214                                 cast<CXXRecordDecl>(Record));
5215   }
5216 
5217   if (!Record->isUnion() && !Owner->isRecord()) {
5218     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5219       << getLangOpts().CPlusPlus;
5220     Invalid = true;
5221   }
5222 
5223   // C++ [dcl.dcl]p3:
5224   //   [If there are no declarators], and except for the declaration of an
5225   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5226   //   names into the program
5227   // C++ [class.mem]p2:
5228   //   each such member-declaration shall either declare at least one member
5229   //   name of the class or declare at least one unnamed bit-field
5230   //
5231   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5232   if (getLangOpts().CPlusPlus && Record->field_empty())
5233     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5234 
5235   // Mock up a declarator.
5236   Declarator Dc(DS, DeclaratorContext::Member);
5237   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5238   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5239 
5240   // Create a declaration for this anonymous struct/union.
5241   NamedDecl *Anon = nullptr;
5242   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5243     Anon = FieldDecl::Create(
5244         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5245         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5246         /*BitWidth=*/nullptr, /*Mutable=*/false,
5247         /*InitStyle=*/ICIS_NoInit);
5248     Anon->setAccess(AS);
5249     ProcessDeclAttributes(S, Anon, Dc);
5250 
5251     if (getLangOpts().CPlusPlus)
5252       FieldCollector->Add(cast<FieldDecl>(Anon));
5253   } else {
5254     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5255     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5256     if (SCSpec == DeclSpec::SCS_mutable) {
5257       // mutable can only appear on non-static class members, so it's always
5258       // an error here
5259       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5260       Invalid = true;
5261       SC = SC_None;
5262     }
5263 
5264     assert(DS.getAttributes().empty() && "No attribute expected");
5265     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5266                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5267                            Context.getTypeDeclType(Record), TInfo, SC);
5268 
5269     // Default-initialize the implicit variable. This initialization will be
5270     // trivial in almost all cases, except if a union member has an in-class
5271     // initializer:
5272     //   union { int n = 0; };
5273     if (!Invalid)
5274       ActOnUninitializedDecl(Anon);
5275   }
5276   Anon->setImplicit();
5277 
5278   // Mark this as an anonymous struct/union type.
5279   Record->setAnonymousStructOrUnion(true);
5280 
5281   // Add the anonymous struct/union object to the current
5282   // context. We'll be referencing this object when we refer to one of
5283   // its members.
5284   Owner->addDecl(Anon);
5285 
5286   // Inject the members of the anonymous struct/union into the owning
5287   // context and into the identifier resolver chain for name lookup
5288   // purposes.
5289   SmallVector<NamedDecl*, 2> Chain;
5290   Chain.push_back(Anon);
5291 
5292   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5293     Invalid = true;
5294 
5295   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5296     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5297       MangleNumberingContext *MCtx;
5298       Decl *ManglingContextDecl;
5299       std::tie(MCtx, ManglingContextDecl) =
5300           getCurrentMangleNumberContext(NewVD->getDeclContext());
5301       if (MCtx) {
5302         Context.setManglingNumber(
5303             NewVD, MCtx->getManglingNumber(
5304                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5305         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5306       }
5307     }
5308   }
5309 
5310   if (Invalid)
5311     Anon->setInvalidDecl();
5312 
5313   return Anon;
5314 }
5315 
5316 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5317 /// Microsoft C anonymous structure.
5318 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5319 /// Example:
5320 ///
5321 /// struct A { int a; };
5322 /// struct B { struct A; int b; };
5323 ///
5324 /// void foo() {
5325 ///   B var;
5326 ///   var.a = 3;
5327 /// }
5328 ///
5329 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5330                                            RecordDecl *Record) {
5331   assert(Record && "expected a record!");
5332 
5333   // Mock up a declarator.
5334   Declarator Dc(DS, DeclaratorContext::TypeName);
5335   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5336   assert(TInfo && "couldn't build declarator info for anonymous struct");
5337 
5338   auto *ParentDecl = cast<RecordDecl>(CurContext);
5339   QualType RecTy = Context.getTypeDeclType(Record);
5340 
5341   // Create a declaration for this anonymous struct.
5342   NamedDecl *Anon =
5343       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5344                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5345                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5346                         /*InitStyle=*/ICIS_NoInit);
5347   Anon->setImplicit();
5348 
5349   // Add the anonymous struct object to the current context.
5350   CurContext->addDecl(Anon);
5351 
5352   // Inject the members of the anonymous struct into the current
5353   // context and into the identifier resolver chain for name lookup
5354   // purposes.
5355   SmallVector<NamedDecl*, 2> Chain;
5356   Chain.push_back(Anon);
5357 
5358   RecordDecl *RecordDef = Record->getDefinition();
5359   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5360                                diag::err_field_incomplete_or_sizeless) ||
5361       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5362                                           AS_none, Chain)) {
5363     Anon->setInvalidDecl();
5364     ParentDecl->setInvalidDecl();
5365   }
5366 
5367   return Anon;
5368 }
5369 
5370 /// GetNameForDeclarator - Determine the full declaration name for the
5371 /// given Declarator.
5372 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5373   return GetNameFromUnqualifiedId(D.getName());
5374 }
5375 
5376 /// Retrieves the declaration name from a parsed unqualified-id.
5377 DeclarationNameInfo
5378 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5379   DeclarationNameInfo NameInfo;
5380   NameInfo.setLoc(Name.StartLocation);
5381 
5382   switch (Name.getKind()) {
5383 
5384   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5385   case UnqualifiedIdKind::IK_Identifier:
5386     NameInfo.setName(Name.Identifier);
5387     return NameInfo;
5388 
5389   case UnqualifiedIdKind::IK_DeductionGuideName: {
5390     // C++ [temp.deduct.guide]p3:
5391     //   The simple-template-id shall name a class template specialization.
5392     //   The template-name shall be the same identifier as the template-name
5393     //   of the simple-template-id.
5394     // These together intend to imply that the template-name shall name a
5395     // class template.
5396     // FIXME: template<typename T> struct X {};
5397     //        template<typename T> using Y = X<T>;
5398     //        Y(int) -> Y<int>;
5399     //   satisfies these rules but does not name a class template.
5400     TemplateName TN = Name.TemplateName.get().get();
5401     auto *Template = TN.getAsTemplateDecl();
5402     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5403       Diag(Name.StartLocation,
5404            diag::err_deduction_guide_name_not_class_template)
5405         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5406       if (Template)
5407         Diag(Template->getLocation(), diag::note_template_decl_here);
5408       return DeclarationNameInfo();
5409     }
5410 
5411     NameInfo.setName(
5412         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5413     return NameInfo;
5414   }
5415 
5416   case UnqualifiedIdKind::IK_OperatorFunctionId:
5417     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5418                                            Name.OperatorFunctionId.Operator));
5419     NameInfo.setCXXOperatorNameRange(SourceRange(
5420         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5421     return NameInfo;
5422 
5423   case UnqualifiedIdKind::IK_LiteralOperatorId:
5424     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5425                                                            Name.Identifier));
5426     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5427     return NameInfo;
5428 
5429   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5430     TypeSourceInfo *TInfo;
5431     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5432     if (Ty.isNull())
5433       return DeclarationNameInfo();
5434     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5435                                                Context.getCanonicalType(Ty)));
5436     NameInfo.setNamedTypeInfo(TInfo);
5437     return NameInfo;
5438   }
5439 
5440   case UnqualifiedIdKind::IK_ConstructorName: {
5441     TypeSourceInfo *TInfo;
5442     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5443     if (Ty.isNull())
5444       return DeclarationNameInfo();
5445     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5446                                               Context.getCanonicalType(Ty)));
5447     NameInfo.setNamedTypeInfo(TInfo);
5448     return NameInfo;
5449   }
5450 
5451   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5452     // In well-formed code, we can only have a constructor
5453     // template-id that refers to the current context, so go there
5454     // to find the actual type being constructed.
5455     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5456     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5457       return DeclarationNameInfo();
5458 
5459     // Determine the type of the class being constructed.
5460     QualType CurClassType = Context.getTypeDeclType(CurClass);
5461 
5462     // FIXME: Check two things: that the template-id names the same type as
5463     // CurClassType, and that the template-id does not occur when the name
5464     // was qualified.
5465 
5466     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5467                                     Context.getCanonicalType(CurClassType)));
5468     // FIXME: should we retrieve TypeSourceInfo?
5469     NameInfo.setNamedTypeInfo(nullptr);
5470     return NameInfo;
5471   }
5472 
5473   case UnqualifiedIdKind::IK_DestructorName: {
5474     TypeSourceInfo *TInfo;
5475     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5476     if (Ty.isNull())
5477       return DeclarationNameInfo();
5478     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5479                                               Context.getCanonicalType(Ty)));
5480     NameInfo.setNamedTypeInfo(TInfo);
5481     return NameInfo;
5482   }
5483 
5484   case UnqualifiedIdKind::IK_TemplateId: {
5485     TemplateName TName = Name.TemplateId->Template.get();
5486     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5487     return Context.getNameForTemplate(TName, TNameLoc);
5488   }
5489 
5490   } // switch (Name.getKind())
5491 
5492   llvm_unreachable("Unknown name kind");
5493 }
5494 
5495 static QualType getCoreType(QualType Ty) {
5496   do {
5497     if (Ty->isPointerType() || Ty->isReferenceType())
5498       Ty = Ty->getPointeeType();
5499     else if (Ty->isArrayType())
5500       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5501     else
5502       return Ty.withoutLocalFastQualifiers();
5503   } while (true);
5504 }
5505 
5506 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5507 /// and Definition have "nearly" matching parameters. This heuristic is
5508 /// used to improve diagnostics in the case where an out-of-line function
5509 /// definition doesn't match any declaration within the class or namespace.
5510 /// Also sets Params to the list of indices to the parameters that differ
5511 /// between the declaration and the definition. If hasSimilarParameters
5512 /// returns true and Params is empty, then all of the parameters match.
5513 static bool hasSimilarParameters(ASTContext &Context,
5514                                      FunctionDecl *Declaration,
5515                                      FunctionDecl *Definition,
5516                                      SmallVectorImpl<unsigned> &Params) {
5517   Params.clear();
5518   if (Declaration->param_size() != Definition->param_size())
5519     return false;
5520   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5521     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5522     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5523 
5524     // The parameter types are identical
5525     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5526       continue;
5527 
5528     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5529     QualType DefParamBaseTy = getCoreType(DefParamTy);
5530     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5531     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5532 
5533     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5534         (DeclTyName && DeclTyName == DefTyName))
5535       Params.push_back(Idx);
5536     else  // The two parameters aren't even close
5537       return false;
5538   }
5539 
5540   return true;
5541 }
5542 
5543 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5544 /// declarator needs to be rebuilt in the current instantiation.
5545 /// Any bits of declarator which appear before the name are valid for
5546 /// consideration here.  That's specifically the type in the decl spec
5547 /// and the base type in any member-pointer chunks.
5548 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5549                                                     DeclarationName Name) {
5550   // The types we specifically need to rebuild are:
5551   //   - typenames, typeofs, and decltypes
5552   //   - types which will become injected class names
5553   // Of course, we also need to rebuild any type referencing such a
5554   // type.  It's safest to just say "dependent", but we call out a
5555   // few cases here.
5556 
5557   DeclSpec &DS = D.getMutableDeclSpec();
5558   switch (DS.getTypeSpecType()) {
5559   case DeclSpec::TST_typename:
5560   case DeclSpec::TST_typeofType:
5561   case DeclSpec::TST_underlyingType:
5562   case DeclSpec::TST_atomic: {
5563     // Grab the type from the parser.
5564     TypeSourceInfo *TSI = nullptr;
5565     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5566     if (T.isNull() || !T->isInstantiationDependentType()) break;
5567 
5568     // Make sure there's a type source info.  This isn't really much
5569     // of a waste; most dependent types should have type source info
5570     // attached already.
5571     if (!TSI)
5572       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5573 
5574     // Rebuild the type in the current instantiation.
5575     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5576     if (!TSI) return true;
5577 
5578     // Store the new type back in the decl spec.
5579     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5580     DS.UpdateTypeRep(LocType);
5581     break;
5582   }
5583 
5584   case DeclSpec::TST_decltype:
5585   case DeclSpec::TST_typeofExpr: {
5586     Expr *E = DS.getRepAsExpr();
5587     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5588     if (Result.isInvalid()) return true;
5589     DS.UpdateExprRep(Result.get());
5590     break;
5591   }
5592 
5593   default:
5594     // Nothing to do for these decl specs.
5595     break;
5596   }
5597 
5598   // It doesn't matter what order we do this in.
5599   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5600     DeclaratorChunk &Chunk = D.getTypeObject(I);
5601 
5602     // The only type information in the declarator which can come
5603     // before the declaration name is the base type of a member
5604     // pointer.
5605     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5606       continue;
5607 
5608     // Rebuild the scope specifier in-place.
5609     CXXScopeSpec &SS = Chunk.Mem.Scope();
5610     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5611       return true;
5612   }
5613 
5614   return false;
5615 }
5616 
5617 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5618   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5619   // of system decl.
5620   if (D->getPreviousDecl() || D->isImplicit())
5621     return;
5622   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5623   if (Status != ReservedIdentifierStatus::NotReserved &&
5624       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5625     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5626         << D << static_cast<int>(Status);
5627 }
5628 
5629 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5630   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5631   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5632 
5633   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5634       Dcl && Dcl->getDeclContext()->isFileContext())
5635     Dcl->setTopLevelDeclInObjCContainer();
5636 
5637   return Dcl;
5638 }
5639 
5640 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5641 ///   If T is the name of a class, then each of the following shall have a
5642 ///   name different from T:
5643 ///     - every static data member of class T;
5644 ///     - every member function of class T
5645 ///     - every member of class T that is itself a type;
5646 /// \returns true if the declaration name violates these rules.
5647 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5648                                    DeclarationNameInfo NameInfo) {
5649   DeclarationName Name = NameInfo.getName();
5650 
5651   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5652   while (Record && Record->isAnonymousStructOrUnion())
5653     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5654   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5655     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5656     return true;
5657   }
5658 
5659   return false;
5660 }
5661 
5662 /// Diagnose a declaration whose declarator-id has the given
5663 /// nested-name-specifier.
5664 ///
5665 /// \param SS The nested-name-specifier of the declarator-id.
5666 ///
5667 /// \param DC The declaration context to which the nested-name-specifier
5668 /// resolves.
5669 ///
5670 /// \param Name The name of the entity being declared.
5671 ///
5672 /// \param Loc The location of the name of the entity being declared.
5673 ///
5674 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5675 /// we're declaring an explicit / partial specialization / instantiation.
5676 ///
5677 /// \returns true if we cannot safely recover from this error, false otherwise.
5678 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5679                                         DeclarationName Name,
5680                                         SourceLocation Loc, bool IsTemplateId) {
5681   DeclContext *Cur = CurContext;
5682   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5683     Cur = Cur->getParent();
5684 
5685   // If the user provided a superfluous scope specifier that refers back to the
5686   // class in which the entity is already declared, diagnose and ignore it.
5687   //
5688   // class X {
5689   //   void X::f();
5690   // };
5691   //
5692   // Note, it was once ill-formed to give redundant qualification in all
5693   // contexts, but that rule was removed by DR482.
5694   if (Cur->Equals(DC)) {
5695     if (Cur->isRecord()) {
5696       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5697                                       : diag::err_member_extra_qualification)
5698         << Name << FixItHint::CreateRemoval(SS.getRange());
5699       SS.clear();
5700     } else {
5701       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5702     }
5703     return false;
5704   }
5705 
5706   // Check whether the qualifying scope encloses the scope of the original
5707   // declaration. For a template-id, we perform the checks in
5708   // CheckTemplateSpecializationScope.
5709   if (!Cur->Encloses(DC) && !IsTemplateId) {
5710     if (Cur->isRecord())
5711       Diag(Loc, diag::err_member_qualification)
5712         << Name << SS.getRange();
5713     else if (isa<TranslationUnitDecl>(DC))
5714       Diag(Loc, diag::err_invalid_declarator_global_scope)
5715         << Name << SS.getRange();
5716     else if (isa<FunctionDecl>(Cur))
5717       Diag(Loc, diag::err_invalid_declarator_in_function)
5718         << Name << SS.getRange();
5719     else if (isa<BlockDecl>(Cur))
5720       Diag(Loc, diag::err_invalid_declarator_in_block)
5721         << Name << SS.getRange();
5722     else
5723       Diag(Loc, diag::err_invalid_declarator_scope)
5724       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5725 
5726     return true;
5727   }
5728 
5729   if (Cur->isRecord()) {
5730     // Cannot qualify members within a class.
5731     Diag(Loc, diag::err_member_qualification)
5732       << Name << SS.getRange();
5733     SS.clear();
5734 
5735     // C++ constructors and destructors with incorrect scopes can break
5736     // our AST invariants by having the wrong underlying types. If
5737     // that's the case, then drop this declaration entirely.
5738     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5739          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5740         !Context.hasSameType(Name.getCXXNameType(),
5741                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5742       return true;
5743 
5744     return false;
5745   }
5746 
5747   // C++11 [dcl.meaning]p1:
5748   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5749   //   not begin with a decltype-specifer"
5750   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5751   while (SpecLoc.getPrefix())
5752     SpecLoc = SpecLoc.getPrefix();
5753   if (dyn_cast_or_null<DecltypeType>(
5754         SpecLoc.getNestedNameSpecifier()->getAsType()))
5755     Diag(Loc, diag::err_decltype_in_declarator)
5756       << SpecLoc.getTypeLoc().getSourceRange();
5757 
5758   return false;
5759 }
5760 
5761 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5762                                   MultiTemplateParamsArg TemplateParamLists) {
5763   // TODO: consider using NameInfo for diagnostic.
5764   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5765   DeclarationName Name = NameInfo.getName();
5766 
5767   // All of these full declarators require an identifier.  If it doesn't have
5768   // one, the ParsedFreeStandingDeclSpec action should be used.
5769   if (D.isDecompositionDeclarator()) {
5770     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5771   } else if (!Name) {
5772     if (!D.isInvalidType())  // Reject this if we think it is valid.
5773       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5774           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5775     return nullptr;
5776   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5777     return nullptr;
5778 
5779   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5780   // we find one that is.
5781   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5782          (S->getFlags() & Scope::TemplateParamScope) != 0)
5783     S = S->getParent();
5784 
5785   DeclContext *DC = CurContext;
5786   if (D.getCXXScopeSpec().isInvalid())
5787     D.setInvalidType();
5788   else if (D.getCXXScopeSpec().isSet()) {
5789     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5790                                         UPPC_DeclarationQualifier))
5791       return nullptr;
5792 
5793     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5794     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5795     if (!DC || isa<EnumDecl>(DC)) {
5796       // If we could not compute the declaration context, it's because the
5797       // declaration context is dependent but does not refer to a class,
5798       // class template, or class template partial specialization. Complain
5799       // and return early, to avoid the coming semantic disaster.
5800       Diag(D.getIdentifierLoc(),
5801            diag::err_template_qualified_declarator_no_match)
5802         << D.getCXXScopeSpec().getScopeRep()
5803         << D.getCXXScopeSpec().getRange();
5804       return nullptr;
5805     }
5806     bool IsDependentContext = DC->isDependentContext();
5807 
5808     if (!IsDependentContext &&
5809         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5810       return nullptr;
5811 
5812     // If a class is incomplete, do not parse entities inside it.
5813     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5814       Diag(D.getIdentifierLoc(),
5815            diag::err_member_def_undefined_record)
5816         << Name << DC << D.getCXXScopeSpec().getRange();
5817       return nullptr;
5818     }
5819     if (!D.getDeclSpec().isFriendSpecified()) {
5820       if (diagnoseQualifiedDeclaration(
5821               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5822               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5823         if (DC->isRecord())
5824           return nullptr;
5825 
5826         D.setInvalidType();
5827       }
5828     }
5829 
5830     // Check whether we need to rebuild the type of the given
5831     // declaration in the current instantiation.
5832     if (EnteringContext && IsDependentContext &&
5833         TemplateParamLists.size() != 0) {
5834       ContextRAII SavedContext(*this, DC);
5835       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5836         D.setInvalidType();
5837     }
5838   }
5839 
5840   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5841   QualType R = TInfo->getType();
5842 
5843   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5844                                       UPPC_DeclarationType))
5845     D.setInvalidType();
5846 
5847   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5848                         forRedeclarationInCurContext());
5849 
5850   // See if this is a redefinition of a variable in the same scope.
5851   if (!D.getCXXScopeSpec().isSet()) {
5852     bool IsLinkageLookup = false;
5853     bool CreateBuiltins = false;
5854 
5855     // If the declaration we're planning to build will be a function
5856     // or object with linkage, then look for another declaration with
5857     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5858     //
5859     // If the declaration we're planning to build will be declared with
5860     // external linkage in the translation unit, create any builtin with
5861     // the same name.
5862     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5863       /* Do nothing*/;
5864     else if (CurContext->isFunctionOrMethod() &&
5865              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5866               R->isFunctionType())) {
5867       IsLinkageLookup = true;
5868       CreateBuiltins =
5869           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5870     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5871                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5872       CreateBuiltins = true;
5873 
5874     if (IsLinkageLookup) {
5875       Previous.clear(LookupRedeclarationWithLinkage);
5876       Previous.setRedeclarationKind(ForExternalRedeclaration);
5877     }
5878 
5879     LookupName(Previous, S, CreateBuiltins);
5880   } else { // Something like "int foo::x;"
5881     LookupQualifiedName(Previous, DC);
5882 
5883     // C++ [dcl.meaning]p1:
5884     //   When the declarator-id is qualified, the declaration shall refer to a
5885     //  previously declared member of the class or namespace to which the
5886     //  qualifier refers (or, in the case of a namespace, of an element of the
5887     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5888     //  thereof; [...]
5889     //
5890     // Note that we already checked the context above, and that we do not have
5891     // enough information to make sure that Previous contains the declaration
5892     // we want to match. For example, given:
5893     //
5894     //   class X {
5895     //     void f();
5896     //     void f(float);
5897     //   };
5898     //
5899     //   void X::f(int) { } // ill-formed
5900     //
5901     // In this case, Previous will point to the overload set
5902     // containing the two f's declared in X, but neither of them
5903     // matches.
5904 
5905     // C++ [dcl.meaning]p1:
5906     //   [...] the member shall not merely have been introduced by a
5907     //   using-declaration in the scope of the class or namespace nominated by
5908     //   the nested-name-specifier of the declarator-id.
5909     RemoveUsingDecls(Previous);
5910   }
5911 
5912   if (Previous.isSingleResult() &&
5913       Previous.getFoundDecl()->isTemplateParameter()) {
5914     // Maybe we will complain about the shadowed template parameter.
5915     if (!D.isInvalidType())
5916       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5917                                       Previous.getFoundDecl());
5918 
5919     // Just pretend that we didn't see the previous declaration.
5920     Previous.clear();
5921   }
5922 
5923   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5924     // Forget that the previous declaration is the injected-class-name.
5925     Previous.clear();
5926 
5927   // In C++, the previous declaration we find might be a tag type
5928   // (class or enum). In this case, the new declaration will hide the
5929   // tag type. Note that this applies to functions, function templates, and
5930   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5931   if (Previous.isSingleTagDecl() &&
5932       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5933       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5934     Previous.clear();
5935 
5936   // Check that there are no default arguments other than in the parameters
5937   // of a function declaration (C++ only).
5938   if (getLangOpts().CPlusPlus)
5939     CheckExtraCXXDefaultArguments(D);
5940 
5941   NamedDecl *New;
5942 
5943   bool AddToScope = true;
5944   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5945     if (TemplateParamLists.size()) {
5946       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5947       return nullptr;
5948     }
5949 
5950     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5951   } else if (R->isFunctionType()) {
5952     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5953                                   TemplateParamLists,
5954                                   AddToScope);
5955   } else {
5956     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5957                                   AddToScope);
5958   }
5959 
5960   if (!New)
5961     return nullptr;
5962 
5963   // If this has an identifier and is not a function template specialization,
5964   // add it to the scope stack.
5965   if (New->getDeclName() && AddToScope)
5966     PushOnScopeChains(New, S);
5967 
5968   if (isInOpenMPDeclareTargetContext())
5969     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5970 
5971   return New;
5972 }
5973 
5974 /// Helper method to turn variable array types into constant array
5975 /// types in certain situations which would otherwise be errors (for
5976 /// GCC compatibility).
5977 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5978                                                     ASTContext &Context,
5979                                                     bool &SizeIsNegative,
5980                                                     llvm::APSInt &Oversized) {
5981   // This method tries to turn a variable array into a constant
5982   // array even when the size isn't an ICE.  This is necessary
5983   // for compatibility with code that depends on gcc's buggy
5984   // constant expression folding, like struct {char x[(int)(char*)2];}
5985   SizeIsNegative = false;
5986   Oversized = 0;
5987 
5988   if (T->isDependentType())
5989     return QualType();
5990 
5991   QualifierCollector Qs;
5992   const Type *Ty = Qs.strip(T);
5993 
5994   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5995     QualType Pointee = PTy->getPointeeType();
5996     QualType FixedType =
5997         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5998                                             Oversized);
5999     if (FixedType.isNull()) return FixedType;
6000     FixedType = Context.getPointerType(FixedType);
6001     return Qs.apply(Context, FixedType);
6002   }
6003   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6004     QualType Inner = PTy->getInnerType();
6005     QualType FixedType =
6006         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6007                                             Oversized);
6008     if (FixedType.isNull()) return FixedType;
6009     FixedType = Context.getParenType(FixedType);
6010     return Qs.apply(Context, FixedType);
6011   }
6012 
6013   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6014   if (!VLATy)
6015     return QualType();
6016 
6017   QualType ElemTy = VLATy->getElementType();
6018   if (ElemTy->isVariablyModifiedType()) {
6019     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6020                                                  SizeIsNegative, Oversized);
6021     if (ElemTy.isNull())
6022       return QualType();
6023   }
6024 
6025   Expr::EvalResult Result;
6026   if (!VLATy->getSizeExpr() ||
6027       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6028     return QualType();
6029 
6030   llvm::APSInt Res = Result.Val.getInt();
6031 
6032   // Check whether the array size is negative.
6033   if (Res.isSigned() && Res.isNegative()) {
6034     SizeIsNegative = true;
6035     return QualType();
6036   }
6037 
6038   // Check whether the array is too large to be addressed.
6039   unsigned ActiveSizeBits =
6040       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6041        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6042           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6043           : Res.getActiveBits();
6044   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6045     Oversized = Res;
6046     return QualType();
6047   }
6048 
6049   QualType FoldedArrayType = Context.getConstantArrayType(
6050       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6051   return Qs.apply(Context, FoldedArrayType);
6052 }
6053 
6054 static void
6055 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6056   SrcTL = SrcTL.getUnqualifiedLoc();
6057   DstTL = DstTL.getUnqualifiedLoc();
6058   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6059     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6060     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6061                                       DstPTL.getPointeeLoc());
6062     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6063     return;
6064   }
6065   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6066     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6067     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6068                                       DstPTL.getInnerLoc());
6069     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6070     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6071     return;
6072   }
6073   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6074   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6075   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6076   TypeLoc DstElemTL = DstATL.getElementLoc();
6077   if (VariableArrayTypeLoc SrcElemATL =
6078           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6079     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6080     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6081   } else {
6082     DstElemTL.initializeFullCopy(SrcElemTL);
6083   }
6084   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6085   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6086   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6087 }
6088 
6089 /// Helper method to turn variable array types into constant array
6090 /// types in certain situations which would otherwise be errors (for
6091 /// GCC compatibility).
6092 static TypeSourceInfo*
6093 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6094                                               ASTContext &Context,
6095                                               bool &SizeIsNegative,
6096                                               llvm::APSInt &Oversized) {
6097   QualType FixedTy
6098     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6099                                           SizeIsNegative, Oversized);
6100   if (FixedTy.isNull())
6101     return nullptr;
6102   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6103   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6104                                     FixedTInfo->getTypeLoc());
6105   return FixedTInfo;
6106 }
6107 
6108 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6109 /// true if we were successful.
6110 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6111                                            QualType &T, SourceLocation Loc,
6112                                            unsigned FailedFoldDiagID) {
6113   bool SizeIsNegative;
6114   llvm::APSInt Oversized;
6115   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6116       TInfo, Context, SizeIsNegative, Oversized);
6117   if (FixedTInfo) {
6118     Diag(Loc, diag::ext_vla_folded_to_constant);
6119     TInfo = FixedTInfo;
6120     T = FixedTInfo->getType();
6121     return true;
6122   }
6123 
6124   if (SizeIsNegative)
6125     Diag(Loc, diag::err_typecheck_negative_array_size);
6126   else if (Oversized.getBoolValue())
6127     Diag(Loc, diag::err_array_too_large) << Oversized.toString(10);
6128   else if (FailedFoldDiagID)
6129     Diag(Loc, FailedFoldDiagID);
6130   return false;
6131 }
6132 
6133 /// Register the given locally-scoped extern "C" declaration so
6134 /// that it can be found later for redeclarations. We include any extern "C"
6135 /// declaration that is not visible in the translation unit here, not just
6136 /// function-scope declarations.
6137 void
6138 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6139   if (!getLangOpts().CPlusPlus &&
6140       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6141     // Don't need to track declarations in the TU in C.
6142     return;
6143 
6144   // Note that we have a locally-scoped external with this name.
6145   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6146 }
6147 
6148 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6149   // FIXME: We can have multiple results via __attribute__((overloadable)).
6150   auto Result = Context.getExternCContextDecl()->lookup(Name);
6151   return Result.empty() ? nullptr : *Result.begin();
6152 }
6153 
6154 /// Diagnose function specifiers on a declaration of an identifier that
6155 /// does not identify a function.
6156 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6157   // FIXME: We should probably indicate the identifier in question to avoid
6158   // confusion for constructs like "virtual int a(), b;"
6159   if (DS.isVirtualSpecified())
6160     Diag(DS.getVirtualSpecLoc(),
6161          diag::err_virtual_non_function);
6162 
6163   if (DS.hasExplicitSpecifier())
6164     Diag(DS.getExplicitSpecLoc(),
6165          diag::err_explicit_non_function);
6166 
6167   if (DS.isNoreturnSpecified())
6168     Diag(DS.getNoreturnSpecLoc(),
6169          diag::err_noreturn_non_function);
6170 }
6171 
6172 NamedDecl*
6173 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6174                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6175   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6176   if (D.getCXXScopeSpec().isSet()) {
6177     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6178       << D.getCXXScopeSpec().getRange();
6179     D.setInvalidType();
6180     // Pretend we didn't see the scope specifier.
6181     DC = CurContext;
6182     Previous.clear();
6183   }
6184 
6185   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6186 
6187   if (D.getDeclSpec().isInlineSpecified())
6188     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6189         << getLangOpts().CPlusPlus17;
6190   if (D.getDeclSpec().hasConstexprSpecifier())
6191     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6192         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6193 
6194   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6195     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6196       Diag(D.getName().StartLocation,
6197            diag::err_deduction_guide_invalid_specifier)
6198           << "typedef";
6199     else
6200       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6201           << D.getName().getSourceRange();
6202     return nullptr;
6203   }
6204 
6205   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6206   if (!NewTD) return nullptr;
6207 
6208   // Handle attributes prior to checking for duplicates in MergeVarDecl
6209   ProcessDeclAttributes(S, NewTD, D);
6210 
6211   CheckTypedefForVariablyModifiedType(S, NewTD);
6212 
6213   bool Redeclaration = D.isRedeclaration();
6214   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6215   D.setRedeclaration(Redeclaration);
6216   return ND;
6217 }
6218 
6219 void
6220 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6221   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6222   // then it shall have block scope.
6223   // Note that variably modified types must be fixed before merging the decl so
6224   // that redeclarations will match.
6225   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6226   QualType T = TInfo->getType();
6227   if (T->isVariablyModifiedType()) {
6228     setFunctionHasBranchProtectedScope();
6229 
6230     if (S->getFnParent() == nullptr) {
6231       bool SizeIsNegative;
6232       llvm::APSInt Oversized;
6233       TypeSourceInfo *FixedTInfo =
6234         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6235                                                       SizeIsNegative,
6236                                                       Oversized);
6237       if (FixedTInfo) {
6238         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6239         NewTD->setTypeSourceInfo(FixedTInfo);
6240       } else {
6241         if (SizeIsNegative)
6242           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6243         else if (T->isVariableArrayType())
6244           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6245         else if (Oversized.getBoolValue())
6246           Diag(NewTD->getLocation(), diag::err_array_too_large)
6247             << Oversized.toString(10);
6248         else
6249           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6250         NewTD->setInvalidDecl();
6251       }
6252     }
6253   }
6254 }
6255 
6256 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6257 /// declares a typedef-name, either using the 'typedef' type specifier or via
6258 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6259 NamedDecl*
6260 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6261                            LookupResult &Previous, bool &Redeclaration) {
6262 
6263   // Find the shadowed declaration before filtering for scope.
6264   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6265 
6266   // Merge the decl with the existing one if appropriate. If the decl is
6267   // in an outer scope, it isn't the same thing.
6268   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6269                        /*AllowInlineNamespace*/false);
6270   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6271   if (!Previous.empty()) {
6272     Redeclaration = true;
6273     MergeTypedefNameDecl(S, NewTD, Previous);
6274   } else {
6275     inferGslPointerAttribute(NewTD);
6276   }
6277 
6278   if (ShadowedDecl && !Redeclaration)
6279     CheckShadow(NewTD, ShadowedDecl, Previous);
6280 
6281   // If this is the C FILE type, notify the AST context.
6282   if (IdentifierInfo *II = NewTD->getIdentifier())
6283     if (!NewTD->isInvalidDecl() &&
6284         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6285       if (II->isStr("FILE"))
6286         Context.setFILEDecl(NewTD);
6287       else if (II->isStr("jmp_buf"))
6288         Context.setjmp_bufDecl(NewTD);
6289       else if (II->isStr("sigjmp_buf"))
6290         Context.setsigjmp_bufDecl(NewTD);
6291       else if (II->isStr("ucontext_t"))
6292         Context.setucontext_tDecl(NewTD);
6293     }
6294 
6295   return NewTD;
6296 }
6297 
6298 /// Determines whether the given declaration is an out-of-scope
6299 /// previous declaration.
6300 ///
6301 /// This routine should be invoked when name lookup has found a
6302 /// previous declaration (PrevDecl) that is not in the scope where a
6303 /// new declaration by the same name is being introduced. If the new
6304 /// declaration occurs in a local scope, previous declarations with
6305 /// linkage may still be considered previous declarations (C99
6306 /// 6.2.2p4-5, C++ [basic.link]p6).
6307 ///
6308 /// \param PrevDecl the previous declaration found by name
6309 /// lookup
6310 ///
6311 /// \param DC the context in which the new declaration is being
6312 /// declared.
6313 ///
6314 /// \returns true if PrevDecl is an out-of-scope previous declaration
6315 /// for a new delcaration with the same name.
6316 static bool
6317 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6318                                 ASTContext &Context) {
6319   if (!PrevDecl)
6320     return false;
6321 
6322   if (!PrevDecl->hasLinkage())
6323     return false;
6324 
6325   if (Context.getLangOpts().CPlusPlus) {
6326     // C++ [basic.link]p6:
6327     //   If there is a visible declaration of an entity with linkage
6328     //   having the same name and type, ignoring entities declared
6329     //   outside the innermost enclosing namespace scope, the block
6330     //   scope declaration declares that same entity and receives the
6331     //   linkage of the previous declaration.
6332     DeclContext *OuterContext = DC->getRedeclContext();
6333     if (!OuterContext->isFunctionOrMethod())
6334       // This rule only applies to block-scope declarations.
6335       return false;
6336 
6337     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6338     if (PrevOuterContext->isRecord())
6339       // We found a member function: ignore it.
6340       return false;
6341 
6342     // Find the innermost enclosing namespace for the new and
6343     // previous declarations.
6344     OuterContext = OuterContext->getEnclosingNamespaceContext();
6345     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6346 
6347     // The previous declaration is in a different namespace, so it
6348     // isn't the same function.
6349     if (!OuterContext->Equals(PrevOuterContext))
6350       return false;
6351   }
6352 
6353   return true;
6354 }
6355 
6356 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6357   CXXScopeSpec &SS = D.getCXXScopeSpec();
6358   if (!SS.isSet()) return;
6359   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6360 }
6361 
6362 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6363   QualType type = decl->getType();
6364   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6365   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6366     // Various kinds of declaration aren't allowed to be __autoreleasing.
6367     unsigned kind = -1U;
6368     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6369       if (var->hasAttr<BlocksAttr>())
6370         kind = 0; // __block
6371       else if (!var->hasLocalStorage())
6372         kind = 1; // global
6373     } else if (isa<ObjCIvarDecl>(decl)) {
6374       kind = 3; // ivar
6375     } else if (isa<FieldDecl>(decl)) {
6376       kind = 2; // field
6377     }
6378 
6379     if (kind != -1U) {
6380       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6381         << kind;
6382     }
6383   } else if (lifetime == Qualifiers::OCL_None) {
6384     // Try to infer lifetime.
6385     if (!type->isObjCLifetimeType())
6386       return false;
6387 
6388     lifetime = type->getObjCARCImplicitLifetime();
6389     type = Context.getLifetimeQualifiedType(type, lifetime);
6390     decl->setType(type);
6391   }
6392 
6393   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6394     // Thread-local variables cannot have lifetime.
6395     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6396         var->getTLSKind()) {
6397       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6398         << var->getType();
6399       return true;
6400     }
6401   }
6402 
6403   return false;
6404 }
6405 
6406 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6407   if (Decl->getType().hasAddressSpace())
6408     return;
6409   if (Decl->getType()->isDependentType())
6410     return;
6411   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6412     QualType Type = Var->getType();
6413     if (Type->isSamplerT() || Type->isVoidType())
6414       return;
6415     LangAS ImplAS = LangAS::opencl_private;
6416     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6417         Var->hasGlobalStorage())
6418       ImplAS = LangAS::opencl_global;
6419     // If the original type from a decayed type is an array type and that array
6420     // type has no address space yet, deduce it now.
6421     if (auto DT = dyn_cast<DecayedType>(Type)) {
6422       auto OrigTy = DT->getOriginalType();
6423       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6424         // Add the address space to the original array type and then propagate
6425         // that to the element type through `getAsArrayType`.
6426         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6427         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6428         // Re-generate the decayed type.
6429         Type = Context.getDecayedType(OrigTy);
6430       }
6431     }
6432     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6433     // Apply any qualifiers (including address space) from the array type to
6434     // the element type. This implements C99 6.7.3p8: "If the specification of
6435     // an array type includes any type qualifiers, the element type is so
6436     // qualified, not the array type."
6437     if (Type->isArrayType())
6438       Type = QualType(Context.getAsArrayType(Type), 0);
6439     Decl->setType(Type);
6440   }
6441 }
6442 
6443 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6444   // Ensure that an auto decl is deduced otherwise the checks below might cache
6445   // the wrong linkage.
6446   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6447 
6448   // 'weak' only applies to declarations with external linkage.
6449   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6450     if (!ND.isExternallyVisible()) {
6451       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6452       ND.dropAttr<WeakAttr>();
6453     }
6454   }
6455   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6456     if (ND.isExternallyVisible()) {
6457       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6458       ND.dropAttr<WeakRefAttr>();
6459       ND.dropAttr<AliasAttr>();
6460     }
6461   }
6462 
6463   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6464     if (VD->hasInit()) {
6465       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6466         assert(VD->isThisDeclarationADefinition() &&
6467                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6468         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6469         VD->dropAttr<AliasAttr>();
6470       }
6471     }
6472   }
6473 
6474   // 'selectany' only applies to externally visible variable declarations.
6475   // It does not apply to functions.
6476   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6477     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6478       S.Diag(Attr->getLocation(),
6479              diag::err_attribute_selectany_non_extern_data);
6480       ND.dropAttr<SelectAnyAttr>();
6481     }
6482   }
6483 
6484   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6485     auto *VD = dyn_cast<VarDecl>(&ND);
6486     bool IsAnonymousNS = false;
6487     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6488     if (VD) {
6489       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6490       while (NS && !IsAnonymousNS) {
6491         IsAnonymousNS = NS->isAnonymousNamespace();
6492         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6493       }
6494     }
6495     // dll attributes require external linkage. Static locals may have external
6496     // linkage but still cannot be explicitly imported or exported.
6497     // In Microsoft mode, a variable defined in anonymous namespace must have
6498     // external linkage in order to be exported.
6499     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6500     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6501         (!AnonNSInMicrosoftMode &&
6502          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6503       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6504         << &ND << Attr;
6505       ND.setInvalidDecl();
6506     }
6507   }
6508 
6509   // Check the attributes on the function type, if any.
6510   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6511     // Don't declare this variable in the second operand of the for-statement;
6512     // GCC miscompiles that by ending its lifetime before evaluating the
6513     // third operand. See gcc.gnu.org/PR86769.
6514     AttributedTypeLoc ATL;
6515     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6516          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6517          TL = ATL.getModifiedLoc()) {
6518       // The [[lifetimebound]] attribute can be applied to the implicit object
6519       // parameter of a non-static member function (other than a ctor or dtor)
6520       // by applying it to the function type.
6521       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6522         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6523         if (!MD || MD->isStatic()) {
6524           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6525               << !MD << A->getRange();
6526         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6527           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6528               << isa<CXXDestructorDecl>(MD) << A->getRange();
6529         }
6530       }
6531     }
6532   }
6533 }
6534 
6535 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6536                                            NamedDecl *NewDecl,
6537                                            bool IsSpecialization,
6538                                            bool IsDefinition) {
6539   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6540     return;
6541 
6542   bool IsTemplate = false;
6543   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6544     OldDecl = OldTD->getTemplatedDecl();
6545     IsTemplate = true;
6546     if (!IsSpecialization)
6547       IsDefinition = false;
6548   }
6549   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6550     NewDecl = NewTD->getTemplatedDecl();
6551     IsTemplate = true;
6552   }
6553 
6554   if (!OldDecl || !NewDecl)
6555     return;
6556 
6557   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6558   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6559   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6560   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6561 
6562   // dllimport and dllexport are inheritable attributes so we have to exclude
6563   // inherited attribute instances.
6564   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6565                     (NewExportAttr && !NewExportAttr->isInherited());
6566 
6567   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6568   // the only exception being explicit specializations.
6569   // Implicitly generated declarations are also excluded for now because there
6570   // is no other way to switch these to use dllimport or dllexport.
6571   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6572 
6573   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6574     // Allow with a warning for free functions and global variables.
6575     bool JustWarn = false;
6576     if (!OldDecl->isCXXClassMember()) {
6577       auto *VD = dyn_cast<VarDecl>(OldDecl);
6578       if (VD && !VD->getDescribedVarTemplate())
6579         JustWarn = true;
6580       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6581       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6582         JustWarn = true;
6583     }
6584 
6585     // We cannot change a declaration that's been used because IR has already
6586     // been emitted. Dllimported functions will still work though (modulo
6587     // address equality) as they can use the thunk.
6588     if (OldDecl->isUsed())
6589       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6590         JustWarn = false;
6591 
6592     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6593                                : diag::err_attribute_dll_redeclaration;
6594     S.Diag(NewDecl->getLocation(), DiagID)
6595         << NewDecl
6596         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6597     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6598     if (!JustWarn) {
6599       NewDecl->setInvalidDecl();
6600       return;
6601     }
6602   }
6603 
6604   // A redeclaration is not allowed to drop a dllimport attribute, the only
6605   // exceptions being inline function definitions (except for function
6606   // templates), local extern declarations, qualified friend declarations or
6607   // special MSVC extension: in the last case, the declaration is treated as if
6608   // it were marked dllexport.
6609   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6610   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6611   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6612     // Ignore static data because out-of-line definitions are diagnosed
6613     // separately.
6614     IsStaticDataMember = VD->isStaticDataMember();
6615     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6616                    VarDecl::DeclarationOnly;
6617   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6618     IsInline = FD->isInlined();
6619     IsQualifiedFriend = FD->getQualifier() &&
6620                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6621   }
6622 
6623   if (OldImportAttr && !HasNewAttr &&
6624       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6625       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6626     if (IsMicrosoftABI && IsDefinition) {
6627       S.Diag(NewDecl->getLocation(),
6628              diag::warn_redeclaration_without_import_attribute)
6629           << NewDecl;
6630       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6631       NewDecl->dropAttr<DLLImportAttr>();
6632       NewDecl->addAttr(
6633           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6634     } else {
6635       S.Diag(NewDecl->getLocation(),
6636              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6637           << NewDecl << OldImportAttr;
6638       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6639       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6640       OldDecl->dropAttr<DLLImportAttr>();
6641       NewDecl->dropAttr<DLLImportAttr>();
6642     }
6643   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6644     // In MinGW, seeing a function declared inline drops the dllimport
6645     // attribute.
6646     OldDecl->dropAttr<DLLImportAttr>();
6647     NewDecl->dropAttr<DLLImportAttr>();
6648     S.Diag(NewDecl->getLocation(),
6649            diag::warn_dllimport_dropped_from_inline_function)
6650         << NewDecl << OldImportAttr;
6651   }
6652 
6653   // A specialization of a class template member function is processed here
6654   // since it's a redeclaration. If the parent class is dllexport, the
6655   // specialization inherits that attribute. This doesn't happen automatically
6656   // since the parent class isn't instantiated until later.
6657   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6658     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6659         !NewImportAttr && !NewExportAttr) {
6660       if (const DLLExportAttr *ParentExportAttr =
6661               MD->getParent()->getAttr<DLLExportAttr>()) {
6662         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6663         NewAttr->setInherited(true);
6664         NewDecl->addAttr(NewAttr);
6665       }
6666     }
6667   }
6668 }
6669 
6670 /// Given that we are within the definition of the given function,
6671 /// will that definition behave like C99's 'inline', where the
6672 /// definition is discarded except for optimization purposes?
6673 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6674   // Try to avoid calling GetGVALinkageForFunction.
6675 
6676   // All cases of this require the 'inline' keyword.
6677   if (!FD->isInlined()) return false;
6678 
6679   // This is only possible in C++ with the gnu_inline attribute.
6680   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6681     return false;
6682 
6683   // Okay, go ahead and call the relatively-more-expensive function.
6684   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6685 }
6686 
6687 /// Determine whether a variable is extern "C" prior to attaching
6688 /// an initializer. We can't just call isExternC() here, because that
6689 /// will also compute and cache whether the declaration is externally
6690 /// visible, which might change when we attach the initializer.
6691 ///
6692 /// This can only be used if the declaration is known to not be a
6693 /// redeclaration of an internal linkage declaration.
6694 ///
6695 /// For instance:
6696 ///
6697 ///   auto x = []{};
6698 ///
6699 /// Attaching the initializer here makes this declaration not externally
6700 /// visible, because its type has internal linkage.
6701 ///
6702 /// FIXME: This is a hack.
6703 template<typename T>
6704 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6705   if (S.getLangOpts().CPlusPlus) {
6706     // In C++, the overloadable attribute negates the effects of extern "C".
6707     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6708       return false;
6709 
6710     // So do CUDA's host/device attributes.
6711     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6712                                  D->template hasAttr<CUDAHostAttr>()))
6713       return false;
6714   }
6715   return D->isExternC();
6716 }
6717 
6718 static bool shouldConsiderLinkage(const VarDecl *VD) {
6719   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6720   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6721       isa<OMPDeclareMapperDecl>(DC))
6722     return VD->hasExternalStorage();
6723   if (DC->isFileContext())
6724     return true;
6725   if (DC->isRecord())
6726     return false;
6727   if (isa<RequiresExprBodyDecl>(DC))
6728     return false;
6729   llvm_unreachable("Unexpected context");
6730 }
6731 
6732 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6733   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6734   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6735       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6736     return true;
6737   if (DC->isRecord())
6738     return false;
6739   llvm_unreachable("Unexpected context");
6740 }
6741 
6742 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6743                           ParsedAttr::Kind Kind) {
6744   // Check decl attributes on the DeclSpec.
6745   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6746     return true;
6747 
6748   // Walk the declarator structure, checking decl attributes that were in a type
6749   // position to the decl itself.
6750   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6751     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6752       return true;
6753   }
6754 
6755   // Finally, check attributes on the decl itself.
6756   return PD.getAttributes().hasAttribute(Kind);
6757 }
6758 
6759 /// Adjust the \c DeclContext for a function or variable that might be a
6760 /// function-local external declaration.
6761 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6762   if (!DC->isFunctionOrMethod())
6763     return false;
6764 
6765   // If this is a local extern function or variable declared within a function
6766   // template, don't add it into the enclosing namespace scope until it is
6767   // instantiated; it might have a dependent type right now.
6768   if (DC->isDependentContext())
6769     return true;
6770 
6771   // C++11 [basic.link]p7:
6772   //   When a block scope declaration of an entity with linkage is not found to
6773   //   refer to some other declaration, then that entity is a member of the
6774   //   innermost enclosing namespace.
6775   //
6776   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6777   // semantically-enclosing namespace, not a lexically-enclosing one.
6778   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6779     DC = DC->getParent();
6780   return true;
6781 }
6782 
6783 /// Returns true if given declaration has external C language linkage.
6784 static bool isDeclExternC(const Decl *D) {
6785   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6786     return FD->isExternC();
6787   if (const auto *VD = dyn_cast<VarDecl>(D))
6788     return VD->isExternC();
6789 
6790   llvm_unreachable("Unknown type of decl!");
6791 }
6792 
6793 /// Returns true if there hasn't been any invalid type diagnosed.
6794 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6795   DeclContext *DC = NewVD->getDeclContext();
6796   QualType R = NewVD->getType();
6797 
6798   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6799   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6800   // argument.
6801   if (R->isImageType() || R->isPipeType()) {
6802     Se.Diag(NewVD->getLocation(),
6803             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6804         << R;
6805     NewVD->setInvalidDecl();
6806     return false;
6807   }
6808 
6809   // OpenCL v1.2 s6.9.r:
6810   // The event type cannot be used to declare a program scope variable.
6811   // OpenCL v2.0 s6.9.q:
6812   // The clk_event_t and reserve_id_t types cannot be declared in program
6813   // scope.
6814   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6815     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6816       Se.Diag(NewVD->getLocation(),
6817               diag::err_invalid_type_for_program_scope_var)
6818           << R;
6819       NewVD->setInvalidDecl();
6820       return false;
6821     }
6822   }
6823 
6824   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6825   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6826                                                Se.getLangOpts())) {
6827     QualType NR = R.getCanonicalType();
6828     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6829            NR->isReferenceType()) {
6830       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6831           NR->isFunctionReferenceType()) {
6832         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6833             << NR->isReferenceType();
6834         NewVD->setInvalidDecl();
6835         return false;
6836       }
6837       NR = NR->getPointeeType();
6838     }
6839   }
6840 
6841   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6842                                                Se.getLangOpts())) {
6843     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6844     // half array type (unless the cl_khr_fp16 extension is enabled).
6845     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6846       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6847       NewVD->setInvalidDecl();
6848       return false;
6849     }
6850   }
6851 
6852   // OpenCL v1.2 s6.9.r:
6853   // The event type cannot be used with the __local, __constant and __global
6854   // address space qualifiers.
6855   if (R->isEventT()) {
6856     if (R.getAddressSpace() != LangAS::opencl_private) {
6857       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6858       NewVD->setInvalidDecl();
6859       return false;
6860     }
6861   }
6862 
6863   if (R->isSamplerT()) {
6864     // OpenCL v1.2 s6.9.b p4:
6865     // The sampler type cannot be used with the __local and __global address
6866     // space qualifiers.
6867     if (R.getAddressSpace() == LangAS::opencl_local ||
6868         R.getAddressSpace() == LangAS::opencl_global) {
6869       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6870       NewVD->setInvalidDecl();
6871     }
6872 
6873     // OpenCL v1.2 s6.12.14.1:
6874     // A global sampler must be declared with either the constant address
6875     // space qualifier or with the const qualifier.
6876     if (DC->isTranslationUnit() &&
6877         !(R.getAddressSpace() == LangAS::opencl_constant ||
6878           R.isConstQualified())) {
6879       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6880       NewVD->setInvalidDecl();
6881     }
6882     if (NewVD->isInvalidDecl())
6883       return false;
6884   }
6885 
6886   return true;
6887 }
6888 
6889 template <typename AttrTy>
6890 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6891   const TypedefNameDecl *TND = TT->getDecl();
6892   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6893     AttrTy *Clone = Attribute->clone(S.Context);
6894     Clone->setInherited(true);
6895     D->addAttr(Clone);
6896   }
6897 }
6898 
6899 NamedDecl *Sema::ActOnVariableDeclarator(
6900     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6901     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6902     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6903   QualType R = TInfo->getType();
6904   DeclarationName Name = GetNameForDeclarator(D).getName();
6905 
6906   IdentifierInfo *II = Name.getAsIdentifierInfo();
6907 
6908   if (D.isDecompositionDeclarator()) {
6909     // Take the name of the first declarator as our name for diagnostic
6910     // purposes.
6911     auto &Decomp = D.getDecompositionDeclarator();
6912     if (!Decomp.bindings().empty()) {
6913       II = Decomp.bindings()[0].Name;
6914       Name = II;
6915     }
6916   } else if (!II) {
6917     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6918     return nullptr;
6919   }
6920 
6921 
6922   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6923   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6924 
6925   // dllimport globals without explicit storage class are treated as extern. We
6926   // have to change the storage class this early to get the right DeclContext.
6927   if (SC == SC_None && !DC->isRecord() &&
6928       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6929       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6930     SC = SC_Extern;
6931 
6932   DeclContext *OriginalDC = DC;
6933   bool IsLocalExternDecl = SC == SC_Extern &&
6934                            adjustContextForLocalExternDecl(DC);
6935 
6936   if (SCSpec == DeclSpec::SCS_mutable) {
6937     // mutable can only appear on non-static class members, so it's always
6938     // an error here
6939     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6940     D.setInvalidType();
6941     SC = SC_None;
6942   }
6943 
6944   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6945       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6946                               D.getDeclSpec().getStorageClassSpecLoc())) {
6947     // In C++11, the 'register' storage class specifier is deprecated.
6948     // Suppress the warning in system macros, it's used in macros in some
6949     // popular C system headers, such as in glibc's htonl() macro.
6950     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6951          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6952                                    : diag::warn_deprecated_register)
6953       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6954   }
6955 
6956   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6957 
6958   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6959     // C99 6.9p2: The storage-class specifiers auto and register shall not
6960     // appear in the declaration specifiers in an external declaration.
6961     // Global Register+Asm is a GNU extension we support.
6962     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6963       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6964       D.setInvalidType();
6965     }
6966   }
6967 
6968   // If this variable has a VLA type and an initializer, try to
6969   // fold to a constant-sized type. This is otherwise invalid.
6970   if (D.hasInitializer() && R->isVariableArrayType())
6971     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6972                                     /*DiagID=*/0);
6973 
6974   bool IsMemberSpecialization = false;
6975   bool IsVariableTemplateSpecialization = false;
6976   bool IsPartialSpecialization = false;
6977   bool IsVariableTemplate = false;
6978   VarDecl *NewVD = nullptr;
6979   VarTemplateDecl *NewTemplate = nullptr;
6980   TemplateParameterList *TemplateParams = nullptr;
6981   if (!getLangOpts().CPlusPlus) {
6982     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6983                             II, R, TInfo, SC);
6984 
6985     if (R->getContainedDeducedType())
6986       ParsingInitForAutoVars.insert(NewVD);
6987 
6988     if (D.isInvalidType())
6989       NewVD->setInvalidDecl();
6990 
6991     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6992         NewVD->hasLocalStorage())
6993       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6994                             NTCUC_AutoVar, NTCUK_Destruct);
6995   } else {
6996     bool Invalid = false;
6997 
6998     if (DC->isRecord() && !CurContext->isRecord()) {
6999       // This is an out-of-line definition of a static data member.
7000       switch (SC) {
7001       case SC_None:
7002         break;
7003       case SC_Static:
7004         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7005              diag::err_static_out_of_line)
7006           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7007         break;
7008       case SC_Auto:
7009       case SC_Register:
7010       case SC_Extern:
7011         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7012         // to names of variables declared in a block or to function parameters.
7013         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7014         // of class members
7015 
7016         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7017              diag::err_storage_class_for_static_member)
7018           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7019         break;
7020       case SC_PrivateExtern:
7021         llvm_unreachable("C storage class in c++!");
7022       }
7023     }
7024 
7025     if (SC == SC_Static && CurContext->isRecord()) {
7026       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7027         // Walk up the enclosing DeclContexts to check for any that are
7028         // incompatible with static data members.
7029         const DeclContext *FunctionOrMethod = nullptr;
7030         const CXXRecordDecl *AnonStruct = nullptr;
7031         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7032           if (Ctxt->isFunctionOrMethod()) {
7033             FunctionOrMethod = Ctxt;
7034             break;
7035           }
7036           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7037           if (ParentDecl && !ParentDecl->getDeclName()) {
7038             AnonStruct = ParentDecl;
7039             break;
7040           }
7041         }
7042         if (FunctionOrMethod) {
7043           // C++ [class.static.data]p5: A local class shall not have static data
7044           // members.
7045           Diag(D.getIdentifierLoc(),
7046                diag::err_static_data_member_not_allowed_in_local_class)
7047             << Name << RD->getDeclName() << RD->getTagKind();
7048         } else if (AnonStruct) {
7049           // C++ [class.static.data]p4: Unnamed classes and classes contained
7050           // directly or indirectly within unnamed classes shall not contain
7051           // static data members.
7052           Diag(D.getIdentifierLoc(),
7053                diag::err_static_data_member_not_allowed_in_anon_struct)
7054             << Name << AnonStruct->getTagKind();
7055           Invalid = true;
7056         } else if (RD->isUnion()) {
7057           // C++98 [class.union]p1: If a union contains a static data member,
7058           // the program is ill-formed. C++11 drops this restriction.
7059           Diag(D.getIdentifierLoc(),
7060                getLangOpts().CPlusPlus11
7061                  ? diag::warn_cxx98_compat_static_data_member_in_union
7062                  : diag::ext_static_data_member_in_union) << Name;
7063         }
7064       }
7065     }
7066 
7067     // Match up the template parameter lists with the scope specifier, then
7068     // determine whether we have a template or a template specialization.
7069     bool InvalidScope = false;
7070     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7071         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7072         D.getCXXScopeSpec(),
7073         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7074             ? D.getName().TemplateId
7075             : nullptr,
7076         TemplateParamLists,
7077         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7078     Invalid |= InvalidScope;
7079 
7080     if (TemplateParams) {
7081       if (!TemplateParams->size() &&
7082           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7083         // There is an extraneous 'template<>' for this variable. Complain
7084         // about it, but allow the declaration of the variable.
7085         Diag(TemplateParams->getTemplateLoc(),
7086              diag::err_template_variable_noparams)
7087           << II
7088           << SourceRange(TemplateParams->getTemplateLoc(),
7089                          TemplateParams->getRAngleLoc());
7090         TemplateParams = nullptr;
7091       } else {
7092         // Check that we can declare a template here.
7093         if (CheckTemplateDeclScope(S, TemplateParams))
7094           return nullptr;
7095 
7096         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7097           // This is an explicit specialization or a partial specialization.
7098           IsVariableTemplateSpecialization = true;
7099           IsPartialSpecialization = TemplateParams->size() > 0;
7100         } else { // if (TemplateParams->size() > 0)
7101           // This is a template declaration.
7102           IsVariableTemplate = true;
7103 
7104           // Only C++1y supports variable templates (N3651).
7105           Diag(D.getIdentifierLoc(),
7106                getLangOpts().CPlusPlus14
7107                    ? diag::warn_cxx11_compat_variable_template
7108                    : diag::ext_variable_template);
7109         }
7110       }
7111     } else {
7112       // Check that we can declare a member specialization here.
7113       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7114           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7115         return nullptr;
7116       assert((Invalid ||
7117               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7118              "should have a 'template<>' for this decl");
7119     }
7120 
7121     if (IsVariableTemplateSpecialization) {
7122       SourceLocation TemplateKWLoc =
7123           TemplateParamLists.size() > 0
7124               ? TemplateParamLists[0]->getTemplateLoc()
7125               : SourceLocation();
7126       DeclResult Res = ActOnVarTemplateSpecialization(
7127           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7128           IsPartialSpecialization);
7129       if (Res.isInvalid())
7130         return nullptr;
7131       NewVD = cast<VarDecl>(Res.get());
7132       AddToScope = false;
7133     } else if (D.isDecompositionDeclarator()) {
7134       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7135                                         D.getIdentifierLoc(), R, TInfo, SC,
7136                                         Bindings);
7137     } else
7138       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7139                               D.getIdentifierLoc(), II, R, TInfo, SC);
7140 
7141     // If this is supposed to be a variable template, create it as such.
7142     if (IsVariableTemplate) {
7143       NewTemplate =
7144           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7145                                   TemplateParams, NewVD);
7146       NewVD->setDescribedVarTemplate(NewTemplate);
7147     }
7148 
7149     // If this decl has an auto type in need of deduction, make a note of the
7150     // Decl so we can diagnose uses of it in its own initializer.
7151     if (R->getContainedDeducedType())
7152       ParsingInitForAutoVars.insert(NewVD);
7153 
7154     if (D.isInvalidType() || Invalid) {
7155       NewVD->setInvalidDecl();
7156       if (NewTemplate)
7157         NewTemplate->setInvalidDecl();
7158     }
7159 
7160     SetNestedNameSpecifier(*this, NewVD, D);
7161 
7162     // If we have any template parameter lists that don't directly belong to
7163     // the variable (matching the scope specifier), store them.
7164     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7165     if (TemplateParamLists.size() > VDTemplateParamLists)
7166       NewVD->setTemplateParameterListsInfo(
7167           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7168   }
7169 
7170   if (D.getDeclSpec().isInlineSpecified()) {
7171     if (!getLangOpts().CPlusPlus) {
7172       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7173           << 0;
7174     } else if (CurContext->isFunctionOrMethod()) {
7175       // 'inline' is not allowed on block scope variable declaration.
7176       Diag(D.getDeclSpec().getInlineSpecLoc(),
7177            diag::err_inline_declaration_block_scope) << Name
7178         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7179     } else {
7180       Diag(D.getDeclSpec().getInlineSpecLoc(),
7181            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7182                                      : diag::ext_inline_variable);
7183       NewVD->setInlineSpecified();
7184     }
7185   }
7186 
7187   // Set the lexical context. If the declarator has a C++ scope specifier, the
7188   // lexical context will be different from the semantic context.
7189   NewVD->setLexicalDeclContext(CurContext);
7190   if (NewTemplate)
7191     NewTemplate->setLexicalDeclContext(CurContext);
7192 
7193   if (IsLocalExternDecl) {
7194     if (D.isDecompositionDeclarator())
7195       for (auto *B : Bindings)
7196         B->setLocalExternDecl();
7197     else
7198       NewVD->setLocalExternDecl();
7199   }
7200 
7201   bool EmitTLSUnsupportedError = false;
7202   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7203     // C++11 [dcl.stc]p4:
7204     //   When thread_local is applied to a variable of block scope the
7205     //   storage-class-specifier static is implied if it does not appear
7206     //   explicitly.
7207     // Core issue: 'static' is not implied if the variable is declared
7208     //   'extern'.
7209     if (NewVD->hasLocalStorage() &&
7210         (SCSpec != DeclSpec::SCS_unspecified ||
7211          TSCS != DeclSpec::TSCS_thread_local ||
7212          !DC->isFunctionOrMethod()))
7213       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7214            diag::err_thread_non_global)
7215         << DeclSpec::getSpecifierName(TSCS);
7216     else if (!Context.getTargetInfo().isTLSSupported()) {
7217       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7218           getLangOpts().SYCLIsDevice) {
7219         // Postpone error emission until we've collected attributes required to
7220         // figure out whether it's a host or device variable and whether the
7221         // error should be ignored.
7222         EmitTLSUnsupportedError = true;
7223         // We still need to mark the variable as TLS so it shows up in AST with
7224         // proper storage class for other tools to use even if we're not going
7225         // to emit any code for it.
7226         NewVD->setTSCSpec(TSCS);
7227       } else
7228         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7229              diag::err_thread_unsupported);
7230     } else
7231       NewVD->setTSCSpec(TSCS);
7232   }
7233 
7234   switch (D.getDeclSpec().getConstexprSpecifier()) {
7235   case ConstexprSpecKind::Unspecified:
7236     break;
7237 
7238   case ConstexprSpecKind::Consteval:
7239     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7240          diag::err_constexpr_wrong_decl_kind)
7241         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7242     LLVM_FALLTHROUGH;
7243 
7244   case ConstexprSpecKind::Constexpr:
7245     NewVD->setConstexpr(true);
7246     // C++1z [dcl.spec.constexpr]p1:
7247     //   A static data member declared with the constexpr specifier is
7248     //   implicitly an inline variable.
7249     if (NewVD->isStaticDataMember() &&
7250         (getLangOpts().CPlusPlus17 ||
7251          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7252       NewVD->setImplicitlyInline();
7253     break;
7254 
7255   case ConstexprSpecKind::Constinit:
7256     if (!NewVD->hasGlobalStorage())
7257       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7258            diag::err_constinit_local_variable);
7259     else
7260       NewVD->addAttr(ConstInitAttr::Create(
7261           Context, D.getDeclSpec().getConstexprSpecLoc(),
7262           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7263     break;
7264   }
7265 
7266   // C99 6.7.4p3
7267   //   An inline definition of a function with external linkage shall
7268   //   not contain a definition of a modifiable object with static or
7269   //   thread storage duration...
7270   // We only apply this when the function is required to be defined
7271   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7272   // that a local variable with thread storage duration still has to
7273   // be marked 'static'.  Also note that it's possible to get these
7274   // semantics in C++ using __attribute__((gnu_inline)).
7275   if (SC == SC_Static && S->getFnParent() != nullptr &&
7276       !NewVD->getType().isConstQualified()) {
7277     FunctionDecl *CurFD = getCurFunctionDecl();
7278     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7279       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7280            diag::warn_static_local_in_extern_inline);
7281       MaybeSuggestAddingStaticToDecl(CurFD);
7282     }
7283   }
7284 
7285   if (D.getDeclSpec().isModulePrivateSpecified()) {
7286     if (IsVariableTemplateSpecialization)
7287       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7288           << (IsPartialSpecialization ? 1 : 0)
7289           << FixItHint::CreateRemoval(
7290                  D.getDeclSpec().getModulePrivateSpecLoc());
7291     else if (IsMemberSpecialization)
7292       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7293         << 2
7294         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7295     else if (NewVD->hasLocalStorage())
7296       Diag(NewVD->getLocation(), diag::err_module_private_local)
7297           << 0 << NewVD
7298           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7299           << FixItHint::CreateRemoval(
7300                  D.getDeclSpec().getModulePrivateSpecLoc());
7301     else {
7302       NewVD->setModulePrivate();
7303       if (NewTemplate)
7304         NewTemplate->setModulePrivate();
7305       for (auto *B : Bindings)
7306         B->setModulePrivate();
7307     }
7308   }
7309 
7310   if (getLangOpts().OpenCL) {
7311     deduceOpenCLAddressSpace(NewVD);
7312 
7313     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7314     if (TSC != TSCS_unspecified) {
7315       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
7316       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7317            diag::err_opencl_unknown_type_specifier)
7318           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
7319           << DeclSpec::getSpecifierName(TSC) << 1;
7320       NewVD->setInvalidDecl();
7321     }
7322   }
7323 
7324   // Handle attributes prior to checking for duplicates in MergeVarDecl
7325   ProcessDeclAttributes(S, NewVD, D);
7326 
7327   // FIXME: This is probably the wrong location to be doing this and we should
7328   // probably be doing this for more attributes (especially for function
7329   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7330   // the code to copy attributes would be generated by TableGen.
7331   if (R->isFunctionPointerType())
7332     if (const auto *TT = R->getAs<TypedefType>())
7333       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7334 
7335   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7336       getLangOpts().SYCLIsDevice) {
7337     if (EmitTLSUnsupportedError &&
7338         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7339          (getLangOpts().OpenMPIsDevice &&
7340           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7341       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7342            diag::err_thread_unsupported);
7343 
7344     if (EmitTLSUnsupportedError &&
7345         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7346       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7347     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7348     // storage [duration]."
7349     if (SC == SC_None && S->getFnParent() != nullptr &&
7350         (NewVD->hasAttr<CUDASharedAttr>() ||
7351          NewVD->hasAttr<CUDAConstantAttr>())) {
7352       NewVD->setStorageClass(SC_Static);
7353     }
7354   }
7355 
7356   // Ensure that dllimport globals without explicit storage class are treated as
7357   // extern. The storage class is set above using parsed attributes. Now we can
7358   // check the VarDecl itself.
7359   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7360          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7361          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7362 
7363   // In auto-retain/release, infer strong retension for variables of
7364   // retainable type.
7365   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7366     NewVD->setInvalidDecl();
7367 
7368   // Handle GNU asm-label extension (encoded as an attribute).
7369   if (Expr *E = (Expr*)D.getAsmLabel()) {
7370     // The parser guarantees this is a string.
7371     StringLiteral *SE = cast<StringLiteral>(E);
7372     StringRef Label = SE->getString();
7373     if (S->getFnParent() != nullptr) {
7374       switch (SC) {
7375       case SC_None:
7376       case SC_Auto:
7377         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7378         break;
7379       case SC_Register:
7380         // Local Named register
7381         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7382             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7383           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7384         break;
7385       case SC_Static:
7386       case SC_Extern:
7387       case SC_PrivateExtern:
7388         break;
7389       }
7390     } else if (SC == SC_Register) {
7391       // Global Named register
7392       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7393         const auto &TI = Context.getTargetInfo();
7394         bool HasSizeMismatch;
7395 
7396         if (!TI.isValidGCCRegisterName(Label))
7397           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7398         else if (!TI.validateGlobalRegisterVariable(Label,
7399                                                     Context.getTypeSize(R),
7400                                                     HasSizeMismatch))
7401           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7402         else if (HasSizeMismatch)
7403           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7404       }
7405 
7406       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7407         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7408         NewVD->setInvalidDecl(true);
7409       }
7410     }
7411 
7412     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7413                                         /*IsLiteralLabel=*/true,
7414                                         SE->getStrTokenLoc(0)));
7415   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7416     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7417       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7418     if (I != ExtnameUndeclaredIdentifiers.end()) {
7419       if (isDeclExternC(NewVD)) {
7420         NewVD->addAttr(I->second);
7421         ExtnameUndeclaredIdentifiers.erase(I);
7422       } else
7423         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7424             << /*Variable*/1 << NewVD;
7425     }
7426   }
7427 
7428   // Find the shadowed declaration before filtering for scope.
7429   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7430                                 ? getShadowedDeclaration(NewVD, Previous)
7431                                 : nullptr;
7432 
7433   // Don't consider existing declarations that are in a different
7434   // scope and are out-of-semantic-context declarations (if the new
7435   // declaration has linkage).
7436   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7437                        D.getCXXScopeSpec().isNotEmpty() ||
7438                        IsMemberSpecialization ||
7439                        IsVariableTemplateSpecialization);
7440 
7441   // Check whether the previous declaration is in the same block scope. This
7442   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7443   if (getLangOpts().CPlusPlus &&
7444       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7445     NewVD->setPreviousDeclInSameBlockScope(
7446         Previous.isSingleResult() && !Previous.isShadowed() &&
7447         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7448 
7449   if (!getLangOpts().CPlusPlus) {
7450     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7451   } else {
7452     // If this is an explicit specialization of a static data member, check it.
7453     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7454         CheckMemberSpecialization(NewVD, Previous))
7455       NewVD->setInvalidDecl();
7456 
7457     // Merge the decl with the existing one if appropriate.
7458     if (!Previous.empty()) {
7459       if (Previous.isSingleResult() &&
7460           isa<FieldDecl>(Previous.getFoundDecl()) &&
7461           D.getCXXScopeSpec().isSet()) {
7462         // The user tried to define a non-static data member
7463         // out-of-line (C++ [dcl.meaning]p1).
7464         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7465           << D.getCXXScopeSpec().getRange();
7466         Previous.clear();
7467         NewVD->setInvalidDecl();
7468       }
7469     } else if (D.getCXXScopeSpec().isSet()) {
7470       // No previous declaration in the qualifying scope.
7471       Diag(D.getIdentifierLoc(), diag::err_no_member)
7472         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7473         << D.getCXXScopeSpec().getRange();
7474       NewVD->setInvalidDecl();
7475     }
7476 
7477     if (!IsVariableTemplateSpecialization)
7478       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7479 
7480     if (NewTemplate) {
7481       VarTemplateDecl *PrevVarTemplate =
7482           NewVD->getPreviousDecl()
7483               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7484               : nullptr;
7485 
7486       // Check the template parameter list of this declaration, possibly
7487       // merging in the template parameter list from the previous variable
7488       // template declaration.
7489       if (CheckTemplateParameterList(
7490               TemplateParams,
7491               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7492                               : nullptr,
7493               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7494                DC->isDependentContext())
7495                   ? TPC_ClassTemplateMember
7496                   : TPC_VarTemplate))
7497         NewVD->setInvalidDecl();
7498 
7499       // If we are providing an explicit specialization of a static variable
7500       // template, make a note of that.
7501       if (PrevVarTemplate &&
7502           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7503         PrevVarTemplate->setMemberSpecialization();
7504     }
7505   }
7506 
7507   // Diagnose shadowed variables iff this isn't a redeclaration.
7508   if (ShadowedDecl && !D.isRedeclaration())
7509     CheckShadow(NewVD, ShadowedDecl, Previous);
7510 
7511   ProcessPragmaWeak(S, NewVD);
7512 
7513   // If this is the first declaration of an extern C variable, update
7514   // the map of such variables.
7515   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7516       isIncompleteDeclExternC(*this, NewVD))
7517     RegisterLocallyScopedExternCDecl(NewVD, S);
7518 
7519   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7520     MangleNumberingContext *MCtx;
7521     Decl *ManglingContextDecl;
7522     std::tie(MCtx, ManglingContextDecl) =
7523         getCurrentMangleNumberContext(NewVD->getDeclContext());
7524     if (MCtx) {
7525       Context.setManglingNumber(
7526           NewVD, MCtx->getManglingNumber(
7527                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7528       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7529     }
7530   }
7531 
7532   // Special handling of variable named 'main'.
7533   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7534       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7535       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7536 
7537     // C++ [basic.start.main]p3
7538     // A program that declares a variable main at global scope is ill-formed.
7539     if (getLangOpts().CPlusPlus)
7540       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7541 
7542     // In C, and external-linkage variable named main results in undefined
7543     // behavior.
7544     else if (NewVD->hasExternalFormalLinkage())
7545       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7546   }
7547 
7548   if (D.isRedeclaration() && !Previous.empty()) {
7549     NamedDecl *Prev = Previous.getRepresentativeDecl();
7550     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7551                                    D.isFunctionDefinition());
7552   }
7553 
7554   if (NewTemplate) {
7555     if (NewVD->isInvalidDecl())
7556       NewTemplate->setInvalidDecl();
7557     ActOnDocumentableDecl(NewTemplate);
7558     return NewTemplate;
7559   }
7560 
7561   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7562     CompleteMemberSpecialization(NewVD, Previous);
7563 
7564   return NewVD;
7565 }
7566 
7567 /// Enum describing the %select options in diag::warn_decl_shadow.
7568 enum ShadowedDeclKind {
7569   SDK_Local,
7570   SDK_Global,
7571   SDK_StaticMember,
7572   SDK_Field,
7573   SDK_Typedef,
7574   SDK_Using,
7575   SDK_StructuredBinding
7576 };
7577 
7578 /// Determine what kind of declaration we're shadowing.
7579 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7580                                                 const DeclContext *OldDC) {
7581   if (isa<TypeAliasDecl>(ShadowedDecl))
7582     return SDK_Using;
7583   else if (isa<TypedefDecl>(ShadowedDecl))
7584     return SDK_Typedef;
7585   else if (isa<BindingDecl>(ShadowedDecl))
7586     return SDK_StructuredBinding;
7587   else if (isa<RecordDecl>(OldDC))
7588     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7589 
7590   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7591 }
7592 
7593 /// Return the location of the capture if the given lambda captures the given
7594 /// variable \p VD, or an invalid source location otherwise.
7595 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7596                                          const VarDecl *VD) {
7597   for (const Capture &Capture : LSI->Captures) {
7598     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7599       return Capture.getLocation();
7600   }
7601   return SourceLocation();
7602 }
7603 
7604 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7605                                      const LookupResult &R) {
7606   // Only diagnose if we're shadowing an unambiguous field or variable.
7607   if (R.getResultKind() != LookupResult::Found)
7608     return false;
7609 
7610   // Return false if warning is ignored.
7611   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7612 }
7613 
7614 /// Return the declaration shadowed by the given variable \p D, or null
7615 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7616 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7617                                         const LookupResult &R) {
7618   if (!shouldWarnIfShadowedDecl(Diags, R))
7619     return nullptr;
7620 
7621   // Don't diagnose declarations at file scope.
7622   if (D->hasGlobalStorage())
7623     return nullptr;
7624 
7625   NamedDecl *ShadowedDecl = R.getFoundDecl();
7626   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7627                                                             : nullptr;
7628 }
7629 
7630 /// Return the declaration shadowed by the given typedef \p D, or null
7631 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7632 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7633                                         const LookupResult &R) {
7634   // Don't warn if typedef declaration is part of a class
7635   if (D->getDeclContext()->isRecord())
7636     return nullptr;
7637 
7638   if (!shouldWarnIfShadowedDecl(Diags, R))
7639     return nullptr;
7640 
7641   NamedDecl *ShadowedDecl = R.getFoundDecl();
7642   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7643 }
7644 
7645 /// Return the declaration shadowed by the given variable \p D, or null
7646 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7647 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7648                                         const LookupResult &R) {
7649   if (!shouldWarnIfShadowedDecl(Diags, R))
7650     return nullptr;
7651 
7652   NamedDecl *ShadowedDecl = R.getFoundDecl();
7653   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7654                                                             : nullptr;
7655 }
7656 
7657 /// Diagnose variable or built-in function shadowing.  Implements
7658 /// -Wshadow.
7659 ///
7660 /// This method is called whenever a VarDecl is added to a "useful"
7661 /// scope.
7662 ///
7663 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7664 /// \param R the lookup of the name
7665 ///
7666 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7667                        const LookupResult &R) {
7668   DeclContext *NewDC = D->getDeclContext();
7669 
7670   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7671     // Fields are not shadowed by variables in C++ static methods.
7672     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7673       if (MD->isStatic())
7674         return;
7675 
7676     // Fields shadowed by constructor parameters are a special case. Usually
7677     // the constructor initializes the field with the parameter.
7678     if (isa<CXXConstructorDecl>(NewDC))
7679       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7680         // Remember that this was shadowed so we can either warn about its
7681         // modification or its existence depending on warning settings.
7682         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7683         return;
7684       }
7685   }
7686 
7687   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7688     if (shadowedVar->isExternC()) {
7689       // For shadowing external vars, make sure that we point to the global
7690       // declaration, not a locally scoped extern declaration.
7691       for (auto I : shadowedVar->redecls())
7692         if (I->isFileVarDecl()) {
7693           ShadowedDecl = I;
7694           break;
7695         }
7696     }
7697 
7698   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7699 
7700   unsigned WarningDiag = diag::warn_decl_shadow;
7701   SourceLocation CaptureLoc;
7702   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7703       isa<CXXMethodDecl>(NewDC)) {
7704     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7705       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7706         if (RD->getLambdaCaptureDefault() == LCD_None) {
7707           // Try to avoid warnings for lambdas with an explicit capture list.
7708           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7709           // Warn only when the lambda captures the shadowed decl explicitly.
7710           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7711           if (CaptureLoc.isInvalid())
7712             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7713         } else {
7714           // Remember that this was shadowed so we can avoid the warning if the
7715           // shadowed decl isn't captured and the warning settings allow it.
7716           cast<LambdaScopeInfo>(getCurFunction())
7717               ->ShadowingDecls.push_back(
7718                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7719           return;
7720         }
7721       }
7722 
7723       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7724         // A variable can't shadow a local variable in an enclosing scope, if
7725         // they are separated by a non-capturing declaration context.
7726         for (DeclContext *ParentDC = NewDC;
7727              ParentDC && !ParentDC->Equals(OldDC);
7728              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7729           // Only block literals, captured statements, and lambda expressions
7730           // can capture; other scopes don't.
7731           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7732               !isLambdaCallOperator(ParentDC)) {
7733             return;
7734           }
7735         }
7736       }
7737     }
7738   }
7739 
7740   // Only warn about certain kinds of shadowing for class members.
7741   if (NewDC && NewDC->isRecord()) {
7742     // In particular, don't warn about shadowing non-class members.
7743     if (!OldDC->isRecord())
7744       return;
7745 
7746     // TODO: should we warn about static data members shadowing
7747     // static data members from base classes?
7748 
7749     // TODO: don't diagnose for inaccessible shadowed members.
7750     // This is hard to do perfectly because we might friend the
7751     // shadowing context, but that's just a false negative.
7752   }
7753 
7754 
7755   DeclarationName Name = R.getLookupName();
7756 
7757   // Emit warning and note.
7758   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7759     return;
7760   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7761   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7762   if (!CaptureLoc.isInvalid())
7763     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7764         << Name << /*explicitly*/ 1;
7765   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7766 }
7767 
7768 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7769 /// when these variables are captured by the lambda.
7770 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7771   for (const auto &Shadow : LSI->ShadowingDecls) {
7772     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7773     // Try to avoid the warning when the shadowed decl isn't captured.
7774     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7775     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7776     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7777                                        ? diag::warn_decl_shadow_uncaptured_local
7778                                        : diag::warn_decl_shadow)
7779         << Shadow.VD->getDeclName()
7780         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7781     if (!CaptureLoc.isInvalid())
7782       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7783           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7784     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7785   }
7786 }
7787 
7788 /// Check -Wshadow without the advantage of a previous lookup.
7789 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7790   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7791     return;
7792 
7793   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7794                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7795   LookupName(R, S);
7796   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7797     CheckShadow(D, ShadowedDecl, R);
7798 }
7799 
7800 /// Check if 'E', which is an expression that is about to be modified, refers
7801 /// to a constructor parameter that shadows a field.
7802 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7803   // Quickly ignore expressions that can't be shadowing ctor parameters.
7804   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7805     return;
7806   E = E->IgnoreParenImpCasts();
7807   auto *DRE = dyn_cast<DeclRefExpr>(E);
7808   if (!DRE)
7809     return;
7810   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7811   auto I = ShadowingDecls.find(D);
7812   if (I == ShadowingDecls.end())
7813     return;
7814   const NamedDecl *ShadowedDecl = I->second;
7815   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7816   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7817   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7818   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7819 
7820   // Avoid issuing multiple warnings about the same decl.
7821   ShadowingDecls.erase(I);
7822 }
7823 
7824 /// Check for conflict between this global or extern "C" declaration and
7825 /// previous global or extern "C" declarations. This is only used in C++.
7826 template<typename T>
7827 static bool checkGlobalOrExternCConflict(
7828     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7829   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7830   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7831 
7832   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7833     // The common case: this global doesn't conflict with any extern "C"
7834     // declaration.
7835     return false;
7836   }
7837 
7838   if (Prev) {
7839     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7840       // Both the old and new declarations have C language linkage. This is a
7841       // redeclaration.
7842       Previous.clear();
7843       Previous.addDecl(Prev);
7844       return true;
7845     }
7846 
7847     // This is a global, non-extern "C" declaration, and there is a previous
7848     // non-global extern "C" declaration. Diagnose if this is a variable
7849     // declaration.
7850     if (!isa<VarDecl>(ND))
7851       return false;
7852   } else {
7853     // The declaration is extern "C". Check for any declaration in the
7854     // translation unit which might conflict.
7855     if (IsGlobal) {
7856       // We have already performed the lookup into the translation unit.
7857       IsGlobal = false;
7858       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7859            I != E; ++I) {
7860         if (isa<VarDecl>(*I)) {
7861           Prev = *I;
7862           break;
7863         }
7864       }
7865     } else {
7866       DeclContext::lookup_result R =
7867           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7868       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7869            I != E; ++I) {
7870         if (isa<VarDecl>(*I)) {
7871           Prev = *I;
7872           break;
7873         }
7874         // FIXME: If we have any other entity with this name in global scope,
7875         // the declaration is ill-formed, but that is a defect: it breaks the
7876         // 'stat' hack, for instance. Only variables can have mangled name
7877         // clashes with extern "C" declarations, so only they deserve a
7878         // diagnostic.
7879       }
7880     }
7881 
7882     if (!Prev)
7883       return false;
7884   }
7885 
7886   // Use the first declaration's location to ensure we point at something which
7887   // is lexically inside an extern "C" linkage-spec.
7888   assert(Prev && "should have found a previous declaration to diagnose");
7889   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7890     Prev = FD->getFirstDecl();
7891   else
7892     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7893 
7894   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7895     << IsGlobal << ND;
7896   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7897     << IsGlobal;
7898   return false;
7899 }
7900 
7901 /// Apply special rules for handling extern "C" declarations. Returns \c true
7902 /// if we have found that this is a redeclaration of some prior entity.
7903 ///
7904 /// Per C++ [dcl.link]p6:
7905 ///   Two declarations [for a function or variable] with C language linkage
7906 ///   with the same name that appear in different scopes refer to the same
7907 ///   [entity]. An entity with C language linkage shall not be declared with
7908 ///   the same name as an entity in global scope.
7909 template<typename T>
7910 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7911                                                   LookupResult &Previous) {
7912   if (!S.getLangOpts().CPlusPlus) {
7913     // In C, when declaring a global variable, look for a corresponding 'extern'
7914     // variable declared in function scope. We don't need this in C++, because
7915     // we find local extern decls in the surrounding file-scope DeclContext.
7916     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7917       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7918         Previous.clear();
7919         Previous.addDecl(Prev);
7920         return true;
7921       }
7922     }
7923     return false;
7924   }
7925 
7926   // A declaration in the translation unit can conflict with an extern "C"
7927   // declaration.
7928   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7929     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7930 
7931   // An extern "C" declaration can conflict with a declaration in the
7932   // translation unit or can be a redeclaration of an extern "C" declaration
7933   // in another scope.
7934   if (isIncompleteDeclExternC(S,ND))
7935     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7936 
7937   // Neither global nor extern "C": nothing to do.
7938   return false;
7939 }
7940 
7941 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7942   // If the decl is already known invalid, don't check it.
7943   if (NewVD->isInvalidDecl())
7944     return;
7945 
7946   QualType T = NewVD->getType();
7947 
7948   // Defer checking an 'auto' type until its initializer is attached.
7949   if (T->isUndeducedType())
7950     return;
7951 
7952   if (NewVD->hasAttrs())
7953     CheckAlignasUnderalignment(NewVD);
7954 
7955   if (T->isObjCObjectType()) {
7956     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7957       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7958     T = Context.getObjCObjectPointerType(T);
7959     NewVD->setType(T);
7960   }
7961 
7962   // Emit an error if an address space was applied to decl with local storage.
7963   // This includes arrays of objects with address space qualifiers, but not
7964   // automatic variables that point to other address spaces.
7965   // ISO/IEC TR 18037 S5.1.2
7966   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7967       T.getAddressSpace() != LangAS::Default) {
7968     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7969     NewVD->setInvalidDecl();
7970     return;
7971   }
7972 
7973   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7974   // scope.
7975   if (getLangOpts().OpenCLVersion == 120 &&
7976       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7977                                             getLangOpts()) &&
7978       NewVD->isStaticLocal()) {
7979     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7980     NewVD->setInvalidDecl();
7981     return;
7982   }
7983 
7984   if (getLangOpts().OpenCL) {
7985     if (!diagnoseOpenCLTypes(*this, NewVD))
7986       return;
7987 
7988     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7989     if (NewVD->hasAttr<BlocksAttr>()) {
7990       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7991       return;
7992     }
7993 
7994     if (T->isBlockPointerType()) {
7995       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7996       // can't use 'extern' storage class.
7997       if (!T.isConstQualified()) {
7998         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7999             << 0 /*const*/;
8000         NewVD->setInvalidDecl();
8001         return;
8002       }
8003       if (NewVD->hasExternalStorage()) {
8004         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8005         NewVD->setInvalidDecl();
8006         return;
8007       }
8008     }
8009 
8010     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
8011     // __constant address space.
8012     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
8013     // variables inside a function can also be declared in the global
8014     // address space.
8015     // C++ for OpenCL inherits rule from OpenCL C v2.0.
8016     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8017     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8018         NewVD->hasExternalStorage()) {
8019       if (!T->isSamplerT() &&
8020           !T->isDependentType() &&
8021           !(T.getAddressSpace() == LangAS::opencl_constant ||
8022             (T.getAddressSpace() == LangAS::opencl_global &&
8023              (getLangOpts().OpenCLVersion == 200 ||
8024               getLangOpts().OpenCLCPlusPlus)))) {
8025         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8026         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
8027           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8028               << Scope << "global or constant";
8029         else
8030           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8031               << Scope << "constant";
8032         NewVD->setInvalidDecl();
8033         return;
8034       }
8035     } else {
8036       if (T.getAddressSpace() == LangAS::opencl_global) {
8037         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8038             << 1 /*is any function*/ << "global";
8039         NewVD->setInvalidDecl();
8040         return;
8041       }
8042       if (T.getAddressSpace() == LangAS::opencl_constant ||
8043           T.getAddressSpace() == LangAS::opencl_local) {
8044         FunctionDecl *FD = getCurFunctionDecl();
8045         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8046         // in functions.
8047         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8048           if (T.getAddressSpace() == LangAS::opencl_constant)
8049             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8050                 << 0 /*non-kernel only*/ << "constant";
8051           else
8052             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8053                 << 0 /*non-kernel only*/ << "local";
8054           NewVD->setInvalidDecl();
8055           return;
8056         }
8057         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8058         // in the outermost scope of a kernel function.
8059         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8060           if (!getCurScope()->isFunctionScope()) {
8061             if (T.getAddressSpace() == LangAS::opencl_constant)
8062               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8063                   << "constant";
8064             else
8065               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8066                   << "local";
8067             NewVD->setInvalidDecl();
8068             return;
8069           }
8070         }
8071       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8072                  // If we are parsing a template we didn't deduce an addr
8073                  // space yet.
8074                  T.getAddressSpace() != LangAS::Default) {
8075         // Do not allow other address spaces on automatic variable.
8076         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8077         NewVD->setInvalidDecl();
8078         return;
8079       }
8080     }
8081   }
8082 
8083   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8084       && !NewVD->hasAttr<BlocksAttr>()) {
8085     if (getLangOpts().getGC() != LangOptions::NonGC)
8086       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8087     else {
8088       assert(!getLangOpts().ObjCAutoRefCount);
8089       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8090     }
8091   }
8092 
8093   bool isVM = T->isVariablyModifiedType();
8094   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8095       NewVD->hasAttr<BlocksAttr>())
8096     setFunctionHasBranchProtectedScope();
8097 
8098   if ((isVM && NewVD->hasLinkage()) ||
8099       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8100     bool SizeIsNegative;
8101     llvm::APSInt Oversized;
8102     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8103         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8104     QualType FixedT;
8105     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8106       FixedT = FixedTInfo->getType();
8107     else if (FixedTInfo) {
8108       // Type and type-as-written are canonically different. We need to fix up
8109       // both types separately.
8110       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8111                                                    Oversized);
8112     }
8113     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8114       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8115       // FIXME: This won't give the correct result for
8116       // int a[10][n];
8117       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8118 
8119       if (NewVD->isFileVarDecl())
8120         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8121         << SizeRange;
8122       else if (NewVD->isStaticLocal())
8123         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8124         << SizeRange;
8125       else
8126         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8127         << SizeRange;
8128       NewVD->setInvalidDecl();
8129       return;
8130     }
8131 
8132     if (!FixedTInfo) {
8133       if (NewVD->isFileVarDecl())
8134         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8135       else
8136         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8137       NewVD->setInvalidDecl();
8138       return;
8139     }
8140 
8141     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8142     NewVD->setType(FixedT);
8143     NewVD->setTypeSourceInfo(FixedTInfo);
8144   }
8145 
8146   if (T->isVoidType()) {
8147     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8148     //                    of objects and functions.
8149     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8150       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8151         << T;
8152       NewVD->setInvalidDecl();
8153       return;
8154     }
8155   }
8156 
8157   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8158     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8159     NewVD->setInvalidDecl();
8160     return;
8161   }
8162 
8163   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8164     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8165     NewVD->setInvalidDecl();
8166     return;
8167   }
8168 
8169   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8170     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8171     NewVD->setInvalidDecl();
8172     return;
8173   }
8174 
8175   if (NewVD->isConstexpr() && !T->isDependentType() &&
8176       RequireLiteralType(NewVD->getLocation(), T,
8177                          diag::err_constexpr_var_non_literal)) {
8178     NewVD->setInvalidDecl();
8179     return;
8180   }
8181 
8182   // PPC MMA non-pointer types are not allowed as non-local variable types.
8183   if (Context.getTargetInfo().getTriple().isPPC64() &&
8184       !NewVD->isLocalVarDecl() &&
8185       CheckPPCMMAType(T, NewVD->getLocation())) {
8186     NewVD->setInvalidDecl();
8187     return;
8188   }
8189 }
8190 
8191 /// Perform semantic checking on a newly-created variable
8192 /// declaration.
8193 ///
8194 /// This routine performs all of the type-checking required for a
8195 /// variable declaration once it has been built. It is used both to
8196 /// check variables after they have been parsed and their declarators
8197 /// have been translated into a declaration, and to check variables
8198 /// that have been instantiated from a template.
8199 ///
8200 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8201 ///
8202 /// Returns true if the variable declaration is a redeclaration.
8203 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8204   CheckVariableDeclarationType(NewVD);
8205 
8206   // If the decl is already known invalid, don't check it.
8207   if (NewVD->isInvalidDecl())
8208     return false;
8209 
8210   // If we did not find anything by this name, look for a non-visible
8211   // extern "C" declaration with the same name.
8212   if (Previous.empty() &&
8213       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8214     Previous.setShadowed();
8215 
8216   if (!Previous.empty()) {
8217     MergeVarDecl(NewVD, Previous);
8218     return true;
8219   }
8220   return false;
8221 }
8222 
8223 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8224 /// and if so, check that it's a valid override and remember it.
8225 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8226   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8227 
8228   // Look for methods in base classes that this method might override.
8229   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8230                      /*DetectVirtual=*/false);
8231   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8232     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8233     DeclarationName Name = MD->getDeclName();
8234 
8235     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8236       // We really want to find the base class destructor here.
8237       QualType T = Context.getTypeDeclType(BaseRecord);
8238       CanQualType CT = Context.getCanonicalType(T);
8239       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8240     }
8241 
8242     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8243       CXXMethodDecl *BaseMD =
8244           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8245       if (!BaseMD || !BaseMD->isVirtual() ||
8246           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8247                      /*ConsiderCudaAttrs=*/true,
8248                      // C++2a [class.virtual]p2 does not consider requires
8249                      // clauses when overriding.
8250                      /*ConsiderRequiresClauses=*/false))
8251         continue;
8252 
8253       if (Overridden.insert(BaseMD).second) {
8254         MD->addOverriddenMethod(BaseMD);
8255         CheckOverridingFunctionReturnType(MD, BaseMD);
8256         CheckOverridingFunctionAttributes(MD, BaseMD);
8257         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8258         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8259       }
8260 
8261       // A method can only override one function from each base class. We
8262       // don't track indirectly overridden methods from bases of bases.
8263       return true;
8264     }
8265 
8266     return false;
8267   };
8268 
8269   DC->lookupInBases(VisitBase, Paths);
8270   return !Overridden.empty();
8271 }
8272 
8273 namespace {
8274   // Struct for holding all of the extra arguments needed by
8275   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8276   struct ActOnFDArgs {
8277     Scope *S;
8278     Declarator &D;
8279     MultiTemplateParamsArg TemplateParamLists;
8280     bool AddToScope;
8281   };
8282 } // end anonymous namespace
8283 
8284 namespace {
8285 
8286 // Callback to only accept typo corrections that have a non-zero edit distance.
8287 // Also only accept corrections that have the same parent decl.
8288 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8289  public:
8290   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8291                             CXXRecordDecl *Parent)
8292       : Context(Context), OriginalFD(TypoFD),
8293         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8294 
8295   bool ValidateCandidate(const TypoCorrection &candidate) override {
8296     if (candidate.getEditDistance() == 0)
8297       return false;
8298 
8299     SmallVector<unsigned, 1> MismatchedParams;
8300     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8301                                           CDeclEnd = candidate.end();
8302          CDecl != CDeclEnd; ++CDecl) {
8303       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8304 
8305       if (FD && !FD->hasBody() &&
8306           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8307         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8308           CXXRecordDecl *Parent = MD->getParent();
8309           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8310             return true;
8311         } else if (!ExpectedParent) {
8312           return true;
8313         }
8314       }
8315     }
8316 
8317     return false;
8318   }
8319 
8320   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8321     return std::make_unique<DifferentNameValidatorCCC>(*this);
8322   }
8323 
8324  private:
8325   ASTContext &Context;
8326   FunctionDecl *OriginalFD;
8327   CXXRecordDecl *ExpectedParent;
8328 };
8329 
8330 } // end anonymous namespace
8331 
8332 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8333   TypoCorrectedFunctionDefinitions.insert(F);
8334 }
8335 
8336 /// Generate diagnostics for an invalid function redeclaration.
8337 ///
8338 /// This routine handles generating the diagnostic messages for an invalid
8339 /// function redeclaration, including finding possible similar declarations
8340 /// or performing typo correction if there are no previous declarations with
8341 /// the same name.
8342 ///
8343 /// Returns a NamedDecl iff typo correction was performed and substituting in
8344 /// the new declaration name does not cause new errors.
8345 static NamedDecl *DiagnoseInvalidRedeclaration(
8346     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8347     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8348   DeclarationName Name = NewFD->getDeclName();
8349   DeclContext *NewDC = NewFD->getDeclContext();
8350   SmallVector<unsigned, 1> MismatchedParams;
8351   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8352   TypoCorrection Correction;
8353   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8354   unsigned DiagMsg =
8355     IsLocalFriend ? diag::err_no_matching_local_friend :
8356     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8357     diag::err_member_decl_does_not_match;
8358   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8359                     IsLocalFriend ? Sema::LookupLocalFriendName
8360                                   : Sema::LookupOrdinaryName,
8361                     Sema::ForVisibleRedeclaration);
8362 
8363   NewFD->setInvalidDecl();
8364   if (IsLocalFriend)
8365     SemaRef.LookupName(Prev, S);
8366   else
8367     SemaRef.LookupQualifiedName(Prev, NewDC);
8368   assert(!Prev.isAmbiguous() &&
8369          "Cannot have an ambiguity in previous-declaration lookup");
8370   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8371   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8372                                 MD ? MD->getParent() : nullptr);
8373   if (!Prev.empty()) {
8374     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8375          Func != FuncEnd; ++Func) {
8376       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8377       if (FD &&
8378           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8379         // Add 1 to the index so that 0 can mean the mismatch didn't
8380         // involve a parameter
8381         unsigned ParamNum =
8382             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8383         NearMatches.push_back(std::make_pair(FD, ParamNum));
8384       }
8385     }
8386   // If the qualified name lookup yielded nothing, try typo correction
8387   } else if ((Correction = SemaRef.CorrectTypo(
8388                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8389                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8390                   IsLocalFriend ? nullptr : NewDC))) {
8391     // Set up everything for the call to ActOnFunctionDeclarator
8392     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8393                               ExtraArgs.D.getIdentifierLoc());
8394     Previous.clear();
8395     Previous.setLookupName(Correction.getCorrection());
8396     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8397                                     CDeclEnd = Correction.end();
8398          CDecl != CDeclEnd; ++CDecl) {
8399       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8400       if (FD && !FD->hasBody() &&
8401           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8402         Previous.addDecl(FD);
8403       }
8404     }
8405     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8406 
8407     NamedDecl *Result;
8408     // Retry building the function declaration with the new previous
8409     // declarations, and with errors suppressed.
8410     {
8411       // Trap errors.
8412       Sema::SFINAETrap Trap(SemaRef);
8413 
8414       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8415       // pieces need to verify the typo-corrected C++ declaration and hopefully
8416       // eliminate the need for the parameter pack ExtraArgs.
8417       Result = SemaRef.ActOnFunctionDeclarator(
8418           ExtraArgs.S, ExtraArgs.D,
8419           Correction.getCorrectionDecl()->getDeclContext(),
8420           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8421           ExtraArgs.AddToScope);
8422 
8423       if (Trap.hasErrorOccurred())
8424         Result = nullptr;
8425     }
8426 
8427     if (Result) {
8428       // Determine which correction we picked.
8429       Decl *Canonical = Result->getCanonicalDecl();
8430       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8431            I != E; ++I)
8432         if ((*I)->getCanonicalDecl() == Canonical)
8433           Correction.setCorrectionDecl(*I);
8434 
8435       // Let Sema know about the correction.
8436       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8437       SemaRef.diagnoseTypo(
8438           Correction,
8439           SemaRef.PDiag(IsLocalFriend
8440                           ? diag::err_no_matching_local_friend_suggest
8441                           : diag::err_member_decl_does_not_match_suggest)
8442             << Name << NewDC << IsDefinition);
8443       return Result;
8444     }
8445 
8446     // Pretend the typo correction never occurred
8447     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8448                               ExtraArgs.D.getIdentifierLoc());
8449     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8450     Previous.clear();
8451     Previous.setLookupName(Name);
8452   }
8453 
8454   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8455       << Name << NewDC << IsDefinition << NewFD->getLocation();
8456 
8457   bool NewFDisConst = false;
8458   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8459     NewFDisConst = NewMD->isConst();
8460 
8461   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8462        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8463        NearMatch != NearMatchEnd; ++NearMatch) {
8464     FunctionDecl *FD = NearMatch->first;
8465     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8466     bool FDisConst = MD && MD->isConst();
8467     bool IsMember = MD || !IsLocalFriend;
8468 
8469     // FIXME: These notes are poorly worded for the local friend case.
8470     if (unsigned Idx = NearMatch->second) {
8471       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8472       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8473       if (Loc.isInvalid()) Loc = FD->getLocation();
8474       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8475                                  : diag::note_local_decl_close_param_match)
8476         << Idx << FDParam->getType()
8477         << NewFD->getParamDecl(Idx - 1)->getType();
8478     } else if (FDisConst != NewFDisConst) {
8479       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8480           << NewFDisConst << FD->getSourceRange().getEnd();
8481     } else
8482       SemaRef.Diag(FD->getLocation(),
8483                    IsMember ? diag::note_member_def_close_match
8484                             : diag::note_local_decl_close_match);
8485   }
8486   return nullptr;
8487 }
8488 
8489 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8490   switch (D.getDeclSpec().getStorageClassSpec()) {
8491   default: llvm_unreachable("Unknown storage class!");
8492   case DeclSpec::SCS_auto:
8493   case DeclSpec::SCS_register:
8494   case DeclSpec::SCS_mutable:
8495     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8496                  diag::err_typecheck_sclass_func);
8497     D.getMutableDeclSpec().ClearStorageClassSpecs();
8498     D.setInvalidType();
8499     break;
8500   case DeclSpec::SCS_unspecified: break;
8501   case DeclSpec::SCS_extern:
8502     if (D.getDeclSpec().isExternInLinkageSpec())
8503       return SC_None;
8504     return SC_Extern;
8505   case DeclSpec::SCS_static: {
8506     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8507       // C99 6.7.1p5:
8508       //   The declaration of an identifier for a function that has
8509       //   block scope shall have no explicit storage-class specifier
8510       //   other than extern
8511       // See also (C++ [dcl.stc]p4).
8512       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8513                    diag::err_static_block_func);
8514       break;
8515     } else
8516       return SC_Static;
8517   }
8518   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8519   }
8520 
8521   // No explicit storage class has already been returned
8522   return SC_None;
8523 }
8524 
8525 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8526                                            DeclContext *DC, QualType &R,
8527                                            TypeSourceInfo *TInfo,
8528                                            StorageClass SC,
8529                                            bool &IsVirtualOkay) {
8530   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8531   DeclarationName Name = NameInfo.getName();
8532 
8533   FunctionDecl *NewFD = nullptr;
8534   bool isInline = D.getDeclSpec().isInlineSpecified();
8535 
8536   if (!SemaRef.getLangOpts().CPlusPlus) {
8537     // Determine whether the function was written with a
8538     // prototype. This true when:
8539     //   - there is a prototype in the declarator, or
8540     //   - the type R of the function is some kind of typedef or other non-
8541     //     attributed reference to a type name (which eventually refers to a
8542     //     function type).
8543     bool HasPrototype =
8544       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8545       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8546 
8547     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8548                                  R, TInfo, SC, isInline, HasPrototype,
8549                                  ConstexprSpecKind::Unspecified,
8550                                  /*TrailingRequiresClause=*/nullptr);
8551     if (D.isInvalidType())
8552       NewFD->setInvalidDecl();
8553 
8554     return NewFD;
8555   }
8556 
8557   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8558 
8559   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8560   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8561     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8562                  diag::err_constexpr_wrong_decl_kind)
8563         << static_cast<int>(ConstexprKind);
8564     ConstexprKind = ConstexprSpecKind::Unspecified;
8565     D.getMutableDeclSpec().ClearConstexprSpec();
8566   }
8567   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8568 
8569   // Check that the return type is not an abstract class type.
8570   // For record types, this is done by the AbstractClassUsageDiagnoser once
8571   // the class has been completely parsed.
8572   if (!DC->isRecord() &&
8573       SemaRef.RequireNonAbstractType(
8574           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8575           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8576     D.setInvalidType();
8577 
8578   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8579     // This is a C++ constructor declaration.
8580     assert(DC->isRecord() &&
8581            "Constructors can only be declared in a member context");
8582 
8583     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8584     return CXXConstructorDecl::Create(
8585         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8586         TInfo, ExplicitSpecifier, isInline,
8587         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8588         TrailingRequiresClause);
8589 
8590   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8591     // This is a C++ destructor declaration.
8592     if (DC->isRecord()) {
8593       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8594       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8595       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8596           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8597           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8598           TrailingRequiresClause);
8599 
8600       // If the destructor needs an implicit exception specification, set it
8601       // now. FIXME: It'd be nice to be able to create the right type to start
8602       // with, but the type needs to reference the destructor declaration.
8603       if (SemaRef.getLangOpts().CPlusPlus11)
8604         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8605 
8606       IsVirtualOkay = true;
8607       return NewDD;
8608 
8609     } else {
8610       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8611       D.setInvalidType();
8612 
8613       // Create a FunctionDecl to satisfy the function definition parsing
8614       // code path.
8615       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8616                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8617                                   isInline,
8618                                   /*hasPrototype=*/true, ConstexprKind,
8619                                   TrailingRequiresClause);
8620     }
8621 
8622   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8623     if (!DC->isRecord()) {
8624       SemaRef.Diag(D.getIdentifierLoc(),
8625            diag::err_conv_function_not_member);
8626       return nullptr;
8627     }
8628 
8629     SemaRef.CheckConversionDeclarator(D, R, SC);
8630     if (D.isInvalidType())
8631       return nullptr;
8632 
8633     IsVirtualOkay = true;
8634     return CXXConversionDecl::Create(
8635         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8636         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8637         TrailingRequiresClause);
8638 
8639   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8640     if (TrailingRequiresClause)
8641       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8642                    diag::err_trailing_requires_clause_on_deduction_guide)
8643           << TrailingRequiresClause->getSourceRange();
8644     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8645 
8646     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8647                                          ExplicitSpecifier, NameInfo, R, TInfo,
8648                                          D.getEndLoc());
8649   } else if (DC->isRecord()) {
8650     // If the name of the function is the same as the name of the record,
8651     // then this must be an invalid constructor that has a return type.
8652     // (The parser checks for a return type and makes the declarator a
8653     // constructor if it has no return type).
8654     if (Name.getAsIdentifierInfo() &&
8655         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8656       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8657         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8658         << SourceRange(D.getIdentifierLoc());
8659       return nullptr;
8660     }
8661 
8662     // This is a C++ method declaration.
8663     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8664         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8665         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8666         TrailingRequiresClause);
8667     IsVirtualOkay = !Ret->isStatic();
8668     return Ret;
8669   } else {
8670     bool isFriend =
8671         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8672     if (!isFriend && SemaRef.CurContext->isRecord())
8673       return nullptr;
8674 
8675     // Determine whether the function was written with a
8676     // prototype. This true when:
8677     //   - we're in C++ (where every function has a prototype),
8678     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8679                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8680                                 ConstexprKind, TrailingRequiresClause);
8681   }
8682 }
8683 
8684 enum OpenCLParamType {
8685   ValidKernelParam,
8686   PtrPtrKernelParam,
8687   PtrKernelParam,
8688   InvalidAddrSpacePtrKernelParam,
8689   InvalidKernelParam,
8690   RecordKernelParam
8691 };
8692 
8693 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8694   // Size dependent types are just typedefs to normal integer types
8695   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8696   // integers other than by their names.
8697   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8698 
8699   // Remove typedefs one by one until we reach a typedef
8700   // for a size dependent type.
8701   QualType DesugaredTy = Ty;
8702   do {
8703     ArrayRef<StringRef> Names(SizeTypeNames);
8704     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8705     if (Names.end() != Match)
8706       return true;
8707 
8708     Ty = DesugaredTy;
8709     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8710   } while (DesugaredTy != Ty);
8711 
8712   return false;
8713 }
8714 
8715 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8716   if (PT->isDependentType())
8717     return InvalidKernelParam;
8718 
8719   if (PT->isPointerType() || PT->isReferenceType()) {
8720     QualType PointeeType = PT->getPointeeType();
8721     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8722         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8723         PointeeType.getAddressSpace() == LangAS::Default)
8724       return InvalidAddrSpacePtrKernelParam;
8725 
8726     if (PointeeType->isPointerType()) {
8727       // This is a pointer to pointer parameter.
8728       // Recursively check inner type.
8729       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8730       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8731           ParamKind == InvalidKernelParam)
8732         return ParamKind;
8733 
8734       return PtrPtrKernelParam;
8735     }
8736 
8737     // C++ for OpenCL v1.0 s2.4:
8738     // Moreover the types used in parameters of the kernel functions must be:
8739     // Standard layout types for pointer parameters. The same applies to
8740     // reference if an implementation supports them in kernel parameters.
8741     if (S.getLangOpts().OpenCLCPlusPlus &&
8742         !S.getOpenCLOptions().isAvailableOption(
8743             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8744         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8745         !PointeeType->isStandardLayoutType())
8746       return InvalidKernelParam;
8747 
8748     return PtrKernelParam;
8749   }
8750 
8751   // OpenCL v1.2 s6.9.k:
8752   // Arguments to kernel functions in a program cannot be declared with the
8753   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8754   // uintptr_t or a struct and/or union that contain fields declared to be one
8755   // of these built-in scalar types.
8756   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8757     return InvalidKernelParam;
8758 
8759   if (PT->isImageType())
8760     return PtrKernelParam;
8761 
8762   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8763     return InvalidKernelParam;
8764 
8765   // OpenCL extension spec v1.2 s9.5:
8766   // This extension adds support for half scalar and vector types as built-in
8767   // types that can be used for arithmetic operations, conversions etc.
8768   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8769       PT->isHalfType())
8770     return InvalidKernelParam;
8771 
8772   // Look into an array argument to check if it has a forbidden type.
8773   if (PT->isArrayType()) {
8774     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8775     // Call ourself to check an underlying type of an array. Since the
8776     // getPointeeOrArrayElementType returns an innermost type which is not an
8777     // array, this recursive call only happens once.
8778     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8779   }
8780 
8781   // C++ for OpenCL v1.0 s2.4:
8782   // Moreover the types used in parameters of the kernel functions must be:
8783   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8784   // types) for parameters passed by value;
8785   if (S.getLangOpts().OpenCLCPlusPlus &&
8786       !S.getOpenCLOptions().isAvailableOption(
8787           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8788       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8789     return InvalidKernelParam;
8790 
8791   if (PT->isRecordType())
8792     return RecordKernelParam;
8793 
8794   return ValidKernelParam;
8795 }
8796 
8797 static void checkIsValidOpenCLKernelParameter(
8798   Sema &S,
8799   Declarator &D,
8800   ParmVarDecl *Param,
8801   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8802   QualType PT = Param->getType();
8803 
8804   // Cache the valid types we encounter to avoid rechecking structs that are
8805   // used again
8806   if (ValidTypes.count(PT.getTypePtr()))
8807     return;
8808 
8809   switch (getOpenCLKernelParameterType(S, PT)) {
8810   case PtrPtrKernelParam:
8811     // OpenCL v3.0 s6.11.a:
8812     // A kernel function argument cannot be declared as a pointer to a pointer
8813     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8814     if (S.getLangOpts().OpenCLVersion < 120 &&
8815         !S.getLangOpts().OpenCLCPlusPlus) {
8816       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8817       D.setInvalidType();
8818       return;
8819     }
8820 
8821     ValidTypes.insert(PT.getTypePtr());
8822     return;
8823 
8824   case InvalidAddrSpacePtrKernelParam:
8825     // OpenCL v1.0 s6.5:
8826     // __kernel function arguments declared to be a pointer of a type can point
8827     // to one of the following address spaces only : __global, __local or
8828     // __constant.
8829     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8830     D.setInvalidType();
8831     return;
8832 
8833     // OpenCL v1.2 s6.9.k:
8834     // Arguments to kernel functions in a program cannot be declared with the
8835     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8836     // uintptr_t or a struct and/or union that contain fields declared to be
8837     // one of these built-in scalar types.
8838 
8839   case InvalidKernelParam:
8840     // OpenCL v1.2 s6.8 n:
8841     // A kernel function argument cannot be declared
8842     // of event_t type.
8843     // Do not diagnose half type since it is diagnosed as invalid argument
8844     // type for any function elsewhere.
8845     if (!PT->isHalfType()) {
8846       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8847 
8848       // Explain what typedefs are involved.
8849       const TypedefType *Typedef = nullptr;
8850       while ((Typedef = PT->getAs<TypedefType>())) {
8851         SourceLocation Loc = Typedef->getDecl()->getLocation();
8852         // SourceLocation may be invalid for a built-in type.
8853         if (Loc.isValid())
8854           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8855         PT = Typedef->desugar();
8856       }
8857     }
8858 
8859     D.setInvalidType();
8860     return;
8861 
8862   case PtrKernelParam:
8863   case ValidKernelParam:
8864     ValidTypes.insert(PT.getTypePtr());
8865     return;
8866 
8867   case RecordKernelParam:
8868     break;
8869   }
8870 
8871   // Track nested structs we will inspect
8872   SmallVector<const Decl *, 4> VisitStack;
8873 
8874   // Track where we are in the nested structs. Items will migrate from
8875   // VisitStack to HistoryStack as we do the DFS for bad field.
8876   SmallVector<const FieldDecl *, 4> HistoryStack;
8877   HistoryStack.push_back(nullptr);
8878 
8879   // At this point we already handled everything except of a RecordType or
8880   // an ArrayType of a RecordType.
8881   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8882   const RecordType *RecTy =
8883       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8884   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8885 
8886   VisitStack.push_back(RecTy->getDecl());
8887   assert(VisitStack.back() && "First decl null?");
8888 
8889   do {
8890     const Decl *Next = VisitStack.pop_back_val();
8891     if (!Next) {
8892       assert(!HistoryStack.empty());
8893       // Found a marker, we have gone up a level
8894       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8895         ValidTypes.insert(Hist->getType().getTypePtr());
8896 
8897       continue;
8898     }
8899 
8900     // Adds everything except the original parameter declaration (which is not a
8901     // field itself) to the history stack.
8902     const RecordDecl *RD;
8903     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8904       HistoryStack.push_back(Field);
8905 
8906       QualType FieldTy = Field->getType();
8907       // Other field types (known to be valid or invalid) are handled while we
8908       // walk around RecordDecl::fields().
8909       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8910              "Unexpected type.");
8911       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8912 
8913       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8914     } else {
8915       RD = cast<RecordDecl>(Next);
8916     }
8917 
8918     // Add a null marker so we know when we've gone back up a level
8919     VisitStack.push_back(nullptr);
8920 
8921     for (const auto *FD : RD->fields()) {
8922       QualType QT = FD->getType();
8923 
8924       if (ValidTypes.count(QT.getTypePtr()))
8925         continue;
8926 
8927       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8928       if (ParamType == ValidKernelParam)
8929         continue;
8930 
8931       if (ParamType == RecordKernelParam) {
8932         VisitStack.push_back(FD);
8933         continue;
8934       }
8935 
8936       // OpenCL v1.2 s6.9.p:
8937       // Arguments to kernel functions that are declared to be a struct or union
8938       // do not allow OpenCL objects to be passed as elements of the struct or
8939       // union.
8940       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8941           ParamType == InvalidAddrSpacePtrKernelParam) {
8942         S.Diag(Param->getLocation(),
8943                diag::err_record_with_pointers_kernel_param)
8944           << PT->isUnionType()
8945           << PT;
8946       } else {
8947         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8948       }
8949 
8950       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8951           << OrigRecDecl->getDeclName();
8952 
8953       // We have an error, now let's go back up through history and show where
8954       // the offending field came from
8955       for (ArrayRef<const FieldDecl *>::const_iterator
8956                I = HistoryStack.begin() + 1,
8957                E = HistoryStack.end();
8958            I != E; ++I) {
8959         const FieldDecl *OuterField = *I;
8960         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8961           << OuterField->getType();
8962       }
8963 
8964       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8965         << QT->isPointerType()
8966         << QT;
8967       D.setInvalidType();
8968       return;
8969     }
8970   } while (!VisitStack.empty());
8971 }
8972 
8973 /// Find the DeclContext in which a tag is implicitly declared if we see an
8974 /// elaborated type specifier in the specified context, and lookup finds
8975 /// nothing.
8976 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8977   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8978     DC = DC->getParent();
8979   return DC;
8980 }
8981 
8982 /// Find the Scope in which a tag is implicitly declared if we see an
8983 /// elaborated type specifier in the specified context, and lookup finds
8984 /// nothing.
8985 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8986   while (S->isClassScope() ||
8987          (LangOpts.CPlusPlus &&
8988           S->isFunctionPrototypeScope()) ||
8989          ((S->getFlags() & Scope::DeclScope) == 0) ||
8990          (S->getEntity() && S->getEntity()->isTransparentContext()))
8991     S = S->getParent();
8992   return S;
8993 }
8994 
8995 NamedDecl*
8996 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8997                               TypeSourceInfo *TInfo, LookupResult &Previous,
8998                               MultiTemplateParamsArg TemplateParamListsRef,
8999                               bool &AddToScope) {
9000   QualType R = TInfo->getType();
9001 
9002   assert(R->isFunctionType());
9003   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9004     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9005 
9006   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9007   for (TemplateParameterList *TPL : TemplateParamListsRef)
9008     TemplateParamLists.push_back(TPL);
9009   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9010     if (!TemplateParamLists.empty() &&
9011         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9012       TemplateParamLists.back() = Invented;
9013     else
9014       TemplateParamLists.push_back(Invented);
9015   }
9016 
9017   // TODO: consider using NameInfo for diagnostic.
9018   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9019   DeclarationName Name = NameInfo.getName();
9020   StorageClass SC = getFunctionStorageClass(*this, D);
9021 
9022   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9023     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9024          diag::err_invalid_thread)
9025       << DeclSpec::getSpecifierName(TSCS);
9026 
9027   if (D.isFirstDeclarationOfMember())
9028     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9029                            D.getIdentifierLoc());
9030 
9031   bool isFriend = false;
9032   FunctionTemplateDecl *FunctionTemplate = nullptr;
9033   bool isMemberSpecialization = false;
9034   bool isFunctionTemplateSpecialization = false;
9035 
9036   bool isDependentClassScopeExplicitSpecialization = false;
9037   bool HasExplicitTemplateArgs = false;
9038   TemplateArgumentListInfo TemplateArgs;
9039 
9040   bool isVirtualOkay = false;
9041 
9042   DeclContext *OriginalDC = DC;
9043   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9044 
9045   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9046                                               isVirtualOkay);
9047   if (!NewFD) return nullptr;
9048 
9049   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9050     NewFD->setTopLevelDeclInObjCContainer();
9051 
9052   // Set the lexical context. If this is a function-scope declaration, or has a
9053   // C++ scope specifier, or is the object of a friend declaration, the lexical
9054   // context will be different from the semantic context.
9055   NewFD->setLexicalDeclContext(CurContext);
9056 
9057   if (IsLocalExternDecl)
9058     NewFD->setLocalExternDecl();
9059 
9060   if (getLangOpts().CPlusPlus) {
9061     bool isInline = D.getDeclSpec().isInlineSpecified();
9062     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9063     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9064     isFriend = D.getDeclSpec().isFriendSpecified();
9065     if (isFriend && !isInline && D.isFunctionDefinition()) {
9066       // C++ [class.friend]p5
9067       //   A function can be defined in a friend declaration of a
9068       //   class . . . . Such a function is implicitly inline.
9069       NewFD->setImplicitlyInline();
9070     }
9071 
9072     // If this is a method defined in an __interface, and is not a constructor
9073     // or an overloaded operator, then set the pure flag (isVirtual will already
9074     // return true).
9075     if (const CXXRecordDecl *Parent =
9076           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9077       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9078         NewFD->setPure(true);
9079 
9080       // C++ [class.union]p2
9081       //   A union can have member functions, but not virtual functions.
9082       if (isVirtual && Parent->isUnion())
9083         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9084     }
9085 
9086     SetNestedNameSpecifier(*this, NewFD, D);
9087     isMemberSpecialization = false;
9088     isFunctionTemplateSpecialization = false;
9089     if (D.isInvalidType())
9090       NewFD->setInvalidDecl();
9091 
9092     // Match up the template parameter lists with the scope specifier, then
9093     // determine whether we have a template or a template specialization.
9094     bool Invalid = false;
9095     TemplateParameterList *TemplateParams =
9096         MatchTemplateParametersToScopeSpecifier(
9097             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9098             D.getCXXScopeSpec(),
9099             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9100                 ? D.getName().TemplateId
9101                 : nullptr,
9102             TemplateParamLists, isFriend, isMemberSpecialization,
9103             Invalid);
9104     if (TemplateParams) {
9105       // Check that we can declare a template here.
9106       if (CheckTemplateDeclScope(S, TemplateParams))
9107         NewFD->setInvalidDecl();
9108 
9109       if (TemplateParams->size() > 0) {
9110         // This is a function template
9111 
9112         // A destructor cannot be a template.
9113         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9114           Diag(NewFD->getLocation(), diag::err_destructor_template);
9115           NewFD->setInvalidDecl();
9116         }
9117 
9118         // If we're adding a template to a dependent context, we may need to
9119         // rebuilding some of the types used within the template parameter list,
9120         // now that we know what the current instantiation is.
9121         if (DC->isDependentContext()) {
9122           ContextRAII SavedContext(*this, DC);
9123           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9124             Invalid = true;
9125         }
9126 
9127         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9128                                                         NewFD->getLocation(),
9129                                                         Name, TemplateParams,
9130                                                         NewFD);
9131         FunctionTemplate->setLexicalDeclContext(CurContext);
9132         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9133 
9134         // For source fidelity, store the other template param lists.
9135         if (TemplateParamLists.size() > 1) {
9136           NewFD->setTemplateParameterListsInfo(Context,
9137               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9138                   .drop_back(1));
9139         }
9140       } else {
9141         // This is a function template specialization.
9142         isFunctionTemplateSpecialization = true;
9143         // For source fidelity, store all the template param lists.
9144         if (TemplateParamLists.size() > 0)
9145           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9146 
9147         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9148         if (isFriend) {
9149           // We want to remove the "template<>", found here.
9150           SourceRange RemoveRange = TemplateParams->getSourceRange();
9151 
9152           // If we remove the template<> and the name is not a
9153           // template-id, we're actually silently creating a problem:
9154           // the friend declaration will refer to an untemplated decl,
9155           // and clearly the user wants a template specialization.  So
9156           // we need to insert '<>' after the name.
9157           SourceLocation InsertLoc;
9158           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9159             InsertLoc = D.getName().getSourceRange().getEnd();
9160             InsertLoc = getLocForEndOfToken(InsertLoc);
9161           }
9162 
9163           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9164             << Name << RemoveRange
9165             << FixItHint::CreateRemoval(RemoveRange)
9166             << FixItHint::CreateInsertion(InsertLoc, "<>");
9167         }
9168       }
9169     } else {
9170       // Check that we can declare a template here.
9171       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9172           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9173         NewFD->setInvalidDecl();
9174 
9175       // All template param lists were matched against the scope specifier:
9176       // this is NOT (an explicit specialization of) a template.
9177       if (TemplateParamLists.size() > 0)
9178         // For source fidelity, store all the template param lists.
9179         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9180     }
9181 
9182     if (Invalid) {
9183       NewFD->setInvalidDecl();
9184       if (FunctionTemplate)
9185         FunctionTemplate->setInvalidDecl();
9186     }
9187 
9188     // C++ [dcl.fct.spec]p5:
9189     //   The virtual specifier shall only be used in declarations of
9190     //   nonstatic class member functions that appear within a
9191     //   member-specification of a class declaration; see 10.3.
9192     //
9193     if (isVirtual && !NewFD->isInvalidDecl()) {
9194       if (!isVirtualOkay) {
9195         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9196              diag::err_virtual_non_function);
9197       } else if (!CurContext->isRecord()) {
9198         // 'virtual' was specified outside of the class.
9199         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9200              diag::err_virtual_out_of_class)
9201           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9202       } else if (NewFD->getDescribedFunctionTemplate()) {
9203         // C++ [temp.mem]p3:
9204         //  A member function template shall not be virtual.
9205         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9206              diag::err_virtual_member_function_template)
9207           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9208       } else {
9209         // Okay: Add virtual to the method.
9210         NewFD->setVirtualAsWritten(true);
9211       }
9212 
9213       if (getLangOpts().CPlusPlus14 &&
9214           NewFD->getReturnType()->isUndeducedType())
9215         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9216     }
9217 
9218     if (getLangOpts().CPlusPlus14 &&
9219         (NewFD->isDependentContext() ||
9220          (isFriend && CurContext->isDependentContext())) &&
9221         NewFD->getReturnType()->isUndeducedType()) {
9222       // If the function template is referenced directly (for instance, as a
9223       // member of the current instantiation), pretend it has a dependent type.
9224       // This is not really justified by the standard, but is the only sane
9225       // thing to do.
9226       // FIXME: For a friend function, we have not marked the function as being
9227       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9228       const FunctionProtoType *FPT =
9229           NewFD->getType()->castAs<FunctionProtoType>();
9230       QualType Result =
9231           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9232       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9233                                              FPT->getExtProtoInfo()));
9234     }
9235 
9236     // C++ [dcl.fct.spec]p3:
9237     //  The inline specifier shall not appear on a block scope function
9238     //  declaration.
9239     if (isInline && !NewFD->isInvalidDecl()) {
9240       if (CurContext->isFunctionOrMethod()) {
9241         // 'inline' is not allowed on block scope function declaration.
9242         Diag(D.getDeclSpec().getInlineSpecLoc(),
9243              diag::err_inline_declaration_block_scope) << Name
9244           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9245       }
9246     }
9247 
9248     // C++ [dcl.fct.spec]p6:
9249     //  The explicit specifier shall be used only in the declaration of a
9250     //  constructor or conversion function within its class definition;
9251     //  see 12.3.1 and 12.3.2.
9252     if (hasExplicit && !NewFD->isInvalidDecl() &&
9253         !isa<CXXDeductionGuideDecl>(NewFD)) {
9254       if (!CurContext->isRecord()) {
9255         // 'explicit' was specified outside of the class.
9256         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9257              diag::err_explicit_out_of_class)
9258             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9259       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9260                  !isa<CXXConversionDecl>(NewFD)) {
9261         // 'explicit' was specified on a function that wasn't a constructor
9262         // or conversion function.
9263         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9264              diag::err_explicit_non_ctor_or_conv_function)
9265             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9266       }
9267     }
9268 
9269     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9270     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9271       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9272       // are implicitly inline.
9273       NewFD->setImplicitlyInline();
9274 
9275       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9276       // be either constructors or to return a literal type. Therefore,
9277       // destructors cannot be declared constexpr.
9278       if (isa<CXXDestructorDecl>(NewFD) &&
9279           (!getLangOpts().CPlusPlus20 ||
9280            ConstexprKind == ConstexprSpecKind::Consteval)) {
9281         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9282             << static_cast<int>(ConstexprKind);
9283         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9284                                     ? ConstexprSpecKind::Unspecified
9285                                     : ConstexprSpecKind::Constexpr);
9286       }
9287       // C++20 [dcl.constexpr]p2: An allocation function, or a
9288       // deallocation function shall not be declared with the consteval
9289       // specifier.
9290       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9291           (NewFD->getOverloadedOperator() == OO_New ||
9292            NewFD->getOverloadedOperator() == OO_Array_New ||
9293            NewFD->getOverloadedOperator() == OO_Delete ||
9294            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9295         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9296              diag::err_invalid_consteval_decl_kind)
9297             << NewFD;
9298         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9299       }
9300     }
9301 
9302     // If __module_private__ was specified, mark the function accordingly.
9303     if (D.getDeclSpec().isModulePrivateSpecified()) {
9304       if (isFunctionTemplateSpecialization) {
9305         SourceLocation ModulePrivateLoc
9306           = D.getDeclSpec().getModulePrivateSpecLoc();
9307         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9308           << 0
9309           << FixItHint::CreateRemoval(ModulePrivateLoc);
9310       } else {
9311         NewFD->setModulePrivate();
9312         if (FunctionTemplate)
9313           FunctionTemplate->setModulePrivate();
9314       }
9315     }
9316 
9317     if (isFriend) {
9318       if (FunctionTemplate) {
9319         FunctionTemplate->setObjectOfFriendDecl();
9320         FunctionTemplate->setAccess(AS_public);
9321       }
9322       NewFD->setObjectOfFriendDecl();
9323       NewFD->setAccess(AS_public);
9324     }
9325 
9326     // If a function is defined as defaulted or deleted, mark it as such now.
9327     // We'll do the relevant checks on defaulted / deleted functions later.
9328     switch (D.getFunctionDefinitionKind()) {
9329     case FunctionDefinitionKind::Declaration:
9330     case FunctionDefinitionKind::Definition:
9331       break;
9332 
9333     case FunctionDefinitionKind::Defaulted:
9334       NewFD->setDefaulted();
9335       break;
9336 
9337     case FunctionDefinitionKind::Deleted:
9338       NewFD->setDeletedAsWritten();
9339       break;
9340     }
9341 
9342     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9343         D.isFunctionDefinition()) {
9344       // C++ [class.mfct]p2:
9345       //   A member function may be defined (8.4) in its class definition, in
9346       //   which case it is an inline member function (7.1.2)
9347       NewFD->setImplicitlyInline();
9348     }
9349 
9350     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9351         !CurContext->isRecord()) {
9352       // C++ [class.static]p1:
9353       //   A data or function member of a class may be declared static
9354       //   in a class definition, in which case it is a static member of
9355       //   the class.
9356 
9357       // Complain about the 'static' specifier if it's on an out-of-line
9358       // member function definition.
9359 
9360       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9361       // member function template declaration and class member template
9362       // declaration (MSVC versions before 2015), warn about this.
9363       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9364            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9365              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9366            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9367            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9368         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9369     }
9370 
9371     // C++11 [except.spec]p15:
9372     //   A deallocation function with no exception-specification is treated
9373     //   as if it were specified with noexcept(true).
9374     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9375     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9376          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9377         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9378       NewFD->setType(Context.getFunctionType(
9379           FPT->getReturnType(), FPT->getParamTypes(),
9380           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9381   }
9382 
9383   // Filter out previous declarations that don't match the scope.
9384   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9385                        D.getCXXScopeSpec().isNotEmpty() ||
9386                        isMemberSpecialization ||
9387                        isFunctionTemplateSpecialization);
9388 
9389   // Handle GNU asm-label extension (encoded as an attribute).
9390   if (Expr *E = (Expr*) D.getAsmLabel()) {
9391     // The parser guarantees this is a string.
9392     StringLiteral *SE = cast<StringLiteral>(E);
9393     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9394                                         /*IsLiteralLabel=*/true,
9395                                         SE->getStrTokenLoc(0)));
9396   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9397     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9398       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9399     if (I != ExtnameUndeclaredIdentifiers.end()) {
9400       if (isDeclExternC(NewFD)) {
9401         NewFD->addAttr(I->second);
9402         ExtnameUndeclaredIdentifiers.erase(I);
9403       } else
9404         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9405             << /*Variable*/0 << NewFD;
9406     }
9407   }
9408 
9409   // Copy the parameter declarations from the declarator D to the function
9410   // declaration NewFD, if they are available.  First scavenge them into Params.
9411   SmallVector<ParmVarDecl*, 16> Params;
9412   unsigned FTIIdx;
9413   if (D.isFunctionDeclarator(FTIIdx)) {
9414     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9415 
9416     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9417     // function that takes no arguments, not a function that takes a
9418     // single void argument.
9419     // We let through "const void" here because Sema::GetTypeForDeclarator
9420     // already checks for that case.
9421     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9422       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9423         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9424         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9425         Param->setDeclContext(NewFD);
9426         Params.push_back(Param);
9427 
9428         if (Param->isInvalidDecl())
9429           NewFD->setInvalidDecl();
9430       }
9431     }
9432 
9433     if (!getLangOpts().CPlusPlus) {
9434       // In C, find all the tag declarations from the prototype and move them
9435       // into the function DeclContext. Remove them from the surrounding tag
9436       // injection context of the function, which is typically but not always
9437       // the TU.
9438       DeclContext *PrototypeTagContext =
9439           getTagInjectionContext(NewFD->getLexicalDeclContext());
9440       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9441         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9442 
9443         // We don't want to reparent enumerators. Look at their parent enum
9444         // instead.
9445         if (!TD) {
9446           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9447             TD = cast<EnumDecl>(ECD->getDeclContext());
9448         }
9449         if (!TD)
9450           continue;
9451         DeclContext *TagDC = TD->getLexicalDeclContext();
9452         if (!TagDC->containsDecl(TD))
9453           continue;
9454         TagDC->removeDecl(TD);
9455         TD->setDeclContext(NewFD);
9456         NewFD->addDecl(TD);
9457 
9458         // Preserve the lexical DeclContext if it is not the surrounding tag
9459         // injection context of the FD. In this example, the semantic context of
9460         // E will be f and the lexical context will be S, while both the
9461         // semantic and lexical contexts of S will be f:
9462         //   void f(struct S { enum E { a } f; } s);
9463         if (TagDC != PrototypeTagContext)
9464           TD->setLexicalDeclContext(TagDC);
9465       }
9466     }
9467   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9468     // When we're declaring a function with a typedef, typeof, etc as in the
9469     // following example, we'll need to synthesize (unnamed)
9470     // parameters for use in the declaration.
9471     //
9472     // @code
9473     // typedef void fn(int);
9474     // fn f;
9475     // @endcode
9476 
9477     // Synthesize a parameter for each argument type.
9478     for (const auto &AI : FT->param_types()) {
9479       ParmVarDecl *Param =
9480           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9481       Param->setScopeInfo(0, Params.size());
9482       Params.push_back(Param);
9483     }
9484   } else {
9485     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9486            "Should not need args for typedef of non-prototype fn");
9487   }
9488 
9489   // Finally, we know we have the right number of parameters, install them.
9490   NewFD->setParams(Params);
9491 
9492   if (D.getDeclSpec().isNoreturnSpecified())
9493     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9494                                            D.getDeclSpec().getNoreturnSpecLoc(),
9495                                            AttributeCommonInfo::AS_Keyword));
9496 
9497   // Functions returning a variably modified type violate C99 6.7.5.2p2
9498   // because all functions have linkage.
9499   if (!NewFD->isInvalidDecl() &&
9500       NewFD->getReturnType()->isVariablyModifiedType()) {
9501     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9502     NewFD->setInvalidDecl();
9503   }
9504 
9505   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9506   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9507       !NewFD->hasAttr<SectionAttr>())
9508     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9509         Context, PragmaClangTextSection.SectionName,
9510         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9511 
9512   // Apply an implicit SectionAttr if #pragma code_seg is active.
9513   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9514       !NewFD->hasAttr<SectionAttr>()) {
9515     NewFD->addAttr(SectionAttr::CreateImplicit(
9516         Context, CodeSegStack.CurrentValue->getString(),
9517         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9518         SectionAttr::Declspec_allocate));
9519     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9520                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9521                          ASTContext::PSF_Read,
9522                      NewFD))
9523       NewFD->dropAttr<SectionAttr>();
9524   }
9525 
9526   // Apply an implicit CodeSegAttr from class declspec or
9527   // apply an implicit SectionAttr from #pragma code_seg if active.
9528   if (!NewFD->hasAttr<CodeSegAttr>()) {
9529     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9530                                                                  D.isFunctionDefinition())) {
9531       NewFD->addAttr(SAttr);
9532     }
9533   }
9534 
9535   // Handle attributes.
9536   ProcessDeclAttributes(S, NewFD, D);
9537 
9538   if (getLangOpts().OpenCL) {
9539     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9540     // type declaration will generate a compilation error.
9541     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9542     if (AddressSpace != LangAS::Default) {
9543       Diag(NewFD->getLocation(),
9544            diag::err_opencl_return_value_with_address_space);
9545       NewFD->setInvalidDecl();
9546     }
9547   }
9548 
9549   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9550     checkDeviceDecl(NewFD, D.getBeginLoc());
9551 
9552   if (!getLangOpts().CPlusPlus) {
9553     // Perform semantic checking on the function declaration.
9554     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9555       CheckMain(NewFD, D.getDeclSpec());
9556 
9557     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9558       CheckMSVCRTEntryPoint(NewFD);
9559 
9560     if (!NewFD->isInvalidDecl())
9561       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9562                                                   isMemberSpecialization));
9563     else if (!Previous.empty())
9564       // Recover gracefully from an invalid redeclaration.
9565       D.setRedeclaration(true);
9566     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9567             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9568            "previous declaration set still overloaded");
9569 
9570     // Diagnose no-prototype function declarations with calling conventions that
9571     // don't support variadic calls. Only do this in C and do it after merging
9572     // possibly prototyped redeclarations.
9573     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9574     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9575       CallingConv CC = FT->getExtInfo().getCC();
9576       if (!supportsVariadicCall(CC)) {
9577         // Windows system headers sometimes accidentally use stdcall without
9578         // (void) parameters, so we relax this to a warning.
9579         int DiagID =
9580             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9581         Diag(NewFD->getLocation(), DiagID)
9582             << FunctionType::getNameForCallConv(CC);
9583       }
9584     }
9585 
9586    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9587        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9588      checkNonTrivialCUnion(NewFD->getReturnType(),
9589                            NewFD->getReturnTypeSourceRange().getBegin(),
9590                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9591   } else {
9592     // C++11 [replacement.functions]p3:
9593     //  The program's definitions shall not be specified as inline.
9594     //
9595     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9596     //
9597     // Suppress the diagnostic if the function is __attribute__((used)), since
9598     // that forces an external definition to be emitted.
9599     if (D.getDeclSpec().isInlineSpecified() &&
9600         NewFD->isReplaceableGlobalAllocationFunction() &&
9601         !NewFD->hasAttr<UsedAttr>())
9602       Diag(D.getDeclSpec().getInlineSpecLoc(),
9603            diag::ext_operator_new_delete_declared_inline)
9604         << NewFD->getDeclName();
9605 
9606     // If the declarator is a template-id, translate the parser's template
9607     // argument list into our AST format.
9608     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9609       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9610       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9611       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9612       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9613                                          TemplateId->NumArgs);
9614       translateTemplateArguments(TemplateArgsPtr,
9615                                  TemplateArgs);
9616 
9617       HasExplicitTemplateArgs = true;
9618 
9619       if (NewFD->isInvalidDecl()) {
9620         HasExplicitTemplateArgs = false;
9621       } else if (FunctionTemplate) {
9622         // Function template with explicit template arguments.
9623         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9624           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9625 
9626         HasExplicitTemplateArgs = false;
9627       } else {
9628         assert((isFunctionTemplateSpecialization ||
9629                 D.getDeclSpec().isFriendSpecified()) &&
9630                "should have a 'template<>' for this decl");
9631         // "friend void foo<>(int);" is an implicit specialization decl.
9632         isFunctionTemplateSpecialization = true;
9633       }
9634     } else if (isFriend && isFunctionTemplateSpecialization) {
9635       // This combination is only possible in a recovery case;  the user
9636       // wrote something like:
9637       //   template <> friend void foo(int);
9638       // which we're recovering from as if the user had written:
9639       //   friend void foo<>(int);
9640       // Go ahead and fake up a template id.
9641       HasExplicitTemplateArgs = true;
9642       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9643       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9644     }
9645 
9646     // We do not add HD attributes to specializations here because
9647     // they may have different constexpr-ness compared to their
9648     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9649     // may end up with different effective targets. Instead, a
9650     // specialization inherits its target attributes from its template
9651     // in the CheckFunctionTemplateSpecialization() call below.
9652     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9653       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9654 
9655     // If it's a friend (and only if it's a friend), it's possible
9656     // that either the specialized function type or the specialized
9657     // template is dependent, and therefore matching will fail.  In
9658     // this case, don't check the specialization yet.
9659     if (isFunctionTemplateSpecialization && isFriend &&
9660         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9661          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9662              TemplateArgs.arguments()))) {
9663       assert(HasExplicitTemplateArgs &&
9664              "friend function specialization without template args");
9665       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9666                                                        Previous))
9667         NewFD->setInvalidDecl();
9668     } else if (isFunctionTemplateSpecialization) {
9669       if (CurContext->isDependentContext() && CurContext->isRecord()
9670           && !isFriend) {
9671         isDependentClassScopeExplicitSpecialization = true;
9672       } else if (!NewFD->isInvalidDecl() &&
9673                  CheckFunctionTemplateSpecialization(
9674                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9675                      Previous))
9676         NewFD->setInvalidDecl();
9677 
9678       // C++ [dcl.stc]p1:
9679       //   A storage-class-specifier shall not be specified in an explicit
9680       //   specialization (14.7.3)
9681       FunctionTemplateSpecializationInfo *Info =
9682           NewFD->getTemplateSpecializationInfo();
9683       if (Info && SC != SC_None) {
9684         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9685           Diag(NewFD->getLocation(),
9686                diag::err_explicit_specialization_inconsistent_storage_class)
9687             << SC
9688             << FixItHint::CreateRemoval(
9689                                       D.getDeclSpec().getStorageClassSpecLoc());
9690 
9691         else
9692           Diag(NewFD->getLocation(),
9693                diag::ext_explicit_specialization_storage_class)
9694             << FixItHint::CreateRemoval(
9695                                       D.getDeclSpec().getStorageClassSpecLoc());
9696       }
9697     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9698       if (CheckMemberSpecialization(NewFD, Previous))
9699           NewFD->setInvalidDecl();
9700     }
9701 
9702     // Perform semantic checking on the function declaration.
9703     if (!isDependentClassScopeExplicitSpecialization) {
9704       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9705         CheckMain(NewFD, D.getDeclSpec());
9706 
9707       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9708         CheckMSVCRTEntryPoint(NewFD);
9709 
9710       if (!NewFD->isInvalidDecl())
9711         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9712                                                     isMemberSpecialization));
9713       else if (!Previous.empty())
9714         // Recover gracefully from an invalid redeclaration.
9715         D.setRedeclaration(true);
9716     }
9717 
9718     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9719             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9720            "previous declaration set still overloaded");
9721 
9722     NamedDecl *PrincipalDecl = (FunctionTemplate
9723                                 ? cast<NamedDecl>(FunctionTemplate)
9724                                 : NewFD);
9725 
9726     if (isFriend && NewFD->getPreviousDecl()) {
9727       AccessSpecifier Access = AS_public;
9728       if (!NewFD->isInvalidDecl())
9729         Access = NewFD->getPreviousDecl()->getAccess();
9730 
9731       NewFD->setAccess(Access);
9732       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9733     }
9734 
9735     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9736         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9737       PrincipalDecl->setNonMemberOperator();
9738 
9739     // If we have a function template, check the template parameter
9740     // list. This will check and merge default template arguments.
9741     if (FunctionTemplate) {
9742       FunctionTemplateDecl *PrevTemplate =
9743                                      FunctionTemplate->getPreviousDecl();
9744       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9745                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9746                                     : nullptr,
9747                             D.getDeclSpec().isFriendSpecified()
9748                               ? (D.isFunctionDefinition()
9749                                    ? TPC_FriendFunctionTemplateDefinition
9750                                    : TPC_FriendFunctionTemplate)
9751                               : (D.getCXXScopeSpec().isSet() &&
9752                                  DC && DC->isRecord() &&
9753                                  DC->isDependentContext())
9754                                   ? TPC_ClassTemplateMember
9755                                   : TPC_FunctionTemplate);
9756     }
9757 
9758     if (NewFD->isInvalidDecl()) {
9759       // Ignore all the rest of this.
9760     } else if (!D.isRedeclaration()) {
9761       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9762                                        AddToScope };
9763       // Fake up an access specifier if it's supposed to be a class member.
9764       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9765         NewFD->setAccess(AS_public);
9766 
9767       // Qualified decls generally require a previous declaration.
9768       if (D.getCXXScopeSpec().isSet()) {
9769         // ...with the major exception of templated-scope or
9770         // dependent-scope friend declarations.
9771 
9772         // TODO: we currently also suppress this check in dependent
9773         // contexts because (1) the parameter depth will be off when
9774         // matching friend templates and (2) we might actually be
9775         // selecting a friend based on a dependent factor.  But there
9776         // are situations where these conditions don't apply and we
9777         // can actually do this check immediately.
9778         //
9779         // Unless the scope is dependent, it's always an error if qualified
9780         // redeclaration lookup found nothing at all. Diagnose that now;
9781         // nothing will diagnose that error later.
9782         if (isFriend &&
9783             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9784              (!Previous.empty() && CurContext->isDependentContext()))) {
9785           // ignore these
9786         } else if (NewFD->isCPUDispatchMultiVersion() ||
9787                    NewFD->isCPUSpecificMultiVersion()) {
9788           // ignore this, we allow the redeclaration behavior here to create new
9789           // versions of the function.
9790         } else {
9791           // The user tried to provide an out-of-line definition for a
9792           // function that is a member of a class or namespace, but there
9793           // was no such member function declared (C++ [class.mfct]p2,
9794           // C++ [namespace.memdef]p2). For example:
9795           //
9796           // class X {
9797           //   void f() const;
9798           // };
9799           //
9800           // void X::f() { } // ill-formed
9801           //
9802           // Complain about this problem, and attempt to suggest close
9803           // matches (e.g., those that differ only in cv-qualifiers and
9804           // whether the parameter types are references).
9805 
9806           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9807                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9808             AddToScope = ExtraArgs.AddToScope;
9809             return Result;
9810           }
9811         }
9812 
9813         // Unqualified local friend declarations are required to resolve
9814         // to something.
9815       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9816         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9817                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9818           AddToScope = ExtraArgs.AddToScope;
9819           return Result;
9820         }
9821       }
9822     } else if (!D.isFunctionDefinition() &&
9823                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9824                !isFriend && !isFunctionTemplateSpecialization &&
9825                !isMemberSpecialization) {
9826       // An out-of-line member function declaration must also be a
9827       // definition (C++ [class.mfct]p2).
9828       // Note that this is not the case for explicit specializations of
9829       // function templates or member functions of class templates, per
9830       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9831       // extension for compatibility with old SWIG code which likes to
9832       // generate them.
9833       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9834         << D.getCXXScopeSpec().getRange();
9835     }
9836   }
9837 
9838   // If this is the first declaration of a library builtin function, add
9839   // attributes as appropriate.
9840   if (!D.isRedeclaration() &&
9841       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9842     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9843       if (unsigned BuiltinID = II->getBuiltinID()) {
9844         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9845           // Validate the type matches unless this builtin is specified as
9846           // matching regardless of its declared type.
9847           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9848             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9849           } else {
9850             ASTContext::GetBuiltinTypeError Error;
9851             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9852             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9853 
9854             if (!Error && !BuiltinType.isNull() &&
9855                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9856                     NewFD->getType(), BuiltinType))
9857               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9858           }
9859         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9860                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9861           // FIXME: We should consider this a builtin only in the std namespace.
9862           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9863         }
9864       }
9865     }
9866   }
9867 
9868   ProcessPragmaWeak(S, NewFD);
9869   checkAttributesAfterMerging(*this, *NewFD);
9870 
9871   AddKnownFunctionAttributes(NewFD);
9872 
9873   if (NewFD->hasAttr<OverloadableAttr>() &&
9874       !NewFD->getType()->getAs<FunctionProtoType>()) {
9875     Diag(NewFD->getLocation(),
9876          diag::err_attribute_overloadable_no_prototype)
9877       << NewFD;
9878 
9879     // Turn this into a variadic function with no parameters.
9880     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9881     FunctionProtoType::ExtProtoInfo EPI(
9882         Context.getDefaultCallingConvention(true, false));
9883     EPI.Variadic = true;
9884     EPI.ExtInfo = FT->getExtInfo();
9885 
9886     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9887     NewFD->setType(R);
9888   }
9889 
9890   // If there's a #pragma GCC visibility in scope, and this isn't a class
9891   // member, set the visibility of this function.
9892   if (!DC->isRecord() && NewFD->isExternallyVisible())
9893     AddPushedVisibilityAttribute(NewFD);
9894 
9895   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9896   // marking the function.
9897   AddCFAuditedAttribute(NewFD);
9898 
9899   // If this is a function definition, check if we have to apply optnone due to
9900   // a pragma.
9901   if(D.isFunctionDefinition())
9902     AddRangeBasedOptnone(NewFD);
9903 
9904   // If this is the first declaration of an extern C variable, update
9905   // the map of such variables.
9906   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9907       isIncompleteDeclExternC(*this, NewFD))
9908     RegisterLocallyScopedExternCDecl(NewFD, S);
9909 
9910   // Set this FunctionDecl's range up to the right paren.
9911   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9912 
9913   if (D.isRedeclaration() && !Previous.empty()) {
9914     NamedDecl *Prev = Previous.getRepresentativeDecl();
9915     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9916                                    isMemberSpecialization ||
9917                                        isFunctionTemplateSpecialization,
9918                                    D.isFunctionDefinition());
9919   }
9920 
9921   if (getLangOpts().CUDA) {
9922     IdentifierInfo *II = NewFD->getIdentifier();
9923     if (II && II->isStr(getCudaConfigureFuncName()) &&
9924         !NewFD->isInvalidDecl() &&
9925         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9926       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9927         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9928             << getCudaConfigureFuncName();
9929       Context.setcudaConfigureCallDecl(NewFD);
9930     }
9931 
9932     // Variadic functions, other than a *declaration* of printf, are not allowed
9933     // in device-side CUDA code, unless someone passed
9934     // -fcuda-allow-variadic-functions.
9935     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9936         (NewFD->hasAttr<CUDADeviceAttr>() ||
9937          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9938         !(II && II->isStr("printf") && NewFD->isExternC() &&
9939           !D.isFunctionDefinition())) {
9940       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9941     }
9942   }
9943 
9944   MarkUnusedFileScopedDecl(NewFD);
9945 
9946 
9947 
9948   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9949     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9950     if ((getLangOpts().OpenCLVersion >= 120)
9951         && (SC == SC_Static)) {
9952       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9953       D.setInvalidType();
9954     }
9955 
9956     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9957     if (!NewFD->getReturnType()->isVoidType()) {
9958       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9959       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9960           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9961                                 : FixItHint());
9962       D.setInvalidType();
9963     }
9964 
9965     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9966     for (auto Param : NewFD->parameters())
9967       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9968 
9969     if (getLangOpts().OpenCLCPlusPlus) {
9970       if (DC->isRecord()) {
9971         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9972         D.setInvalidType();
9973       }
9974       if (FunctionTemplate) {
9975         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9976         D.setInvalidType();
9977       }
9978     }
9979   }
9980 
9981   if (getLangOpts().CPlusPlus) {
9982     if (FunctionTemplate) {
9983       if (NewFD->isInvalidDecl())
9984         FunctionTemplate->setInvalidDecl();
9985       return FunctionTemplate;
9986     }
9987 
9988     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9989       CompleteMemberSpecialization(NewFD, Previous);
9990   }
9991 
9992   for (const ParmVarDecl *Param : NewFD->parameters()) {
9993     QualType PT = Param->getType();
9994 
9995     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9996     // types.
9997     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9998       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9999         QualType ElemTy = PipeTy->getElementType();
10000           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10001             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10002             D.setInvalidType();
10003           }
10004       }
10005     }
10006   }
10007 
10008   // Here we have an function template explicit specialization at class scope.
10009   // The actual specialization will be postponed to template instatiation
10010   // time via the ClassScopeFunctionSpecializationDecl node.
10011   if (isDependentClassScopeExplicitSpecialization) {
10012     ClassScopeFunctionSpecializationDecl *NewSpec =
10013                          ClassScopeFunctionSpecializationDecl::Create(
10014                                 Context, CurContext, NewFD->getLocation(),
10015                                 cast<CXXMethodDecl>(NewFD),
10016                                 HasExplicitTemplateArgs, TemplateArgs);
10017     CurContext->addDecl(NewSpec);
10018     AddToScope = false;
10019   }
10020 
10021   // Diagnose availability attributes. Availability cannot be used on functions
10022   // that are run during load/unload.
10023   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10024     if (NewFD->hasAttr<ConstructorAttr>()) {
10025       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10026           << 1;
10027       NewFD->dropAttr<AvailabilityAttr>();
10028     }
10029     if (NewFD->hasAttr<DestructorAttr>()) {
10030       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10031           << 2;
10032       NewFD->dropAttr<AvailabilityAttr>();
10033     }
10034   }
10035 
10036   // Diagnose no_builtin attribute on function declaration that are not a
10037   // definition.
10038   // FIXME: We should really be doing this in
10039   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10040   // the FunctionDecl and at this point of the code
10041   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10042   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10043   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10044     switch (D.getFunctionDefinitionKind()) {
10045     case FunctionDefinitionKind::Defaulted:
10046     case FunctionDefinitionKind::Deleted:
10047       Diag(NBA->getLocation(),
10048            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10049           << NBA->getSpelling();
10050       break;
10051     case FunctionDefinitionKind::Declaration:
10052       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10053           << NBA->getSpelling();
10054       break;
10055     case FunctionDefinitionKind::Definition:
10056       break;
10057     }
10058 
10059   return NewFD;
10060 }
10061 
10062 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10063 /// when __declspec(code_seg) "is applied to a class, all member functions of
10064 /// the class and nested classes -- this includes compiler-generated special
10065 /// member functions -- are put in the specified segment."
10066 /// The actual behavior is a little more complicated. The Microsoft compiler
10067 /// won't check outer classes if there is an active value from #pragma code_seg.
10068 /// The CodeSeg is always applied from the direct parent but only from outer
10069 /// classes when the #pragma code_seg stack is empty. See:
10070 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10071 /// available since MS has removed the page.
10072 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10073   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10074   if (!Method)
10075     return nullptr;
10076   const CXXRecordDecl *Parent = Method->getParent();
10077   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10078     Attr *NewAttr = SAttr->clone(S.getASTContext());
10079     NewAttr->setImplicit(true);
10080     return NewAttr;
10081   }
10082 
10083   // The Microsoft compiler won't check outer classes for the CodeSeg
10084   // when the #pragma code_seg stack is active.
10085   if (S.CodeSegStack.CurrentValue)
10086    return nullptr;
10087 
10088   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10089     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10090       Attr *NewAttr = SAttr->clone(S.getASTContext());
10091       NewAttr->setImplicit(true);
10092       return NewAttr;
10093     }
10094   }
10095   return nullptr;
10096 }
10097 
10098 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10099 /// containing class. Otherwise it will return implicit SectionAttr if the
10100 /// function is a definition and there is an active value on CodeSegStack
10101 /// (from the current #pragma code-seg value).
10102 ///
10103 /// \param FD Function being declared.
10104 /// \param IsDefinition Whether it is a definition or just a declarartion.
10105 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10106 ///          nullptr if no attribute should be added.
10107 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10108                                                        bool IsDefinition) {
10109   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10110     return A;
10111   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10112       CodeSegStack.CurrentValue)
10113     return SectionAttr::CreateImplicit(
10114         getASTContext(), CodeSegStack.CurrentValue->getString(),
10115         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10116         SectionAttr::Declspec_allocate);
10117   return nullptr;
10118 }
10119 
10120 /// Determines if we can perform a correct type check for \p D as a
10121 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10122 /// best-effort check.
10123 ///
10124 /// \param NewD The new declaration.
10125 /// \param OldD The old declaration.
10126 /// \param NewT The portion of the type of the new declaration to check.
10127 /// \param OldT The portion of the type of the old declaration to check.
10128 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10129                                           QualType NewT, QualType OldT) {
10130   if (!NewD->getLexicalDeclContext()->isDependentContext())
10131     return true;
10132 
10133   // For dependently-typed local extern declarations and friends, we can't
10134   // perform a correct type check in general until instantiation:
10135   //
10136   //   int f();
10137   //   template<typename T> void g() { T f(); }
10138   //
10139   // (valid if g() is only instantiated with T = int).
10140   if (NewT->isDependentType() &&
10141       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10142     return false;
10143 
10144   // Similarly, if the previous declaration was a dependent local extern
10145   // declaration, we don't really know its type yet.
10146   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10147     return false;
10148 
10149   return true;
10150 }
10151 
10152 /// Checks if the new declaration declared in dependent context must be
10153 /// put in the same redeclaration chain as the specified declaration.
10154 ///
10155 /// \param D Declaration that is checked.
10156 /// \param PrevDecl Previous declaration found with proper lookup method for the
10157 ///                 same declaration name.
10158 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10159 ///          belongs to.
10160 ///
10161 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10162   if (!D->getLexicalDeclContext()->isDependentContext())
10163     return true;
10164 
10165   // Don't chain dependent friend function definitions until instantiation, to
10166   // permit cases like
10167   //
10168   //   void func();
10169   //   template<typename T> class C1 { friend void func() {} };
10170   //   template<typename T> class C2 { friend void func() {} };
10171   //
10172   // ... which is valid if only one of C1 and C2 is ever instantiated.
10173   //
10174   // FIXME: This need only apply to function definitions. For now, we proxy
10175   // this by checking for a file-scope function. We do not want this to apply
10176   // to friend declarations nominating member functions, because that gets in
10177   // the way of access checks.
10178   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10179     return false;
10180 
10181   auto *VD = dyn_cast<ValueDecl>(D);
10182   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10183   return !VD || !PrevVD ||
10184          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10185                                         PrevVD->getType());
10186 }
10187 
10188 /// Check the target attribute of the function for MultiVersion
10189 /// validity.
10190 ///
10191 /// Returns true if there was an error, false otherwise.
10192 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10193   const auto *TA = FD->getAttr<TargetAttr>();
10194   assert(TA && "MultiVersion Candidate requires a target attribute");
10195   ParsedTargetAttr ParseInfo = TA->parse();
10196   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10197   enum ErrType { Feature = 0, Architecture = 1 };
10198 
10199   if (!ParseInfo.Architecture.empty() &&
10200       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10201     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10202         << Architecture << ParseInfo.Architecture;
10203     return true;
10204   }
10205 
10206   for (const auto &Feat : ParseInfo.Features) {
10207     auto BareFeat = StringRef{Feat}.substr(1);
10208     if (Feat[0] == '-') {
10209       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10210           << Feature << ("no-" + BareFeat).str();
10211       return true;
10212     }
10213 
10214     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10215         !TargetInfo.isValidFeatureName(BareFeat)) {
10216       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10217           << Feature << BareFeat;
10218       return true;
10219     }
10220   }
10221   return false;
10222 }
10223 
10224 // Provide a white-list of attributes that are allowed to be combined with
10225 // multiversion functions.
10226 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10227                                            MultiVersionKind MVType) {
10228   // Note: this list/diagnosis must match the list in
10229   // checkMultiversionAttributesAllSame.
10230   switch (Kind) {
10231   default:
10232     return false;
10233   case attr::Used:
10234     return MVType == MultiVersionKind::Target;
10235   case attr::NonNull:
10236   case attr::NoThrow:
10237     return true;
10238   }
10239 }
10240 
10241 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10242                                                  const FunctionDecl *FD,
10243                                                  const FunctionDecl *CausedFD,
10244                                                  MultiVersionKind MVType) {
10245   bool IsCPUSpecificCPUDispatchMVType =
10246       MVType == MultiVersionKind::CPUDispatch ||
10247       MVType == MultiVersionKind::CPUSpecific;
10248   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10249                             Sema &S, const Attr *A) {
10250     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10251         << IsCPUSpecificCPUDispatchMVType << A;
10252     if (CausedFD)
10253       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10254     return true;
10255   };
10256 
10257   for (const Attr *A : FD->attrs()) {
10258     switch (A->getKind()) {
10259     case attr::CPUDispatch:
10260     case attr::CPUSpecific:
10261       if (MVType != MultiVersionKind::CPUDispatch &&
10262           MVType != MultiVersionKind::CPUSpecific)
10263         return Diagnose(S, A);
10264       break;
10265     case attr::Target:
10266       if (MVType != MultiVersionKind::Target)
10267         return Diagnose(S, A);
10268       break;
10269     default:
10270       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10271         return Diagnose(S, A);
10272       break;
10273     }
10274   }
10275   return false;
10276 }
10277 
10278 bool Sema::areMultiversionVariantFunctionsCompatible(
10279     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10280     const PartialDiagnostic &NoProtoDiagID,
10281     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10282     const PartialDiagnosticAt &NoSupportDiagIDAt,
10283     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10284     bool ConstexprSupported, bool CLinkageMayDiffer) {
10285   enum DoesntSupport {
10286     FuncTemplates = 0,
10287     VirtFuncs = 1,
10288     DeducedReturn = 2,
10289     Constructors = 3,
10290     Destructors = 4,
10291     DeletedFuncs = 5,
10292     DefaultedFuncs = 6,
10293     ConstexprFuncs = 7,
10294     ConstevalFuncs = 8,
10295   };
10296   enum Different {
10297     CallingConv = 0,
10298     ReturnType = 1,
10299     ConstexprSpec = 2,
10300     InlineSpec = 3,
10301     StorageClass = 4,
10302     Linkage = 5,
10303   };
10304 
10305   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10306       !OldFD->getType()->getAs<FunctionProtoType>()) {
10307     Diag(OldFD->getLocation(), NoProtoDiagID);
10308     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10309     return true;
10310   }
10311 
10312   if (NoProtoDiagID.getDiagID() != 0 &&
10313       !NewFD->getType()->getAs<FunctionProtoType>())
10314     return Diag(NewFD->getLocation(), NoProtoDiagID);
10315 
10316   if (!TemplatesSupported &&
10317       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10318     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10319            << FuncTemplates;
10320 
10321   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10322     if (NewCXXFD->isVirtual())
10323       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10324              << VirtFuncs;
10325 
10326     if (isa<CXXConstructorDecl>(NewCXXFD))
10327       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10328              << Constructors;
10329 
10330     if (isa<CXXDestructorDecl>(NewCXXFD))
10331       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10332              << Destructors;
10333   }
10334 
10335   if (NewFD->isDeleted())
10336     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10337            << DeletedFuncs;
10338 
10339   if (NewFD->isDefaulted())
10340     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10341            << DefaultedFuncs;
10342 
10343   if (!ConstexprSupported && NewFD->isConstexpr())
10344     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10345            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10346 
10347   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10348   const auto *NewType = cast<FunctionType>(NewQType);
10349   QualType NewReturnType = NewType->getReturnType();
10350 
10351   if (NewReturnType->isUndeducedType())
10352     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10353            << DeducedReturn;
10354 
10355   // Ensure the return type is identical.
10356   if (OldFD) {
10357     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10358     const auto *OldType = cast<FunctionType>(OldQType);
10359     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10360     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10361 
10362     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10363       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10364 
10365     QualType OldReturnType = OldType->getReturnType();
10366 
10367     if (OldReturnType != NewReturnType)
10368       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10369 
10370     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10371       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10372 
10373     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10374       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10375 
10376     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10377       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10378 
10379     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10380       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10381 
10382     if (CheckEquivalentExceptionSpec(
10383             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10384             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10385       return true;
10386   }
10387   return false;
10388 }
10389 
10390 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10391                                              const FunctionDecl *NewFD,
10392                                              bool CausesMV,
10393                                              MultiVersionKind MVType) {
10394   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10395     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10396     if (OldFD)
10397       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10398     return true;
10399   }
10400 
10401   bool IsCPUSpecificCPUDispatchMVType =
10402       MVType == MultiVersionKind::CPUDispatch ||
10403       MVType == MultiVersionKind::CPUSpecific;
10404 
10405   if (CausesMV && OldFD &&
10406       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10407     return true;
10408 
10409   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10410     return true;
10411 
10412   // Only allow transition to MultiVersion if it hasn't been used.
10413   if (OldFD && CausesMV && OldFD->isUsed(false))
10414     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10415 
10416   return S.areMultiversionVariantFunctionsCompatible(
10417       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10418       PartialDiagnosticAt(NewFD->getLocation(),
10419                           S.PDiag(diag::note_multiversioning_caused_here)),
10420       PartialDiagnosticAt(NewFD->getLocation(),
10421                           S.PDiag(diag::err_multiversion_doesnt_support)
10422                               << IsCPUSpecificCPUDispatchMVType),
10423       PartialDiagnosticAt(NewFD->getLocation(),
10424                           S.PDiag(diag::err_multiversion_diff)),
10425       /*TemplatesSupported=*/false,
10426       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10427       /*CLinkageMayDiffer=*/false);
10428 }
10429 
10430 /// Check the validity of a multiversion function declaration that is the
10431 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10432 ///
10433 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10434 ///
10435 /// Returns true if there was an error, false otherwise.
10436 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10437                                            MultiVersionKind MVType,
10438                                            const TargetAttr *TA) {
10439   assert(MVType != MultiVersionKind::None &&
10440          "Function lacks multiversion attribute");
10441 
10442   // Target only causes MV if it is default, otherwise this is a normal
10443   // function.
10444   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10445     return false;
10446 
10447   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10448     FD->setInvalidDecl();
10449     return true;
10450   }
10451 
10452   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10453     FD->setInvalidDecl();
10454     return true;
10455   }
10456 
10457   FD->setIsMultiVersion();
10458   return false;
10459 }
10460 
10461 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10462   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10463     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10464       return true;
10465   }
10466 
10467   return false;
10468 }
10469 
10470 static bool CheckTargetCausesMultiVersioning(
10471     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10472     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10473     LookupResult &Previous) {
10474   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10475   ParsedTargetAttr NewParsed = NewTA->parse();
10476   // Sort order doesn't matter, it just needs to be consistent.
10477   llvm::sort(NewParsed.Features);
10478 
10479   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10480   // to change, this is a simple redeclaration.
10481   if (!NewTA->isDefaultVersion() &&
10482       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10483     return false;
10484 
10485   // Otherwise, this decl causes MultiVersioning.
10486   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10487     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10488     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10489     NewFD->setInvalidDecl();
10490     return true;
10491   }
10492 
10493   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10494                                        MultiVersionKind::Target)) {
10495     NewFD->setInvalidDecl();
10496     return true;
10497   }
10498 
10499   if (CheckMultiVersionValue(S, NewFD)) {
10500     NewFD->setInvalidDecl();
10501     return true;
10502   }
10503 
10504   // If this is 'default', permit the forward declaration.
10505   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10506     Redeclaration = true;
10507     OldDecl = OldFD;
10508     OldFD->setIsMultiVersion();
10509     NewFD->setIsMultiVersion();
10510     return false;
10511   }
10512 
10513   if (CheckMultiVersionValue(S, OldFD)) {
10514     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10515     NewFD->setInvalidDecl();
10516     return true;
10517   }
10518 
10519   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10520 
10521   if (OldParsed == NewParsed) {
10522     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10523     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10524     NewFD->setInvalidDecl();
10525     return true;
10526   }
10527 
10528   for (const auto *FD : OldFD->redecls()) {
10529     const auto *CurTA = FD->getAttr<TargetAttr>();
10530     // We allow forward declarations before ANY multiversioning attributes, but
10531     // nothing after the fact.
10532     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10533         (!CurTA || CurTA->isInherited())) {
10534       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10535           << 0;
10536       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10537       NewFD->setInvalidDecl();
10538       return true;
10539     }
10540   }
10541 
10542   OldFD->setIsMultiVersion();
10543   NewFD->setIsMultiVersion();
10544   Redeclaration = false;
10545   MergeTypeWithPrevious = false;
10546   OldDecl = nullptr;
10547   Previous.clear();
10548   return false;
10549 }
10550 
10551 /// Check the validity of a new function declaration being added to an existing
10552 /// multiversioned declaration collection.
10553 static bool CheckMultiVersionAdditionalDecl(
10554     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10555     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10556     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10557     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10558     LookupResult &Previous) {
10559 
10560   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10561   // Disallow mixing of multiversioning types.
10562   if ((OldMVType == MultiVersionKind::Target &&
10563        NewMVType != MultiVersionKind::Target) ||
10564       (NewMVType == MultiVersionKind::Target &&
10565        OldMVType != MultiVersionKind::Target)) {
10566     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10567     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10568     NewFD->setInvalidDecl();
10569     return true;
10570   }
10571 
10572   ParsedTargetAttr NewParsed;
10573   if (NewTA) {
10574     NewParsed = NewTA->parse();
10575     llvm::sort(NewParsed.Features);
10576   }
10577 
10578   bool UseMemberUsingDeclRules =
10579       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10580 
10581   // Next, check ALL non-overloads to see if this is a redeclaration of a
10582   // previous member of the MultiVersion set.
10583   for (NamedDecl *ND : Previous) {
10584     FunctionDecl *CurFD = ND->getAsFunction();
10585     if (!CurFD)
10586       continue;
10587     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10588       continue;
10589 
10590     if (NewMVType == MultiVersionKind::Target) {
10591       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10592       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10593         NewFD->setIsMultiVersion();
10594         Redeclaration = true;
10595         OldDecl = ND;
10596         return false;
10597       }
10598 
10599       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10600       if (CurParsed == NewParsed) {
10601         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10602         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10603         NewFD->setInvalidDecl();
10604         return true;
10605       }
10606     } else {
10607       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10608       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10609       // Handle CPUDispatch/CPUSpecific versions.
10610       // Only 1 CPUDispatch function is allowed, this will make it go through
10611       // the redeclaration errors.
10612       if (NewMVType == MultiVersionKind::CPUDispatch &&
10613           CurFD->hasAttr<CPUDispatchAttr>()) {
10614         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10615             std::equal(
10616                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10617                 NewCPUDisp->cpus_begin(),
10618                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10619                   return Cur->getName() == New->getName();
10620                 })) {
10621           NewFD->setIsMultiVersion();
10622           Redeclaration = true;
10623           OldDecl = ND;
10624           return false;
10625         }
10626 
10627         // If the declarations don't match, this is an error condition.
10628         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10629         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10630         NewFD->setInvalidDecl();
10631         return true;
10632       }
10633       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10634 
10635         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10636             std::equal(
10637                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10638                 NewCPUSpec->cpus_begin(),
10639                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10640                   return Cur->getName() == New->getName();
10641                 })) {
10642           NewFD->setIsMultiVersion();
10643           Redeclaration = true;
10644           OldDecl = ND;
10645           return false;
10646         }
10647 
10648         // Only 1 version of CPUSpecific is allowed for each CPU.
10649         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10650           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10651             if (CurII == NewII) {
10652               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10653                   << NewII;
10654               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10655               NewFD->setInvalidDecl();
10656               return true;
10657             }
10658           }
10659         }
10660       }
10661       // If the two decls aren't the same MVType, there is no possible error
10662       // condition.
10663     }
10664   }
10665 
10666   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10667   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10668   // handled in the attribute adding step.
10669   if (NewMVType == MultiVersionKind::Target &&
10670       CheckMultiVersionValue(S, NewFD)) {
10671     NewFD->setInvalidDecl();
10672     return true;
10673   }
10674 
10675   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10676                                        !OldFD->isMultiVersion(), NewMVType)) {
10677     NewFD->setInvalidDecl();
10678     return true;
10679   }
10680 
10681   // Permit forward declarations in the case where these two are compatible.
10682   if (!OldFD->isMultiVersion()) {
10683     OldFD->setIsMultiVersion();
10684     NewFD->setIsMultiVersion();
10685     Redeclaration = true;
10686     OldDecl = OldFD;
10687     return false;
10688   }
10689 
10690   NewFD->setIsMultiVersion();
10691   Redeclaration = false;
10692   MergeTypeWithPrevious = false;
10693   OldDecl = nullptr;
10694   Previous.clear();
10695   return false;
10696 }
10697 
10698 
10699 /// Check the validity of a mulitversion function declaration.
10700 /// Also sets the multiversion'ness' of the function itself.
10701 ///
10702 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10703 ///
10704 /// Returns true if there was an error, false otherwise.
10705 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10706                                       bool &Redeclaration, NamedDecl *&OldDecl,
10707                                       bool &MergeTypeWithPrevious,
10708                                       LookupResult &Previous) {
10709   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10710   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10711   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10712 
10713   // Mixing Multiversioning types is prohibited.
10714   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10715       (NewCPUDisp && NewCPUSpec)) {
10716     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10717     NewFD->setInvalidDecl();
10718     return true;
10719   }
10720 
10721   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10722 
10723   // Main isn't allowed to become a multiversion function, however it IS
10724   // permitted to have 'main' be marked with the 'target' optimization hint.
10725   if (NewFD->isMain()) {
10726     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10727         MVType == MultiVersionKind::CPUDispatch ||
10728         MVType == MultiVersionKind::CPUSpecific) {
10729       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10730       NewFD->setInvalidDecl();
10731       return true;
10732     }
10733     return false;
10734   }
10735 
10736   if (!OldDecl || !OldDecl->getAsFunction() ||
10737       OldDecl->getDeclContext()->getRedeclContext() !=
10738           NewFD->getDeclContext()->getRedeclContext()) {
10739     // If there's no previous declaration, AND this isn't attempting to cause
10740     // multiversioning, this isn't an error condition.
10741     if (MVType == MultiVersionKind::None)
10742       return false;
10743     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10744   }
10745 
10746   FunctionDecl *OldFD = OldDecl->getAsFunction();
10747 
10748   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10749     return false;
10750 
10751   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10752     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10753         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10754     NewFD->setInvalidDecl();
10755     return true;
10756   }
10757 
10758   // Handle the target potentially causes multiversioning case.
10759   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10760     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10761                                             Redeclaration, OldDecl,
10762                                             MergeTypeWithPrevious, Previous);
10763 
10764   // At this point, we have a multiversion function decl (in OldFD) AND an
10765   // appropriate attribute in the current function decl.  Resolve that these are
10766   // still compatible with previous declarations.
10767   return CheckMultiVersionAdditionalDecl(
10768       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10769       OldDecl, MergeTypeWithPrevious, Previous);
10770 }
10771 
10772 /// Perform semantic checking of a new function declaration.
10773 ///
10774 /// Performs semantic analysis of the new function declaration
10775 /// NewFD. This routine performs all semantic checking that does not
10776 /// require the actual declarator involved in the declaration, and is
10777 /// used both for the declaration of functions as they are parsed
10778 /// (called via ActOnDeclarator) and for the declaration of functions
10779 /// that have been instantiated via C++ template instantiation (called
10780 /// via InstantiateDecl).
10781 ///
10782 /// \param IsMemberSpecialization whether this new function declaration is
10783 /// a member specialization (that replaces any definition provided by the
10784 /// previous declaration).
10785 ///
10786 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10787 ///
10788 /// \returns true if the function declaration is a redeclaration.
10789 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10790                                     LookupResult &Previous,
10791                                     bool IsMemberSpecialization) {
10792   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10793          "Variably modified return types are not handled here");
10794 
10795   // Determine whether the type of this function should be merged with
10796   // a previous visible declaration. This never happens for functions in C++,
10797   // and always happens in C if the previous declaration was visible.
10798   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10799                                !Previous.isShadowed();
10800 
10801   bool Redeclaration = false;
10802   NamedDecl *OldDecl = nullptr;
10803   bool MayNeedOverloadableChecks = false;
10804 
10805   // Merge or overload the declaration with an existing declaration of
10806   // the same name, if appropriate.
10807   if (!Previous.empty()) {
10808     // Determine whether NewFD is an overload of PrevDecl or
10809     // a declaration that requires merging. If it's an overload,
10810     // there's no more work to do here; we'll just add the new
10811     // function to the scope.
10812     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10813       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10814       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10815         Redeclaration = true;
10816         OldDecl = Candidate;
10817       }
10818     } else {
10819       MayNeedOverloadableChecks = true;
10820       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10821                             /*NewIsUsingDecl*/ false)) {
10822       case Ovl_Match:
10823         Redeclaration = true;
10824         break;
10825 
10826       case Ovl_NonFunction:
10827         Redeclaration = true;
10828         break;
10829 
10830       case Ovl_Overload:
10831         Redeclaration = false;
10832         break;
10833       }
10834     }
10835   }
10836 
10837   // Check for a previous extern "C" declaration with this name.
10838   if (!Redeclaration &&
10839       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10840     if (!Previous.empty()) {
10841       // This is an extern "C" declaration with the same name as a previous
10842       // declaration, and thus redeclares that entity...
10843       Redeclaration = true;
10844       OldDecl = Previous.getFoundDecl();
10845       MergeTypeWithPrevious = false;
10846 
10847       // ... except in the presence of __attribute__((overloadable)).
10848       if (OldDecl->hasAttr<OverloadableAttr>() ||
10849           NewFD->hasAttr<OverloadableAttr>()) {
10850         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10851           MayNeedOverloadableChecks = true;
10852           Redeclaration = false;
10853           OldDecl = nullptr;
10854         }
10855       }
10856     }
10857   }
10858 
10859   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10860                                 MergeTypeWithPrevious, Previous))
10861     return Redeclaration;
10862 
10863   // PPC MMA non-pointer types are not allowed as function return types.
10864   if (Context.getTargetInfo().getTriple().isPPC64() &&
10865       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10866     NewFD->setInvalidDecl();
10867   }
10868 
10869   // C++11 [dcl.constexpr]p8:
10870   //   A constexpr specifier for a non-static member function that is not
10871   //   a constructor declares that member function to be const.
10872   //
10873   // This needs to be delayed until we know whether this is an out-of-line
10874   // definition of a static member function.
10875   //
10876   // This rule is not present in C++1y, so we produce a backwards
10877   // compatibility warning whenever it happens in C++11.
10878   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10879   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10880       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10881       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10882     CXXMethodDecl *OldMD = nullptr;
10883     if (OldDecl)
10884       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10885     if (!OldMD || !OldMD->isStatic()) {
10886       const FunctionProtoType *FPT =
10887         MD->getType()->castAs<FunctionProtoType>();
10888       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10889       EPI.TypeQuals.addConst();
10890       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10891                                           FPT->getParamTypes(), EPI));
10892 
10893       // Warn that we did this, if we're not performing template instantiation.
10894       // In that case, we'll have warned already when the template was defined.
10895       if (!inTemplateInstantiation()) {
10896         SourceLocation AddConstLoc;
10897         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10898                 .IgnoreParens().getAs<FunctionTypeLoc>())
10899           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10900 
10901         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10902           << FixItHint::CreateInsertion(AddConstLoc, " const");
10903       }
10904     }
10905   }
10906 
10907   if (Redeclaration) {
10908     // NewFD and OldDecl represent declarations that need to be
10909     // merged.
10910     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10911       NewFD->setInvalidDecl();
10912       return Redeclaration;
10913     }
10914 
10915     Previous.clear();
10916     Previous.addDecl(OldDecl);
10917 
10918     if (FunctionTemplateDecl *OldTemplateDecl =
10919             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10920       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10921       FunctionTemplateDecl *NewTemplateDecl
10922         = NewFD->getDescribedFunctionTemplate();
10923       assert(NewTemplateDecl && "Template/non-template mismatch");
10924 
10925       // The call to MergeFunctionDecl above may have created some state in
10926       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10927       // can add it as a redeclaration.
10928       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10929 
10930       NewFD->setPreviousDeclaration(OldFD);
10931       if (NewFD->isCXXClassMember()) {
10932         NewFD->setAccess(OldTemplateDecl->getAccess());
10933         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10934       }
10935 
10936       // If this is an explicit specialization of a member that is a function
10937       // template, mark it as a member specialization.
10938       if (IsMemberSpecialization &&
10939           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10940         NewTemplateDecl->setMemberSpecialization();
10941         assert(OldTemplateDecl->isMemberSpecialization());
10942         // Explicit specializations of a member template do not inherit deleted
10943         // status from the parent member template that they are specializing.
10944         if (OldFD->isDeleted()) {
10945           // FIXME: This assert will not hold in the presence of modules.
10946           assert(OldFD->getCanonicalDecl() == OldFD);
10947           // FIXME: We need an update record for this AST mutation.
10948           OldFD->setDeletedAsWritten(false);
10949         }
10950       }
10951 
10952     } else {
10953       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10954         auto *OldFD = cast<FunctionDecl>(OldDecl);
10955         // This needs to happen first so that 'inline' propagates.
10956         NewFD->setPreviousDeclaration(OldFD);
10957         if (NewFD->isCXXClassMember())
10958           NewFD->setAccess(OldFD->getAccess());
10959       }
10960     }
10961   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10962              !NewFD->getAttr<OverloadableAttr>()) {
10963     assert((Previous.empty() ||
10964             llvm::any_of(Previous,
10965                          [](const NamedDecl *ND) {
10966                            return ND->hasAttr<OverloadableAttr>();
10967                          })) &&
10968            "Non-redecls shouldn't happen without overloadable present");
10969 
10970     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10971       const auto *FD = dyn_cast<FunctionDecl>(ND);
10972       return FD && !FD->hasAttr<OverloadableAttr>();
10973     });
10974 
10975     if (OtherUnmarkedIter != Previous.end()) {
10976       Diag(NewFD->getLocation(),
10977            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10978       Diag((*OtherUnmarkedIter)->getLocation(),
10979            diag::note_attribute_overloadable_prev_overload)
10980           << false;
10981 
10982       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10983     }
10984   }
10985 
10986   if (LangOpts.OpenMP)
10987     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10988 
10989   // Semantic checking for this function declaration (in isolation).
10990 
10991   if (getLangOpts().CPlusPlus) {
10992     // C++-specific checks.
10993     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10994       CheckConstructor(Constructor);
10995     } else if (CXXDestructorDecl *Destructor =
10996                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10997       CXXRecordDecl *Record = Destructor->getParent();
10998       QualType ClassType = Context.getTypeDeclType(Record);
10999 
11000       // FIXME: Shouldn't we be able to perform this check even when the class
11001       // type is dependent? Both gcc and edg can handle that.
11002       if (!ClassType->isDependentType()) {
11003         DeclarationName Name
11004           = Context.DeclarationNames.getCXXDestructorName(
11005                                         Context.getCanonicalType(ClassType));
11006         if (NewFD->getDeclName() != Name) {
11007           Diag(NewFD->getLocation(), diag::err_destructor_name);
11008           NewFD->setInvalidDecl();
11009           return Redeclaration;
11010         }
11011       }
11012     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11013       if (auto *TD = Guide->getDescribedFunctionTemplate())
11014         CheckDeductionGuideTemplate(TD);
11015 
11016       // A deduction guide is not on the list of entities that can be
11017       // explicitly specialized.
11018       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11019         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11020             << /*explicit specialization*/ 1;
11021     }
11022 
11023     // Find any virtual functions that this function overrides.
11024     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11025       if (!Method->isFunctionTemplateSpecialization() &&
11026           !Method->getDescribedFunctionTemplate() &&
11027           Method->isCanonicalDecl()) {
11028         AddOverriddenMethods(Method->getParent(), Method);
11029       }
11030       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11031         // C++2a [class.virtual]p6
11032         // A virtual method shall not have a requires-clause.
11033         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11034              diag::err_constrained_virtual_method);
11035 
11036       if (Method->isStatic())
11037         checkThisInStaticMemberFunctionType(Method);
11038     }
11039 
11040     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11041       ActOnConversionDeclarator(Conversion);
11042 
11043     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11044     if (NewFD->isOverloadedOperator() &&
11045         CheckOverloadedOperatorDeclaration(NewFD)) {
11046       NewFD->setInvalidDecl();
11047       return Redeclaration;
11048     }
11049 
11050     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11051     if (NewFD->getLiteralIdentifier() &&
11052         CheckLiteralOperatorDeclaration(NewFD)) {
11053       NewFD->setInvalidDecl();
11054       return Redeclaration;
11055     }
11056 
11057     // In C++, check default arguments now that we have merged decls. Unless
11058     // the lexical context is the class, because in this case this is done
11059     // during delayed parsing anyway.
11060     if (!CurContext->isRecord())
11061       CheckCXXDefaultArguments(NewFD);
11062 
11063     // If this function is declared as being extern "C", then check to see if
11064     // the function returns a UDT (class, struct, or union type) that is not C
11065     // compatible, and if it does, warn the user.
11066     // But, issue any diagnostic on the first declaration only.
11067     if (Previous.empty() && NewFD->isExternC()) {
11068       QualType R = NewFD->getReturnType();
11069       if (R->isIncompleteType() && !R->isVoidType())
11070         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11071             << NewFD << R;
11072       else if (!R.isPODType(Context) && !R->isVoidType() &&
11073                !R->isObjCObjectPointerType())
11074         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11075     }
11076 
11077     // C++1z [dcl.fct]p6:
11078     //   [...] whether the function has a non-throwing exception-specification
11079     //   [is] part of the function type
11080     //
11081     // This results in an ABI break between C++14 and C++17 for functions whose
11082     // declared type includes an exception-specification in a parameter or
11083     // return type. (Exception specifications on the function itself are OK in
11084     // most cases, and exception specifications are not permitted in most other
11085     // contexts where they could make it into a mangling.)
11086     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11087       auto HasNoexcept = [&](QualType T) -> bool {
11088         // Strip off declarator chunks that could be between us and a function
11089         // type. We don't need to look far, exception specifications are very
11090         // restricted prior to C++17.
11091         if (auto *RT = T->getAs<ReferenceType>())
11092           T = RT->getPointeeType();
11093         else if (T->isAnyPointerType())
11094           T = T->getPointeeType();
11095         else if (auto *MPT = T->getAs<MemberPointerType>())
11096           T = MPT->getPointeeType();
11097         if (auto *FPT = T->getAs<FunctionProtoType>())
11098           if (FPT->isNothrow())
11099             return true;
11100         return false;
11101       };
11102 
11103       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11104       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11105       for (QualType T : FPT->param_types())
11106         AnyNoexcept |= HasNoexcept(T);
11107       if (AnyNoexcept)
11108         Diag(NewFD->getLocation(),
11109              diag::warn_cxx17_compat_exception_spec_in_signature)
11110             << NewFD;
11111     }
11112 
11113     if (!Redeclaration && LangOpts.CUDA)
11114       checkCUDATargetOverload(NewFD, Previous);
11115   }
11116   return Redeclaration;
11117 }
11118 
11119 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11120   // C++11 [basic.start.main]p3:
11121   //   A program that [...] declares main to be inline, static or
11122   //   constexpr is ill-formed.
11123   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11124   //   appear in a declaration of main.
11125   // static main is not an error under C99, but we should warn about it.
11126   // We accept _Noreturn main as an extension.
11127   if (FD->getStorageClass() == SC_Static)
11128     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11129          ? diag::err_static_main : diag::warn_static_main)
11130       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11131   if (FD->isInlineSpecified())
11132     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11133       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11134   if (DS.isNoreturnSpecified()) {
11135     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11136     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11137     Diag(NoreturnLoc, diag::ext_noreturn_main);
11138     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11139       << FixItHint::CreateRemoval(NoreturnRange);
11140   }
11141   if (FD->isConstexpr()) {
11142     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11143         << FD->isConsteval()
11144         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11145     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11146   }
11147 
11148   if (getLangOpts().OpenCL) {
11149     Diag(FD->getLocation(), diag::err_opencl_no_main)
11150         << FD->hasAttr<OpenCLKernelAttr>();
11151     FD->setInvalidDecl();
11152     return;
11153   }
11154 
11155   QualType T = FD->getType();
11156   assert(T->isFunctionType() && "function decl is not of function type");
11157   const FunctionType* FT = T->castAs<FunctionType>();
11158 
11159   // Set default calling convention for main()
11160   if (FT->getCallConv() != CC_C) {
11161     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11162     FD->setType(QualType(FT, 0));
11163     T = Context.getCanonicalType(FD->getType());
11164   }
11165 
11166   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11167     // In C with GNU extensions we allow main() to have non-integer return
11168     // type, but we should warn about the extension, and we disable the
11169     // implicit-return-zero rule.
11170 
11171     // GCC in C mode accepts qualified 'int'.
11172     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11173       FD->setHasImplicitReturnZero(true);
11174     else {
11175       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11176       SourceRange RTRange = FD->getReturnTypeSourceRange();
11177       if (RTRange.isValid())
11178         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11179             << FixItHint::CreateReplacement(RTRange, "int");
11180     }
11181   } else {
11182     // In C and C++, main magically returns 0 if you fall off the end;
11183     // set the flag which tells us that.
11184     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11185 
11186     // All the standards say that main() should return 'int'.
11187     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11188       FD->setHasImplicitReturnZero(true);
11189     else {
11190       // Otherwise, this is just a flat-out error.
11191       SourceRange RTRange = FD->getReturnTypeSourceRange();
11192       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11193           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11194                                 : FixItHint());
11195       FD->setInvalidDecl(true);
11196     }
11197   }
11198 
11199   // Treat protoless main() as nullary.
11200   if (isa<FunctionNoProtoType>(FT)) return;
11201 
11202   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11203   unsigned nparams = FTP->getNumParams();
11204   assert(FD->getNumParams() == nparams);
11205 
11206   bool HasExtraParameters = (nparams > 3);
11207 
11208   if (FTP->isVariadic()) {
11209     Diag(FD->getLocation(), diag::ext_variadic_main);
11210     // FIXME: if we had information about the location of the ellipsis, we
11211     // could add a FixIt hint to remove it as a parameter.
11212   }
11213 
11214   // Darwin passes an undocumented fourth argument of type char**.  If
11215   // other platforms start sprouting these, the logic below will start
11216   // getting shifty.
11217   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11218     HasExtraParameters = false;
11219 
11220   if (HasExtraParameters) {
11221     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11222     FD->setInvalidDecl(true);
11223     nparams = 3;
11224   }
11225 
11226   // FIXME: a lot of the following diagnostics would be improved
11227   // if we had some location information about types.
11228 
11229   QualType CharPP =
11230     Context.getPointerType(Context.getPointerType(Context.CharTy));
11231   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11232 
11233   for (unsigned i = 0; i < nparams; ++i) {
11234     QualType AT = FTP->getParamType(i);
11235 
11236     bool mismatch = true;
11237 
11238     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11239       mismatch = false;
11240     else if (Expected[i] == CharPP) {
11241       // As an extension, the following forms are okay:
11242       //   char const **
11243       //   char const * const *
11244       //   char * const *
11245 
11246       QualifierCollector qs;
11247       const PointerType* PT;
11248       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11249           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11250           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11251                               Context.CharTy)) {
11252         qs.removeConst();
11253         mismatch = !qs.empty();
11254       }
11255     }
11256 
11257     if (mismatch) {
11258       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11259       // TODO: suggest replacing given type with expected type
11260       FD->setInvalidDecl(true);
11261     }
11262   }
11263 
11264   if (nparams == 1 && !FD->isInvalidDecl()) {
11265     Diag(FD->getLocation(), diag::warn_main_one_arg);
11266   }
11267 
11268   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11269     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11270     FD->setInvalidDecl();
11271   }
11272 }
11273 
11274 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11275 
11276   // Default calling convention for main and wmain is __cdecl
11277   if (FD->getName() == "main" || FD->getName() == "wmain")
11278     return false;
11279 
11280   // Default calling convention for MinGW is __cdecl
11281   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11282   if (T.isWindowsGNUEnvironment())
11283     return false;
11284 
11285   // Default calling convention for WinMain, wWinMain and DllMain
11286   // is __stdcall on 32 bit Windows
11287   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11288     return true;
11289 
11290   return false;
11291 }
11292 
11293 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11294   QualType T = FD->getType();
11295   assert(T->isFunctionType() && "function decl is not of function type");
11296   const FunctionType *FT = T->castAs<FunctionType>();
11297 
11298   // Set an implicit return of 'zero' if the function can return some integral,
11299   // enumeration, pointer or nullptr type.
11300   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11301       FT->getReturnType()->isAnyPointerType() ||
11302       FT->getReturnType()->isNullPtrType())
11303     // DllMain is exempt because a return value of zero means it failed.
11304     if (FD->getName() != "DllMain")
11305       FD->setHasImplicitReturnZero(true);
11306 
11307   // Explicity specified calling conventions are applied to MSVC entry points
11308   if (!hasExplicitCallingConv(T)) {
11309     if (isDefaultStdCall(FD, *this)) {
11310       if (FT->getCallConv() != CC_X86StdCall) {
11311         FT = Context.adjustFunctionType(
11312             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11313         FD->setType(QualType(FT, 0));
11314       }
11315     } else if (FT->getCallConv() != CC_C) {
11316       FT = Context.adjustFunctionType(FT,
11317                                       FT->getExtInfo().withCallingConv(CC_C));
11318       FD->setType(QualType(FT, 0));
11319     }
11320   }
11321 
11322   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11323     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11324     FD->setInvalidDecl();
11325   }
11326 }
11327 
11328 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11329   // FIXME: Need strict checking.  In C89, we need to check for
11330   // any assignment, increment, decrement, function-calls, or
11331   // commas outside of a sizeof.  In C99, it's the same list,
11332   // except that the aforementioned are allowed in unevaluated
11333   // expressions.  Everything else falls under the
11334   // "may accept other forms of constant expressions" exception.
11335   //
11336   // Regular C++ code will not end up here (exceptions: language extensions,
11337   // OpenCL C++ etc), so the constant expression rules there don't matter.
11338   if (Init->isValueDependent()) {
11339     assert(Init->containsErrors() &&
11340            "Dependent code should only occur in error-recovery path.");
11341     return true;
11342   }
11343   const Expr *Culprit;
11344   if (Init->isConstantInitializer(Context, false, &Culprit))
11345     return false;
11346   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11347     << Culprit->getSourceRange();
11348   return true;
11349 }
11350 
11351 namespace {
11352   // Visits an initialization expression to see if OrigDecl is evaluated in
11353   // its own initialization and throws a warning if it does.
11354   class SelfReferenceChecker
11355       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11356     Sema &S;
11357     Decl *OrigDecl;
11358     bool isRecordType;
11359     bool isPODType;
11360     bool isReferenceType;
11361 
11362     bool isInitList;
11363     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11364 
11365   public:
11366     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11367 
11368     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11369                                                     S(S), OrigDecl(OrigDecl) {
11370       isPODType = false;
11371       isRecordType = false;
11372       isReferenceType = false;
11373       isInitList = false;
11374       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11375         isPODType = VD->getType().isPODType(S.Context);
11376         isRecordType = VD->getType()->isRecordType();
11377         isReferenceType = VD->getType()->isReferenceType();
11378       }
11379     }
11380 
11381     // For most expressions, just call the visitor.  For initializer lists,
11382     // track the index of the field being initialized since fields are
11383     // initialized in order allowing use of previously initialized fields.
11384     void CheckExpr(Expr *E) {
11385       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11386       if (!InitList) {
11387         Visit(E);
11388         return;
11389       }
11390 
11391       // Track and increment the index here.
11392       isInitList = true;
11393       InitFieldIndex.push_back(0);
11394       for (auto Child : InitList->children()) {
11395         CheckExpr(cast<Expr>(Child));
11396         ++InitFieldIndex.back();
11397       }
11398       InitFieldIndex.pop_back();
11399     }
11400 
11401     // Returns true if MemberExpr is checked and no further checking is needed.
11402     // Returns false if additional checking is required.
11403     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11404       llvm::SmallVector<FieldDecl*, 4> Fields;
11405       Expr *Base = E;
11406       bool ReferenceField = false;
11407 
11408       // Get the field members used.
11409       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11410         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11411         if (!FD)
11412           return false;
11413         Fields.push_back(FD);
11414         if (FD->getType()->isReferenceType())
11415           ReferenceField = true;
11416         Base = ME->getBase()->IgnoreParenImpCasts();
11417       }
11418 
11419       // Keep checking only if the base Decl is the same.
11420       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11421       if (!DRE || DRE->getDecl() != OrigDecl)
11422         return false;
11423 
11424       // A reference field can be bound to an unininitialized field.
11425       if (CheckReference && !ReferenceField)
11426         return true;
11427 
11428       // Convert FieldDecls to their index number.
11429       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11430       for (const FieldDecl *I : llvm::reverse(Fields))
11431         UsedFieldIndex.push_back(I->getFieldIndex());
11432 
11433       // See if a warning is needed by checking the first difference in index
11434       // numbers.  If field being used has index less than the field being
11435       // initialized, then the use is safe.
11436       for (auto UsedIter = UsedFieldIndex.begin(),
11437                 UsedEnd = UsedFieldIndex.end(),
11438                 OrigIter = InitFieldIndex.begin(),
11439                 OrigEnd = InitFieldIndex.end();
11440            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11441         if (*UsedIter < *OrigIter)
11442           return true;
11443         if (*UsedIter > *OrigIter)
11444           break;
11445       }
11446 
11447       // TODO: Add a different warning which will print the field names.
11448       HandleDeclRefExpr(DRE);
11449       return true;
11450     }
11451 
11452     // For most expressions, the cast is directly above the DeclRefExpr.
11453     // For conditional operators, the cast can be outside the conditional
11454     // operator if both expressions are DeclRefExpr's.
11455     void HandleValue(Expr *E) {
11456       E = E->IgnoreParens();
11457       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11458         HandleDeclRefExpr(DRE);
11459         return;
11460       }
11461 
11462       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11463         Visit(CO->getCond());
11464         HandleValue(CO->getTrueExpr());
11465         HandleValue(CO->getFalseExpr());
11466         return;
11467       }
11468 
11469       if (BinaryConditionalOperator *BCO =
11470               dyn_cast<BinaryConditionalOperator>(E)) {
11471         Visit(BCO->getCond());
11472         HandleValue(BCO->getFalseExpr());
11473         return;
11474       }
11475 
11476       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11477         HandleValue(OVE->getSourceExpr());
11478         return;
11479       }
11480 
11481       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11482         if (BO->getOpcode() == BO_Comma) {
11483           Visit(BO->getLHS());
11484           HandleValue(BO->getRHS());
11485           return;
11486         }
11487       }
11488 
11489       if (isa<MemberExpr>(E)) {
11490         if (isInitList) {
11491           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11492                                       false /*CheckReference*/))
11493             return;
11494         }
11495 
11496         Expr *Base = E->IgnoreParenImpCasts();
11497         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11498           // Check for static member variables and don't warn on them.
11499           if (!isa<FieldDecl>(ME->getMemberDecl()))
11500             return;
11501           Base = ME->getBase()->IgnoreParenImpCasts();
11502         }
11503         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11504           HandleDeclRefExpr(DRE);
11505         return;
11506       }
11507 
11508       Visit(E);
11509     }
11510 
11511     // Reference types not handled in HandleValue are handled here since all
11512     // uses of references are bad, not just r-value uses.
11513     void VisitDeclRefExpr(DeclRefExpr *E) {
11514       if (isReferenceType)
11515         HandleDeclRefExpr(E);
11516     }
11517 
11518     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11519       if (E->getCastKind() == CK_LValueToRValue) {
11520         HandleValue(E->getSubExpr());
11521         return;
11522       }
11523 
11524       Inherited::VisitImplicitCastExpr(E);
11525     }
11526 
11527     void VisitMemberExpr(MemberExpr *E) {
11528       if (isInitList) {
11529         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11530           return;
11531       }
11532 
11533       // Don't warn on arrays since they can be treated as pointers.
11534       if (E->getType()->canDecayToPointerType()) return;
11535 
11536       // Warn when a non-static method call is followed by non-static member
11537       // field accesses, which is followed by a DeclRefExpr.
11538       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11539       bool Warn = (MD && !MD->isStatic());
11540       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11541       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11542         if (!isa<FieldDecl>(ME->getMemberDecl()))
11543           Warn = false;
11544         Base = ME->getBase()->IgnoreParenImpCasts();
11545       }
11546 
11547       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11548         if (Warn)
11549           HandleDeclRefExpr(DRE);
11550         return;
11551       }
11552 
11553       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11554       // Visit that expression.
11555       Visit(Base);
11556     }
11557 
11558     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11559       Expr *Callee = E->getCallee();
11560 
11561       if (isa<UnresolvedLookupExpr>(Callee))
11562         return Inherited::VisitCXXOperatorCallExpr(E);
11563 
11564       Visit(Callee);
11565       for (auto Arg: E->arguments())
11566         HandleValue(Arg->IgnoreParenImpCasts());
11567     }
11568 
11569     void VisitUnaryOperator(UnaryOperator *E) {
11570       // For POD record types, addresses of its own members are well-defined.
11571       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11572           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11573         if (!isPODType)
11574           HandleValue(E->getSubExpr());
11575         return;
11576       }
11577 
11578       if (E->isIncrementDecrementOp()) {
11579         HandleValue(E->getSubExpr());
11580         return;
11581       }
11582 
11583       Inherited::VisitUnaryOperator(E);
11584     }
11585 
11586     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11587 
11588     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11589       if (E->getConstructor()->isCopyConstructor()) {
11590         Expr *ArgExpr = E->getArg(0);
11591         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11592           if (ILE->getNumInits() == 1)
11593             ArgExpr = ILE->getInit(0);
11594         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11595           if (ICE->getCastKind() == CK_NoOp)
11596             ArgExpr = ICE->getSubExpr();
11597         HandleValue(ArgExpr);
11598         return;
11599       }
11600       Inherited::VisitCXXConstructExpr(E);
11601     }
11602 
11603     void VisitCallExpr(CallExpr *E) {
11604       // Treat std::move as a use.
11605       if (E->isCallToStdMove()) {
11606         HandleValue(E->getArg(0));
11607         return;
11608       }
11609 
11610       Inherited::VisitCallExpr(E);
11611     }
11612 
11613     void VisitBinaryOperator(BinaryOperator *E) {
11614       if (E->isCompoundAssignmentOp()) {
11615         HandleValue(E->getLHS());
11616         Visit(E->getRHS());
11617         return;
11618       }
11619 
11620       Inherited::VisitBinaryOperator(E);
11621     }
11622 
11623     // A custom visitor for BinaryConditionalOperator is needed because the
11624     // regular visitor would check the condition and true expression separately
11625     // but both point to the same place giving duplicate diagnostics.
11626     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11627       Visit(E->getCond());
11628       Visit(E->getFalseExpr());
11629     }
11630 
11631     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11632       Decl* ReferenceDecl = DRE->getDecl();
11633       if (OrigDecl != ReferenceDecl) return;
11634       unsigned diag;
11635       if (isReferenceType) {
11636         diag = diag::warn_uninit_self_reference_in_reference_init;
11637       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11638         diag = diag::warn_static_self_reference_in_init;
11639       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11640                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11641                  DRE->getDecl()->getType()->isRecordType()) {
11642         diag = diag::warn_uninit_self_reference_in_init;
11643       } else {
11644         // Local variables will be handled by the CFG analysis.
11645         return;
11646       }
11647 
11648       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11649                             S.PDiag(diag)
11650                                 << DRE->getDecl() << OrigDecl->getLocation()
11651                                 << DRE->getSourceRange());
11652     }
11653   };
11654 
11655   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11656   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11657                                  bool DirectInit) {
11658     // Parameters arguments are occassionially constructed with itself,
11659     // for instance, in recursive functions.  Skip them.
11660     if (isa<ParmVarDecl>(OrigDecl))
11661       return;
11662 
11663     E = E->IgnoreParens();
11664 
11665     // Skip checking T a = a where T is not a record or reference type.
11666     // Doing so is a way to silence uninitialized warnings.
11667     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11668       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11669         if (ICE->getCastKind() == CK_LValueToRValue)
11670           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11671             if (DRE->getDecl() == OrigDecl)
11672               return;
11673 
11674     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11675   }
11676 } // end anonymous namespace
11677 
11678 namespace {
11679   // Simple wrapper to add the name of a variable or (if no variable is
11680   // available) a DeclarationName into a diagnostic.
11681   struct VarDeclOrName {
11682     VarDecl *VDecl;
11683     DeclarationName Name;
11684 
11685     friend const Sema::SemaDiagnosticBuilder &
11686     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11687       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11688     }
11689   };
11690 } // end anonymous namespace
11691 
11692 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11693                                             DeclarationName Name, QualType Type,
11694                                             TypeSourceInfo *TSI,
11695                                             SourceRange Range, bool DirectInit,
11696                                             Expr *Init) {
11697   bool IsInitCapture = !VDecl;
11698   assert((!VDecl || !VDecl->isInitCapture()) &&
11699          "init captures are expected to be deduced prior to initialization");
11700 
11701   VarDeclOrName VN{VDecl, Name};
11702 
11703   DeducedType *Deduced = Type->getContainedDeducedType();
11704   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11705 
11706   // C++11 [dcl.spec.auto]p3
11707   if (!Init) {
11708     assert(VDecl && "no init for init capture deduction?");
11709 
11710     // Except for class argument deduction, and then for an initializing
11711     // declaration only, i.e. no static at class scope or extern.
11712     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11713         VDecl->hasExternalStorage() ||
11714         VDecl->isStaticDataMember()) {
11715       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11716         << VDecl->getDeclName() << Type;
11717       return QualType();
11718     }
11719   }
11720 
11721   ArrayRef<Expr*> DeduceInits;
11722   if (Init)
11723     DeduceInits = Init;
11724 
11725   if (DirectInit) {
11726     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11727       DeduceInits = PL->exprs();
11728   }
11729 
11730   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11731     assert(VDecl && "non-auto type for init capture deduction?");
11732     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11733     InitializationKind Kind = InitializationKind::CreateForInit(
11734         VDecl->getLocation(), DirectInit, Init);
11735     // FIXME: Initialization should not be taking a mutable list of inits.
11736     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11737     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11738                                                        InitsCopy);
11739   }
11740 
11741   if (DirectInit) {
11742     if (auto *IL = dyn_cast<InitListExpr>(Init))
11743       DeduceInits = IL->inits();
11744   }
11745 
11746   // Deduction only works if we have exactly one source expression.
11747   if (DeduceInits.empty()) {
11748     // It isn't possible to write this directly, but it is possible to
11749     // end up in this situation with "auto x(some_pack...);"
11750     Diag(Init->getBeginLoc(), IsInitCapture
11751                                   ? diag::err_init_capture_no_expression
11752                                   : diag::err_auto_var_init_no_expression)
11753         << VN << Type << Range;
11754     return QualType();
11755   }
11756 
11757   if (DeduceInits.size() > 1) {
11758     Diag(DeduceInits[1]->getBeginLoc(),
11759          IsInitCapture ? diag::err_init_capture_multiple_expressions
11760                        : diag::err_auto_var_init_multiple_expressions)
11761         << VN << Type << Range;
11762     return QualType();
11763   }
11764 
11765   Expr *DeduceInit = DeduceInits[0];
11766   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11767     Diag(Init->getBeginLoc(), IsInitCapture
11768                                   ? diag::err_init_capture_paren_braces
11769                                   : diag::err_auto_var_init_paren_braces)
11770         << isa<InitListExpr>(Init) << VN << Type << Range;
11771     return QualType();
11772   }
11773 
11774   // Expressions default to 'id' when we're in a debugger.
11775   bool DefaultedAnyToId = false;
11776   if (getLangOpts().DebuggerCastResultToId &&
11777       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11778     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11779     if (Result.isInvalid()) {
11780       return QualType();
11781     }
11782     Init = Result.get();
11783     DefaultedAnyToId = true;
11784   }
11785 
11786   // C++ [dcl.decomp]p1:
11787   //   If the assignment-expression [...] has array type A and no ref-qualifier
11788   //   is present, e has type cv A
11789   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11790       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11791       DeduceInit->getType()->isConstantArrayType())
11792     return Context.getQualifiedType(DeduceInit->getType(),
11793                                     Type.getQualifiers());
11794 
11795   QualType DeducedType;
11796   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11797     if (!IsInitCapture)
11798       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11799     else if (isa<InitListExpr>(Init))
11800       Diag(Range.getBegin(),
11801            diag::err_init_capture_deduction_failure_from_init_list)
11802           << VN
11803           << (DeduceInit->getType().isNull() ? TSI->getType()
11804                                              : DeduceInit->getType())
11805           << DeduceInit->getSourceRange();
11806     else
11807       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11808           << VN << TSI->getType()
11809           << (DeduceInit->getType().isNull() ? TSI->getType()
11810                                              : DeduceInit->getType())
11811           << DeduceInit->getSourceRange();
11812   }
11813 
11814   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11815   // 'id' instead of a specific object type prevents most of our usual
11816   // checks.
11817   // We only want to warn outside of template instantiations, though:
11818   // inside a template, the 'id' could have come from a parameter.
11819   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11820       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11821     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11822     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11823   }
11824 
11825   return DeducedType;
11826 }
11827 
11828 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11829                                          Expr *Init) {
11830   assert(!Init || !Init->containsErrors());
11831   QualType DeducedType = deduceVarTypeFromInitializer(
11832       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11833       VDecl->getSourceRange(), DirectInit, Init);
11834   if (DeducedType.isNull()) {
11835     VDecl->setInvalidDecl();
11836     return true;
11837   }
11838 
11839   VDecl->setType(DeducedType);
11840   assert(VDecl->isLinkageValid());
11841 
11842   // In ARC, infer lifetime.
11843   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11844     VDecl->setInvalidDecl();
11845 
11846   if (getLangOpts().OpenCL)
11847     deduceOpenCLAddressSpace(VDecl);
11848 
11849   // If this is a redeclaration, check that the type we just deduced matches
11850   // the previously declared type.
11851   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11852     // We never need to merge the type, because we cannot form an incomplete
11853     // array of auto, nor deduce such a type.
11854     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11855   }
11856 
11857   // Check the deduced type is valid for a variable declaration.
11858   CheckVariableDeclarationType(VDecl);
11859   return VDecl->isInvalidDecl();
11860 }
11861 
11862 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11863                                               SourceLocation Loc) {
11864   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11865     Init = EWC->getSubExpr();
11866 
11867   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11868     Init = CE->getSubExpr();
11869 
11870   QualType InitType = Init->getType();
11871   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11872           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11873          "shouldn't be called if type doesn't have a non-trivial C struct");
11874   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11875     for (auto I : ILE->inits()) {
11876       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11877           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11878         continue;
11879       SourceLocation SL = I->getExprLoc();
11880       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11881     }
11882     return;
11883   }
11884 
11885   if (isa<ImplicitValueInitExpr>(Init)) {
11886     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11887       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11888                             NTCUK_Init);
11889   } else {
11890     // Assume all other explicit initializers involving copying some existing
11891     // object.
11892     // TODO: ignore any explicit initializers where we can guarantee
11893     // copy-elision.
11894     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11895       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11896   }
11897 }
11898 
11899 namespace {
11900 
11901 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11902   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11903   // in the source code or implicitly by the compiler if it is in a union
11904   // defined in a system header and has non-trivial ObjC ownership
11905   // qualifications. We don't want those fields to participate in determining
11906   // whether the containing union is non-trivial.
11907   return FD->hasAttr<UnavailableAttr>();
11908 }
11909 
11910 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11911     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11912                                     void> {
11913   using Super =
11914       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11915                                     void>;
11916 
11917   DiagNonTrivalCUnionDefaultInitializeVisitor(
11918       QualType OrigTy, SourceLocation OrigLoc,
11919       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11920       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11921 
11922   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11923                      const FieldDecl *FD, bool InNonTrivialUnion) {
11924     if (const auto *AT = S.Context.getAsArrayType(QT))
11925       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11926                                      InNonTrivialUnion);
11927     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11928   }
11929 
11930   void visitARCStrong(QualType QT, const FieldDecl *FD,
11931                       bool InNonTrivialUnion) {
11932     if (InNonTrivialUnion)
11933       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11934           << 1 << 0 << QT << FD->getName();
11935   }
11936 
11937   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11938     if (InNonTrivialUnion)
11939       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11940           << 1 << 0 << QT << FD->getName();
11941   }
11942 
11943   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11944     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11945     if (RD->isUnion()) {
11946       if (OrigLoc.isValid()) {
11947         bool IsUnion = false;
11948         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11949           IsUnion = OrigRD->isUnion();
11950         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11951             << 0 << OrigTy << IsUnion << UseContext;
11952         // Reset OrigLoc so that this diagnostic is emitted only once.
11953         OrigLoc = SourceLocation();
11954       }
11955       InNonTrivialUnion = true;
11956     }
11957 
11958     if (InNonTrivialUnion)
11959       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11960           << 0 << 0 << QT.getUnqualifiedType() << "";
11961 
11962     for (const FieldDecl *FD : RD->fields())
11963       if (!shouldIgnoreForRecordTriviality(FD))
11964         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11965   }
11966 
11967   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11968 
11969   // The non-trivial C union type or the struct/union type that contains a
11970   // non-trivial C union.
11971   QualType OrigTy;
11972   SourceLocation OrigLoc;
11973   Sema::NonTrivialCUnionContext UseContext;
11974   Sema &S;
11975 };
11976 
11977 struct DiagNonTrivalCUnionDestructedTypeVisitor
11978     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11979   using Super =
11980       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11981 
11982   DiagNonTrivalCUnionDestructedTypeVisitor(
11983       QualType OrigTy, SourceLocation OrigLoc,
11984       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11985       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11986 
11987   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11988                      const FieldDecl *FD, bool InNonTrivialUnion) {
11989     if (const auto *AT = S.Context.getAsArrayType(QT))
11990       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11991                                      InNonTrivialUnion);
11992     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11993   }
11994 
11995   void visitARCStrong(QualType QT, const FieldDecl *FD,
11996                       bool InNonTrivialUnion) {
11997     if (InNonTrivialUnion)
11998       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11999           << 1 << 1 << QT << FD->getName();
12000   }
12001 
12002   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12003     if (InNonTrivialUnion)
12004       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12005           << 1 << 1 << QT << FD->getName();
12006   }
12007 
12008   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12009     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12010     if (RD->isUnion()) {
12011       if (OrigLoc.isValid()) {
12012         bool IsUnion = false;
12013         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12014           IsUnion = OrigRD->isUnion();
12015         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12016             << 1 << OrigTy << IsUnion << UseContext;
12017         // Reset OrigLoc so that this diagnostic is emitted only once.
12018         OrigLoc = SourceLocation();
12019       }
12020       InNonTrivialUnion = true;
12021     }
12022 
12023     if (InNonTrivialUnion)
12024       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12025           << 0 << 1 << QT.getUnqualifiedType() << "";
12026 
12027     for (const FieldDecl *FD : RD->fields())
12028       if (!shouldIgnoreForRecordTriviality(FD))
12029         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12030   }
12031 
12032   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12033   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12034                           bool InNonTrivialUnion) {}
12035 
12036   // The non-trivial C union type or the struct/union type that contains a
12037   // non-trivial C union.
12038   QualType OrigTy;
12039   SourceLocation OrigLoc;
12040   Sema::NonTrivialCUnionContext UseContext;
12041   Sema &S;
12042 };
12043 
12044 struct DiagNonTrivalCUnionCopyVisitor
12045     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12046   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12047 
12048   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12049                                  Sema::NonTrivialCUnionContext UseContext,
12050                                  Sema &S)
12051       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12052 
12053   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12054                      const FieldDecl *FD, bool InNonTrivialUnion) {
12055     if (const auto *AT = S.Context.getAsArrayType(QT))
12056       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12057                                      InNonTrivialUnion);
12058     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12059   }
12060 
12061   void visitARCStrong(QualType QT, const FieldDecl *FD,
12062                       bool InNonTrivialUnion) {
12063     if (InNonTrivialUnion)
12064       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12065           << 1 << 2 << QT << FD->getName();
12066   }
12067 
12068   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12069     if (InNonTrivialUnion)
12070       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12071           << 1 << 2 << QT << FD->getName();
12072   }
12073 
12074   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12075     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12076     if (RD->isUnion()) {
12077       if (OrigLoc.isValid()) {
12078         bool IsUnion = false;
12079         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12080           IsUnion = OrigRD->isUnion();
12081         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12082             << 2 << OrigTy << IsUnion << UseContext;
12083         // Reset OrigLoc so that this diagnostic is emitted only once.
12084         OrigLoc = SourceLocation();
12085       }
12086       InNonTrivialUnion = true;
12087     }
12088 
12089     if (InNonTrivialUnion)
12090       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12091           << 0 << 2 << QT.getUnqualifiedType() << "";
12092 
12093     for (const FieldDecl *FD : RD->fields())
12094       if (!shouldIgnoreForRecordTriviality(FD))
12095         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12096   }
12097 
12098   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12099                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12100   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12101   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12102                             bool InNonTrivialUnion) {}
12103 
12104   // The non-trivial C union type or the struct/union type that contains a
12105   // non-trivial C union.
12106   QualType OrigTy;
12107   SourceLocation OrigLoc;
12108   Sema::NonTrivialCUnionContext UseContext;
12109   Sema &S;
12110 };
12111 
12112 } // namespace
12113 
12114 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12115                                  NonTrivialCUnionContext UseContext,
12116                                  unsigned NonTrivialKind) {
12117   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12118           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12119           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12120          "shouldn't be called if type doesn't have a non-trivial C union");
12121 
12122   if ((NonTrivialKind & NTCUK_Init) &&
12123       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12124     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12125         .visit(QT, nullptr, false);
12126   if ((NonTrivialKind & NTCUK_Destruct) &&
12127       QT.hasNonTrivialToPrimitiveDestructCUnion())
12128     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12129         .visit(QT, nullptr, false);
12130   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12131     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12132         .visit(QT, nullptr, false);
12133 }
12134 
12135 /// AddInitializerToDecl - Adds the initializer Init to the
12136 /// declaration dcl. If DirectInit is true, this is C++ direct
12137 /// initialization rather than copy initialization.
12138 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12139   // If there is no declaration, there was an error parsing it.  Just ignore
12140   // the initializer.
12141   if (!RealDecl || RealDecl->isInvalidDecl()) {
12142     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12143     return;
12144   }
12145 
12146   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12147     // Pure-specifiers are handled in ActOnPureSpecifier.
12148     Diag(Method->getLocation(), diag::err_member_function_initialization)
12149       << Method->getDeclName() << Init->getSourceRange();
12150     Method->setInvalidDecl();
12151     return;
12152   }
12153 
12154   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12155   if (!VDecl) {
12156     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12157     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12158     RealDecl->setInvalidDecl();
12159     return;
12160   }
12161 
12162   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12163   if (VDecl->getType()->isUndeducedType()) {
12164     // Attempt typo correction early so that the type of the init expression can
12165     // be deduced based on the chosen correction if the original init contains a
12166     // TypoExpr.
12167     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12168     if (!Res.isUsable()) {
12169       // There are unresolved typos in Init, just drop them.
12170       // FIXME: improve the recovery strategy to preserve the Init.
12171       RealDecl->setInvalidDecl();
12172       return;
12173     }
12174     if (Res.get()->containsErrors()) {
12175       // Invalidate the decl as we don't know the type for recovery-expr yet.
12176       RealDecl->setInvalidDecl();
12177       VDecl->setInit(Res.get());
12178       return;
12179     }
12180     Init = Res.get();
12181 
12182     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12183       return;
12184   }
12185 
12186   // dllimport cannot be used on variable definitions.
12187   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12188     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12189     VDecl->setInvalidDecl();
12190     return;
12191   }
12192 
12193   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12194     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12195     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12196     VDecl->setInvalidDecl();
12197     return;
12198   }
12199 
12200   if (!VDecl->getType()->isDependentType()) {
12201     // A definition must end up with a complete type, which means it must be
12202     // complete with the restriction that an array type might be completed by
12203     // the initializer; note that later code assumes this restriction.
12204     QualType BaseDeclType = VDecl->getType();
12205     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12206       BaseDeclType = Array->getElementType();
12207     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12208                             diag::err_typecheck_decl_incomplete_type)) {
12209       RealDecl->setInvalidDecl();
12210       return;
12211     }
12212 
12213     // The variable can not have an abstract class type.
12214     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12215                                diag::err_abstract_type_in_decl,
12216                                AbstractVariableType))
12217       VDecl->setInvalidDecl();
12218   }
12219 
12220   // If adding the initializer will turn this declaration into a definition,
12221   // and we already have a definition for this variable, diagnose or otherwise
12222   // handle the situation.
12223   VarDecl *Def;
12224   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12225       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12226       !VDecl->isThisDeclarationADemotedDefinition() &&
12227       checkVarDeclRedefinition(Def, VDecl))
12228     return;
12229 
12230   if (getLangOpts().CPlusPlus) {
12231     // C++ [class.static.data]p4
12232     //   If a static data member is of const integral or const
12233     //   enumeration type, its declaration in the class definition can
12234     //   specify a constant-initializer which shall be an integral
12235     //   constant expression (5.19). In that case, the member can appear
12236     //   in integral constant expressions. The member shall still be
12237     //   defined in a namespace scope if it is used in the program and the
12238     //   namespace scope definition shall not contain an initializer.
12239     //
12240     // We already performed a redefinition check above, but for static
12241     // data members we also need to check whether there was an in-class
12242     // declaration with an initializer.
12243     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12244       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12245           << VDecl->getDeclName();
12246       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12247            diag::note_previous_initializer)
12248           << 0;
12249       return;
12250     }
12251 
12252     if (VDecl->hasLocalStorage())
12253       setFunctionHasBranchProtectedScope();
12254 
12255     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12256       VDecl->setInvalidDecl();
12257       return;
12258     }
12259   }
12260 
12261   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12262   // a kernel function cannot be initialized."
12263   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12264     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12265     VDecl->setInvalidDecl();
12266     return;
12267   }
12268 
12269   // The LoaderUninitialized attribute acts as a definition (of undef).
12270   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12271     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12272     VDecl->setInvalidDecl();
12273     return;
12274   }
12275 
12276   // Get the decls type and save a reference for later, since
12277   // CheckInitializerTypes may change it.
12278   QualType DclT = VDecl->getType(), SavT = DclT;
12279 
12280   // Expressions default to 'id' when we're in a debugger
12281   // and we are assigning it to a variable of Objective-C pointer type.
12282   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12283       Init->getType() == Context.UnknownAnyTy) {
12284     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12285     if (Result.isInvalid()) {
12286       VDecl->setInvalidDecl();
12287       return;
12288     }
12289     Init = Result.get();
12290   }
12291 
12292   // Perform the initialization.
12293   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12294   if (!VDecl->isInvalidDecl()) {
12295     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12296     InitializationKind Kind = InitializationKind::CreateForInit(
12297         VDecl->getLocation(), DirectInit, Init);
12298 
12299     MultiExprArg Args = Init;
12300     if (CXXDirectInit)
12301       Args = MultiExprArg(CXXDirectInit->getExprs(),
12302                           CXXDirectInit->getNumExprs());
12303 
12304     // Try to correct any TypoExprs in the initialization arguments.
12305     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12306       ExprResult Res = CorrectDelayedTyposInExpr(
12307           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12308           [this, Entity, Kind](Expr *E) {
12309             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12310             return Init.Failed() ? ExprError() : E;
12311           });
12312       if (Res.isInvalid()) {
12313         VDecl->setInvalidDecl();
12314       } else if (Res.get() != Args[Idx]) {
12315         Args[Idx] = Res.get();
12316       }
12317     }
12318     if (VDecl->isInvalidDecl())
12319       return;
12320 
12321     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12322                                    /*TopLevelOfInitList=*/false,
12323                                    /*TreatUnavailableAsInvalid=*/false);
12324     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12325     if (Result.isInvalid()) {
12326       // If the provied initializer fails to initialize the var decl,
12327       // we attach a recovery expr for better recovery.
12328       auto RecoveryExpr =
12329           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12330       if (RecoveryExpr.get())
12331         VDecl->setInit(RecoveryExpr.get());
12332       return;
12333     }
12334 
12335     Init = Result.getAs<Expr>();
12336   }
12337 
12338   // Check for self-references within variable initializers.
12339   // Variables declared within a function/method body (except for references)
12340   // are handled by a dataflow analysis.
12341   // This is undefined behavior in C++, but valid in C.
12342   if (getLangOpts().CPlusPlus) {
12343     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12344         VDecl->getType()->isReferenceType()) {
12345       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12346     }
12347   }
12348 
12349   // If the type changed, it means we had an incomplete type that was
12350   // completed by the initializer. For example:
12351   //   int ary[] = { 1, 3, 5 };
12352   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12353   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12354     VDecl->setType(DclT);
12355 
12356   if (!VDecl->isInvalidDecl()) {
12357     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12358 
12359     if (VDecl->hasAttr<BlocksAttr>())
12360       checkRetainCycles(VDecl, Init);
12361 
12362     // It is safe to assign a weak reference into a strong variable.
12363     // Although this code can still have problems:
12364     //   id x = self.weakProp;
12365     //   id y = self.weakProp;
12366     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12367     // paths through the function. This should be revisited if
12368     // -Wrepeated-use-of-weak is made flow-sensitive.
12369     if (FunctionScopeInfo *FSI = getCurFunction())
12370       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12371            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12372           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12373                            Init->getBeginLoc()))
12374         FSI->markSafeWeakUse(Init);
12375   }
12376 
12377   // The initialization is usually a full-expression.
12378   //
12379   // FIXME: If this is a braced initialization of an aggregate, it is not
12380   // an expression, and each individual field initializer is a separate
12381   // full-expression. For instance, in:
12382   //
12383   //   struct Temp { ~Temp(); };
12384   //   struct S { S(Temp); };
12385   //   struct T { S a, b; } t = { Temp(), Temp() }
12386   //
12387   // we should destroy the first Temp before constructing the second.
12388   ExprResult Result =
12389       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12390                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12391   if (Result.isInvalid()) {
12392     VDecl->setInvalidDecl();
12393     return;
12394   }
12395   Init = Result.get();
12396 
12397   // Attach the initializer to the decl.
12398   VDecl->setInit(Init);
12399 
12400   if (VDecl->isLocalVarDecl()) {
12401     // Don't check the initializer if the declaration is malformed.
12402     if (VDecl->isInvalidDecl()) {
12403       // do nothing
12404 
12405     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12406     // This is true even in C++ for OpenCL.
12407     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12408       CheckForConstantInitializer(Init, DclT);
12409 
12410     // Otherwise, C++ does not restrict the initializer.
12411     } else if (getLangOpts().CPlusPlus) {
12412       // do nothing
12413 
12414     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12415     // static storage duration shall be constant expressions or string literals.
12416     } else if (VDecl->getStorageClass() == SC_Static) {
12417       CheckForConstantInitializer(Init, DclT);
12418 
12419     // C89 is stricter than C99 for aggregate initializers.
12420     // C89 6.5.7p3: All the expressions [...] in an initializer list
12421     // for an object that has aggregate or union type shall be
12422     // constant expressions.
12423     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12424                isa<InitListExpr>(Init)) {
12425       const Expr *Culprit;
12426       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12427         Diag(Culprit->getExprLoc(),
12428              diag::ext_aggregate_init_not_constant)
12429           << Culprit->getSourceRange();
12430       }
12431     }
12432 
12433     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12434       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12435         if (VDecl->hasLocalStorage())
12436           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12437   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12438              VDecl->getLexicalDeclContext()->isRecord()) {
12439     // This is an in-class initialization for a static data member, e.g.,
12440     //
12441     // struct S {
12442     //   static const int value = 17;
12443     // };
12444 
12445     // C++ [class.mem]p4:
12446     //   A member-declarator can contain a constant-initializer only
12447     //   if it declares a static member (9.4) of const integral or
12448     //   const enumeration type, see 9.4.2.
12449     //
12450     // C++11 [class.static.data]p3:
12451     //   If a non-volatile non-inline const static data member is of integral
12452     //   or enumeration type, its declaration in the class definition can
12453     //   specify a brace-or-equal-initializer in which every initializer-clause
12454     //   that is an assignment-expression is a constant expression. A static
12455     //   data member of literal type can be declared in the class definition
12456     //   with the constexpr specifier; if so, its declaration shall specify a
12457     //   brace-or-equal-initializer in which every initializer-clause that is
12458     //   an assignment-expression is a constant expression.
12459 
12460     // Do nothing on dependent types.
12461     if (DclT->isDependentType()) {
12462 
12463     // Allow any 'static constexpr' members, whether or not they are of literal
12464     // type. We separately check that every constexpr variable is of literal
12465     // type.
12466     } else if (VDecl->isConstexpr()) {
12467 
12468     // Require constness.
12469     } else if (!DclT.isConstQualified()) {
12470       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12471         << Init->getSourceRange();
12472       VDecl->setInvalidDecl();
12473 
12474     // We allow integer constant expressions in all cases.
12475     } else if (DclT->isIntegralOrEnumerationType()) {
12476       // Check whether the expression is a constant expression.
12477       SourceLocation Loc;
12478       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12479         // In C++11, a non-constexpr const static data member with an
12480         // in-class initializer cannot be volatile.
12481         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12482       else if (Init->isValueDependent())
12483         ; // Nothing to check.
12484       else if (Init->isIntegerConstantExpr(Context, &Loc))
12485         ; // Ok, it's an ICE!
12486       else if (Init->getType()->isScopedEnumeralType() &&
12487                Init->isCXX11ConstantExpr(Context))
12488         ; // Ok, it is a scoped-enum constant expression.
12489       else if (Init->isEvaluatable(Context)) {
12490         // If we can constant fold the initializer through heroics, accept it,
12491         // but report this as a use of an extension for -pedantic.
12492         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12493           << Init->getSourceRange();
12494       } else {
12495         // Otherwise, this is some crazy unknown case.  Report the issue at the
12496         // location provided by the isIntegerConstantExpr failed check.
12497         Diag(Loc, diag::err_in_class_initializer_non_constant)
12498           << Init->getSourceRange();
12499         VDecl->setInvalidDecl();
12500       }
12501 
12502     // We allow foldable floating-point constants as an extension.
12503     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12504       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12505       // it anyway and provide a fixit to add the 'constexpr'.
12506       if (getLangOpts().CPlusPlus11) {
12507         Diag(VDecl->getLocation(),
12508              diag::ext_in_class_initializer_float_type_cxx11)
12509             << DclT << Init->getSourceRange();
12510         Diag(VDecl->getBeginLoc(),
12511              diag::note_in_class_initializer_float_type_cxx11)
12512             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12513       } else {
12514         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12515           << DclT << Init->getSourceRange();
12516 
12517         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12518           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12519             << Init->getSourceRange();
12520           VDecl->setInvalidDecl();
12521         }
12522       }
12523 
12524     // Suggest adding 'constexpr' in C++11 for literal types.
12525     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12526       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12527           << DclT << Init->getSourceRange()
12528           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12529       VDecl->setConstexpr(true);
12530 
12531     } else {
12532       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12533         << DclT << Init->getSourceRange();
12534       VDecl->setInvalidDecl();
12535     }
12536   } else if (VDecl->isFileVarDecl()) {
12537     // In C, extern is typically used to avoid tentative definitions when
12538     // declaring variables in headers, but adding an intializer makes it a
12539     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12540     // In C++, extern is often used to give implictly static const variables
12541     // external linkage, so don't warn in that case. If selectany is present,
12542     // this might be header code intended for C and C++ inclusion, so apply the
12543     // C++ rules.
12544     if (VDecl->getStorageClass() == SC_Extern &&
12545         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12546          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12547         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12548         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12549       Diag(VDecl->getLocation(), diag::warn_extern_init);
12550 
12551     // In Microsoft C++ mode, a const variable defined in namespace scope has
12552     // external linkage by default if the variable is declared with
12553     // __declspec(dllexport).
12554     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12555         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12556         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12557       VDecl->setStorageClass(SC_Extern);
12558 
12559     // C99 6.7.8p4. All file scoped initializers need to be constant.
12560     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12561       CheckForConstantInitializer(Init, DclT);
12562   }
12563 
12564   QualType InitType = Init->getType();
12565   if (!InitType.isNull() &&
12566       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12567        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12568     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12569 
12570   // We will represent direct-initialization similarly to copy-initialization:
12571   //    int x(1);  -as-> int x = 1;
12572   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12573   //
12574   // Clients that want to distinguish between the two forms, can check for
12575   // direct initializer using VarDecl::getInitStyle().
12576   // A major benefit is that clients that don't particularly care about which
12577   // exactly form was it (like the CodeGen) can handle both cases without
12578   // special case code.
12579 
12580   // C++ 8.5p11:
12581   // The form of initialization (using parentheses or '=') is generally
12582   // insignificant, but does matter when the entity being initialized has a
12583   // class type.
12584   if (CXXDirectInit) {
12585     assert(DirectInit && "Call-style initializer must be direct init.");
12586     VDecl->setInitStyle(VarDecl::CallInit);
12587   } else if (DirectInit) {
12588     // This must be list-initialization. No other way is direct-initialization.
12589     VDecl->setInitStyle(VarDecl::ListInit);
12590   }
12591 
12592   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12593     DeclsToCheckForDeferredDiags.insert(VDecl);
12594   CheckCompleteVariableDeclaration(VDecl);
12595 }
12596 
12597 /// ActOnInitializerError - Given that there was an error parsing an
12598 /// initializer for the given declaration, try to return to some form
12599 /// of sanity.
12600 void Sema::ActOnInitializerError(Decl *D) {
12601   // Our main concern here is re-establishing invariants like "a
12602   // variable's type is either dependent or complete".
12603   if (!D || D->isInvalidDecl()) return;
12604 
12605   VarDecl *VD = dyn_cast<VarDecl>(D);
12606   if (!VD) return;
12607 
12608   // Bindings are not usable if we can't make sense of the initializer.
12609   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12610     for (auto *BD : DD->bindings())
12611       BD->setInvalidDecl();
12612 
12613   // Auto types are meaningless if we can't make sense of the initializer.
12614   if (VD->getType()->isUndeducedType()) {
12615     D->setInvalidDecl();
12616     return;
12617   }
12618 
12619   QualType Ty = VD->getType();
12620   if (Ty->isDependentType()) return;
12621 
12622   // Require a complete type.
12623   if (RequireCompleteType(VD->getLocation(),
12624                           Context.getBaseElementType(Ty),
12625                           diag::err_typecheck_decl_incomplete_type)) {
12626     VD->setInvalidDecl();
12627     return;
12628   }
12629 
12630   // Require a non-abstract type.
12631   if (RequireNonAbstractType(VD->getLocation(), Ty,
12632                              diag::err_abstract_type_in_decl,
12633                              AbstractVariableType)) {
12634     VD->setInvalidDecl();
12635     return;
12636   }
12637 
12638   // Don't bother complaining about constructors or destructors,
12639   // though.
12640 }
12641 
12642 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12643   // If there is no declaration, there was an error parsing it. Just ignore it.
12644   if (!RealDecl)
12645     return;
12646 
12647   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12648     QualType Type = Var->getType();
12649 
12650     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12651     if (isa<DecompositionDecl>(RealDecl)) {
12652       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12653       Var->setInvalidDecl();
12654       return;
12655     }
12656 
12657     if (Type->isUndeducedType() &&
12658         DeduceVariableDeclarationType(Var, false, nullptr))
12659       return;
12660 
12661     // C++11 [class.static.data]p3: A static data member can be declared with
12662     // the constexpr specifier; if so, its declaration shall specify
12663     // a brace-or-equal-initializer.
12664     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12665     // the definition of a variable [...] or the declaration of a static data
12666     // member.
12667     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12668         !Var->isThisDeclarationADemotedDefinition()) {
12669       if (Var->isStaticDataMember()) {
12670         // C++1z removes the relevant rule; the in-class declaration is always
12671         // a definition there.
12672         if (!getLangOpts().CPlusPlus17 &&
12673             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12674           Diag(Var->getLocation(),
12675                diag::err_constexpr_static_mem_var_requires_init)
12676               << Var;
12677           Var->setInvalidDecl();
12678           return;
12679         }
12680       } else {
12681         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12682         Var->setInvalidDecl();
12683         return;
12684       }
12685     }
12686 
12687     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12688     // be initialized.
12689     if (!Var->isInvalidDecl() &&
12690         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12691         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12692       bool HasConstExprDefaultConstructor = false;
12693       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12694         for (auto *Ctor : RD->ctors()) {
12695           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12696               Ctor->getMethodQualifiers().getAddressSpace() ==
12697                   LangAS::opencl_constant) {
12698             HasConstExprDefaultConstructor = true;
12699           }
12700         }
12701       }
12702       if (!HasConstExprDefaultConstructor) {
12703         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12704         Var->setInvalidDecl();
12705         return;
12706       }
12707     }
12708 
12709     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12710       if (Var->getStorageClass() == SC_Extern) {
12711         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12712             << Var;
12713         Var->setInvalidDecl();
12714         return;
12715       }
12716       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12717                               diag::err_typecheck_decl_incomplete_type)) {
12718         Var->setInvalidDecl();
12719         return;
12720       }
12721       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12722         if (!RD->hasTrivialDefaultConstructor()) {
12723           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12724           Var->setInvalidDecl();
12725           return;
12726         }
12727       }
12728       // The declaration is unitialized, no need for further checks.
12729       return;
12730     }
12731 
12732     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12733     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12734         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12735       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12736                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12737 
12738 
12739     switch (DefKind) {
12740     case VarDecl::Definition:
12741       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12742         break;
12743 
12744       // We have an out-of-line definition of a static data member
12745       // that has an in-class initializer, so we type-check this like
12746       // a declaration.
12747       //
12748       LLVM_FALLTHROUGH;
12749 
12750     case VarDecl::DeclarationOnly:
12751       // It's only a declaration.
12752 
12753       // Block scope. C99 6.7p7: If an identifier for an object is
12754       // declared with no linkage (C99 6.2.2p6), the type for the
12755       // object shall be complete.
12756       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12757           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12758           RequireCompleteType(Var->getLocation(), Type,
12759                               diag::err_typecheck_decl_incomplete_type))
12760         Var->setInvalidDecl();
12761 
12762       // Make sure that the type is not abstract.
12763       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12764           RequireNonAbstractType(Var->getLocation(), Type,
12765                                  diag::err_abstract_type_in_decl,
12766                                  AbstractVariableType))
12767         Var->setInvalidDecl();
12768       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12769           Var->getStorageClass() == SC_PrivateExtern) {
12770         Diag(Var->getLocation(), diag::warn_private_extern);
12771         Diag(Var->getLocation(), diag::note_private_extern);
12772       }
12773 
12774       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12775           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12776         ExternalDeclarations.push_back(Var);
12777 
12778       return;
12779 
12780     case VarDecl::TentativeDefinition:
12781       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12782       // object that has file scope without an initializer, and without a
12783       // storage-class specifier or with the storage-class specifier "static",
12784       // constitutes a tentative definition. Note: A tentative definition with
12785       // external linkage is valid (C99 6.2.2p5).
12786       if (!Var->isInvalidDecl()) {
12787         if (const IncompleteArrayType *ArrayT
12788                                     = Context.getAsIncompleteArrayType(Type)) {
12789           if (RequireCompleteSizedType(
12790                   Var->getLocation(), ArrayT->getElementType(),
12791                   diag::err_array_incomplete_or_sizeless_type))
12792             Var->setInvalidDecl();
12793         } else if (Var->getStorageClass() == SC_Static) {
12794           // C99 6.9.2p3: If the declaration of an identifier for an object is
12795           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12796           // declared type shall not be an incomplete type.
12797           // NOTE: code such as the following
12798           //     static struct s;
12799           //     struct s { int a; };
12800           // is accepted by gcc. Hence here we issue a warning instead of
12801           // an error and we do not invalidate the static declaration.
12802           // NOTE: to avoid multiple warnings, only check the first declaration.
12803           if (Var->isFirstDecl())
12804             RequireCompleteType(Var->getLocation(), Type,
12805                                 diag::ext_typecheck_decl_incomplete_type);
12806         }
12807       }
12808 
12809       // Record the tentative definition; we're done.
12810       if (!Var->isInvalidDecl())
12811         TentativeDefinitions.push_back(Var);
12812       return;
12813     }
12814 
12815     // Provide a specific diagnostic for uninitialized variable
12816     // definitions with incomplete array type.
12817     if (Type->isIncompleteArrayType()) {
12818       Diag(Var->getLocation(),
12819            diag::err_typecheck_incomplete_array_needs_initializer);
12820       Var->setInvalidDecl();
12821       return;
12822     }
12823 
12824     // Provide a specific diagnostic for uninitialized variable
12825     // definitions with reference type.
12826     if (Type->isReferenceType()) {
12827       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12828           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12829       Var->setInvalidDecl();
12830       return;
12831     }
12832 
12833     // Do not attempt to type-check the default initializer for a
12834     // variable with dependent type.
12835     if (Type->isDependentType())
12836       return;
12837 
12838     if (Var->isInvalidDecl())
12839       return;
12840 
12841     if (!Var->hasAttr<AliasAttr>()) {
12842       if (RequireCompleteType(Var->getLocation(),
12843                               Context.getBaseElementType(Type),
12844                               diag::err_typecheck_decl_incomplete_type)) {
12845         Var->setInvalidDecl();
12846         return;
12847       }
12848     } else {
12849       return;
12850     }
12851 
12852     // The variable can not have an abstract class type.
12853     if (RequireNonAbstractType(Var->getLocation(), Type,
12854                                diag::err_abstract_type_in_decl,
12855                                AbstractVariableType)) {
12856       Var->setInvalidDecl();
12857       return;
12858     }
12859 
12860     // Check for jumps past the implicit initializer.  C++0x
12861     // clarifies that this applies to a "variable with automatic
12862     // storage duration", not a "local variable".
12863     // C++11 [stmt.dcl]p3
12864     //   A program that jumps from a point where a variable with automatic
12865     //   storage duration is not in scope to a point where it is in scope is
12866     //   ill-formed unless the variable has scalar type, class type with a
12867     //   trivial default constructor and a trivial destructor, a cv-qualified
12868     //   version of one of these types, or an array of one of the preceding
12869     //   types and is declared without an initializer.
12870     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12871       if (const RecordType *Record
12872             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12873         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12874         // Mark the function (if we're in one) for further checking even if the
12875         // looser rules of C++11 do not require such checks, so that we can
12876         // diagnose incompatibilities with C++98.
12877         if (!CXXRecord->isPOD())
12878           setFunctionHasBranchProtectedScope();
12879       }
12880     }
12881     // In OpenCL, we can't initialize objects in the __local address space,
12882     // even implicitly, so don't synthesize an implicit initializer.
12883     if (getLangOpts().OpenCL &&
12884         Var->getType().getAddressSpace() == LangAS::opencl_local)
12885       return;
12886     // C++03 [dcl.init]p9:
12887     //   If no initializer is specified for an object, and the
12888     //   object is of (possibly cv-qualified) non-POD class type (or
12889     //   array thereof), the object shall be default-initialized; if
12890     //   the object is of const-qualified type, the underlying class
12891     //   type shall have a user-declared default
12892     //   constructor. Otherwise, if no initializer is specified for
12893     //   a non- static object, the object and its subobjects, if
12894     //   any, have an indeterminate initial value); if the object
12895     //   or any of its subobjects are of const-qualified type, the
12896     //   program is ill-formed.
12897     // C++0x [dcl.init]p11:
12898     //   If no initializer is specified for an object, the object is
12899     //   default-initialized; [...].
12900     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12901     InitializationKind Kind
12902       = InitializationKind::CreateDefault(Var->getLocation());
12903 
12904     InitializationSequence InitSeq(*this, Entity, Kind, None);
12905     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12906 
12907     if (Init.get()) {
12908       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12909       // This is important for template substitution.
12910       Var->setInitStyle(VarDecl::CallInit);
12911     } else if (Init.isInvalid()) {
12912       // If default-init fails, attach a recovery-expr initializer to track
12913       // that initialization was attempted and failed.
12914       auto RecoveryExpr =
12915           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12916       if (RecoveryExpr.get())
12917         Var->setInit(RecoveryExpr.get());
12918     }
12919 
12920     CheckCompleteVariableDeclaration(Var);
12921   }
12922 }
12923 
12924 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12925   // If there is no declaration, there was an error parsing it. Ignore it.
12926   if (!D)
12927     return;
12928 
12929   VarDecl *VD = dyn_cast<VarDecl>(D);
12930   if (!VD) {
12931     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12932     D->setInvalidDecl();
12933     return;
12934   }
12935 
12936   VD->setCXXForRangeDecl(true);
12937 
12938   // for-range-declaration cannot be given a storage class specifier.
12939   int Error = -1;
12940   switch (VD->getStorageClass()) {
12941   case SC_None:
12942     break;
12943   case SC_Extern:
12944     Error = 0;
12945     break;
12946   case SC_Static:
12947     Error = 1;
12948     break;
12949   case SC_PrivateExtern:
12950     Error = 2;
12951     break;
12952   case SC_Auto:
12953     Error = 3;
12954     break;
12955   case SC_Register:
12956     Error = 4;
12957     break;
12958   }
12959 
12960   // for-range-declaration cannot be given a storage class specifier con't.
12961   switch (VD->getTSCSpec()) {
12962   case TSCS_thread_local:
12963     Error = 6;
12964     break;
12965   case TSCS___thread:
12966   case TSCS__Thread_local:
12967   case TSCS_unspecified:
12968     break;
12969   }
12970 
12971   if (Error != -1) {
12972     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12973         << VD << Error;
12974     D->setInvalidDecl();
12975   }
12976 }
12977 
12978 StmtResult
12979 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12980                                  IdentifierInfo *Ident,
12981                                  ParsedAttributes &Attrs,
12982                                  SourceLocation AttrEnd) {
12983   // C++1y [stmt.iter]p1:
12984   //   A range-based for statement of the form
12985   //      for ( for-range-identifier : for-range-initializer ) statement
12986   //   is equivalent to
12987   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12988   DeclSpec DS(Attrs.getPool().getFactory());
12989 
12990   const char *PrevSpec;
12991   unsigned DiagID;
12992   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12993                      getPrintingPolicy());
12994 
12995   Declarator D(DS, DeclaratorContext::ForInit);
12996   D.SetIdentifier(Ident, IdentLoc);
12997   D.takeAttributes(Attrs, AttrEnd);
12998 
12999   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13000                 IdentLoc);
13001   Decl *Var = ActOnDeclarator(S, D);
13002   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13003   FinalizeDeclaration(Var);
13004   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13005                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13006 }
13007 
13008 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13009   if (var->isInvalidDecl()) return;
13010 
13011   MaybeAddCUDAConstantAttr(var);
13012 
13013   if (getLangOpts().OpenCL) {
13014     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13015     // initialiser
13016     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13017         !var->hasInit()) {
13018       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13019           << 1 /*Init*/;
13020       var->setInvalidDecl();
13021       return;
13022     }
13023   }
13024 
13025   // In Objective-C, don't allow jumps past the implicit initialization of a
13026   // local retaining variable.
13027   if (getLangOpts().ObjC &&
13028       var->hasLocalStorage()) {
13029     switch (var->getType().getObjCLifetime()) {
13030     case Qualifiers::OCL_None:
13031     case Qualifiers::OCL_ExplicitNone:
13032     case Qualifiers::OCL_Autoreleasing:
13033       break;
13034 
13035     case Qualifiers::OCL_Weak:
13036     case Qualifiers::OCL_Strong:
13037       setFunctionHasBranchProtectedScope();
13038       break;
13039     }
13040   }
13041 
13042   if (var->hasLocalStorage() &&
13043       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13044     setFunctionHasBranchProtectedScope();
13045 
13046   // Warn about externally-visible variables being defined without a
13047   // prior declaration.  We only want to do this for global
13048   // declarations, but we also specifically need to avoid doing it for
13049   // class members because the linkage of an anonymous class can
13050   // change if it's later given a typedef name.
13051   if (var->isThisDeclarationADefinition() &&
13052       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13053       var->isExternallyVisible() && var->hasLinkage() &&
13054       !var->isInline() && !var->getDescribedVarTemplate() &&
13055       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13056       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13057       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13058                                   var->getLocation())) {
13059     // Find a previous declaration that's not a definition.
13060     VarDecl *prev = var->getPreviousDecl();
13061     while (prev && prev->isThisDeclarationADefinition())
13062       prev = prev->getPreviousDecl();
13063 
13064     if (!prev) {
13065       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13066       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13067           << /* variable */ 0;
13068     }
13069   }
13070 
13071   // Cache the result of checking for constant initialization.
13072   Optional<bool> CacheHasConstInit;
13073   const Expr *CacheCulprit = nullptr;
13074   auto checkConstInit = [&]() mutable {
13075     if (!CacheHasConstInit)
13076       CacheHasConstInit = var->getInit()->isConstantInitializer(
13077             Context, var->getType()->isReferenceType(), &CacheCulprit);
13078     return *CacheHasConstInit;
13079   };
13080 
13081   if (var->getTLSKind() == VarDecl::TLS_Static) {
13082     if (var->getType().isDestructedType()) {
13083       // GNU C++98 edits for __thread, [basic.start.term]p3:
13084       //   The type of an object with thread storage duration shall not
13085       //   have a non-trivial destructor.
13086       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13087       if (getLangOpts().CPlusPlus11)
13088         Diag(var->getLocation(), diag::note_use_thread_local);
13089     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13090       if (!checkConstInit()) {
13091         // GNU C++98 edits for __thread, [basic.start.init]p4:
13092         //   An object of thread storage duration shall not require dynamic
13093         //   initialization.
13094         // FIXME: Need strict checking here.
13095         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13096           << CacheCulprit->getSourceRange();
13097         if (getLangOpts().CPlusPlus11)
13098           Diag(var->getLocation(), diag::note_use_thread_local);
13099       }
13100     }
13101   }
13102 
13103 
13104   if (!var->getType()->isStructureType() && var->hasInit() &&
13105       isa<InitListExpr>(var->getInit())) {
13106     const auto *ILE = cast<InitListExpr>(var->getInit());
13107     unsigned NumInits = ILE->getNumInits();
13108     if (NumInits > 2)
13109       for (unsigned I = 0; I < NumInits; ++I) {
13110         const auto *Init = ILE->getInit(I);
13111         if (!Init)
13112           break;
13113         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13114         if (!SL)
13115           break;
13116 
13117         unsigned NumConcat = SL->getNumConcatenated();
13118         // Diagnose missing comma in string array initialization.
13119         // Do not warn when all the elements in the initializer are concatenated
13120         // together. Do not warn for macros too.
13121         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13122           bool OnlyOneMissingComma = true;
13123           for (unsigned J = I + 1; J < NumInits; ++J) {
13124             const auto *Init = ILE->getInit(J);
13125             if (!Init)
13126               break;
13127             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13128             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13129               OnlyOneMissingComma = false;
13130               break;
13131             }
13132           }
13133 
13134           if (OnlyOneMissingComma) {
13135             SmallVector<FixItHint, 1> Hints;
13136             for (unsigned i = 0; i < NumConcat - 1; ++i)
13137               Hints.push_back(FixItHint::CreateInsertion(
13138                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13139 
13140             Diag(SL->getStrTokenLoc(1),
13141                  diag::warn_concatenated_literal_array_init)
13142                 << Hints;
13143             Diag(SL->getBeginLoc(),
13144                  diag::note_concatenated_string_literal_silence);
13145           }
13146           // In any case, stop now.
13147           break;
13148         }
13149       }
13150   }
13151 
13152 
13153   QualType type = var->getType();
13154 
13155   if (var->hasAttr<BlocksAttr>())
13156     getCurFunction()->addByrefBlockVar(var);
13157 
13158   Expr *Init = var->getInit();
13159   bool GlobalStorage = var->hasGlobalStorage();
13160   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13161   QualType baseType = Context.getBaseElementType(type);
13162   bool HasConstInit = true;
13163 
13164   // Check whether the initializer is sufficiently constant.
13165   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13166       !Init->isValueDependent() &&
13167       (GlobalStorage || var->isConstexpr() ||
13168        var->mightBeUsableInConstantExpressions(Context))) {
13169     // If this variable might have a constant initializer or might be usable in
13170     // constant expressions, check whether or not it actually is now.  We can't
13171     // do this lazily, because the result might depend on things that change
13172     // later, such as which constexpr functions happen to be defined.
13173     SmallVector<PartialDiagnosticAt, 8> Notes;
13174     if (!getLangOpts().CPlusPlus11) {
13175       // Prior to C++11, in contexts where a constant initializer is required,
13176       // the set of valid constant initializers is described by syntactic rules
13177       // in [expr.const]p2-6.
13178       // FIXME: Stricter checking for these rules would be useful for constinit /
13179       // -Wglobal-constructors.
13180       HasConstInit = checkConstInit();
13181 
13182       // Compute and cache the constant value, and remember that we have a
13183       // constant initializer.
13184       if (HasConstInit) {
13185         (void)var->checkForConstantInitialization(Notes);
13186         Notes.clear();
13187       } else if (CacheCulprit) {
13188         Notes.emplace_back(CacheCulprit->getExprLoc(),
13189                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13190         Notes.back().second << CacheCulprit->getSourceRange();
13191       }
13192     } else {
13193       // Evaluate the initializer to see if it's a constant initializer.
13194       HasConstInit = var->checkForConstantInitialization(Notes);
13195     }
13196 
13197     if (HasConstInit) {
13198       // FIXME: Consider replacing the initializer with a ConstantExpr.
13199     } else if (var->isConstexpr()) {
13200       SourceLocation DiagLoc = var->getLocation();
13201       // If the note doesn't add any useful information other than a source
13202       // location, fold it into the primary diagnostic.
13203       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13204                                    diag::note_invalid_subexpr_in_const_expr) {
13205         DiagLoc = Notes[0].first;
13206         Notes.clear();
13207       }
13208       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13209           << var << Init->getSourceRange();
13210       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13211         Diag(Notes[I].first, Notes[I].second);
13212     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13213       auto *Attr = var->getAttr<ConstInitAttr>();
13214       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13215           << Init->getSourceRange();
13216       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13217           << Attr->getRange() << Attr->isConstinit();
13218       for (auto &it : Notes)
13219         Diag(it.first, it.second);
13220     } else if (IsGlobal &&
13221                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13222                                            var->getLocation())) {
13223       // Warn about globals which don't have a constant initializer.  Don't
13224       // warn about globals with a non-trivial destructor because we already
13225       // warned about them.
13226       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13227       if (!(RD && !RD->hasTrivialDestructor())) {
13228         // checkConstInit() here permits trivial default initialization even in
13229         // C++11 onwards, where such an initializer is not a constant initializer
13230         // but nonetheless doesn't require a global constructor.
13231         if (!checkConstInit())
13232           Diag(var->getLocation(), diag::warn_global_constructor)
13233               << Init->getSourceRange();
13234       }
13235     }
13236   }
13237 
13238   // Apply section attributes and pragmas to global variables.
13239   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13240       !inTemplateInstantiation()) {
13241     PragmaStack<StringLiteral *> *Stack = nullptr;
13242     int SectionFlags = ASTContext::PSF_Read;
13243     if (var->getType().isConstQualified()) {
13244       if (HasConstInit)
13245         Stack = &ConstSegStack;
13246       else {
13247         Stack = &BSSSegStack;
13248         SectionFlags |= ASTContext::PSF_Write;
13249       }
13250     } else if (var->hasInit() && HasConstInit) {
13251       Stack = &DataSegStack;
13252       SectionFlags |= ASTContext::PSF_Write;
13253     } else {
13254       Stack = &BSSSegStack;
13255       SectionFlags |= ASTContext::PSF_Write;
13256     }
13257     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13258       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13259         SectionFlags |= ASTContext::PSF_Implicit;
13260       UnifySection(SA->getName(), SectionFlags, var);
13261     } else if (Stack->CurrentValue) {
13262       SectionFlags |= ASTContext::PSF_Implicit;
13263       auto SectionName = Stack->CurrentValue->getString();
13264       var->addAttr(SectionAttr::CreateImplicit(
13265           Context, SectionName, Stack->CurrentPragmaLocation,
13266           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13267       if (UnifySection(SectionName, SectionFlags, var))
13268         var->dropAttr<SectionAttr>();
13269     }
13270 
13271     // Apply the init_seg attribute if this has an initializer.  If the
13272     // initializer turns out to not be dynamic, we'll end up ignoring this
13273     // attribute.
13274     if (CurInitSeg && var->getInit())
13275       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13276                                                CurInitSegLoc,
13277                                                AttributeCommonInfo::AS_Pragma));
13278   }
13279 
13280   // All the following checks are C++ only.
13281   if (!getLangOpts().CPlusPlus) {
13282     // If this variable must be emitted, add it as an initializer for the
13283     // current module.
13284     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13285       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13286     return;
13287   }
13288 
13289   // Require the destructor.
13290   if (!type->isDependentType())
13291     if (const RecordType *recordType = baseType->getAs<RecordType>())
13292       FinalizeVarWithDestructor(var, recordType);
13293 
13294   // If this variable must be emitted, add it as an initializer for the current
13295   // module.
13296   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13297     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13298 
13299   // Build the bindings if this is a structured binding declaration.
13300   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13301     CheckCompleteDecompositionDeclaration(DD);
13302 }
13303 
13304 /// Determines if a variable's alignment is dependent.
13305 static bool hasDependentAlignment(VarDecl *VD) {
13306   if (VD->getType()->isDependentType())
13307     return true;
13308   for (auto *I : VD->specific_attrs<AlignedAttr>())
13309     if (I->isAlignmentDependent())
13310       return true;
13311   return false;
13312 }
13313 
13314 /// Check if VD needs to be dllexport/dllimport due to being in a
13315 /// dllexport/import function.
13316 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13317   assert(VD->isStaticLocal());
13318 
13319   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13320 
13321   // Find outermost function when VD is in lambda function.
13322   while (FD && !getDLLAttr(FD) &&
13323          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13324          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13325     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13326   }
13327 
13328   if (!FD)
13329     return;
13330 
13331   // Static locals inherit dll attributes from their function.
13332   if (Attr *A = getDLLAttr(FD)) {
13333     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13334     NewAttr->setInherited(true);
13335     VD->addAttr(NewAttr);
13336   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13337     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13338     NewAttr->setInherited(true);
13339     VD->addAttr(NewAttr);
13340 
13341     // Export this function to enforce exporting this static variable even
13342     // if it is not used in this compilation unit.
13343     if (!FD->hasAttr<DLLExportAttr>())
13344       FD->addAttr(NewAttr);
13345 
13346   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13347     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13348     NewAttr->setInherited(true);
13349     VD->addAttr(NewAttr);
13350   }
13351 }
13352 
13353 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13354 /// any semantic actions necessary after any initializer has been attached.
13355 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13356   // Note that we are no longer parsing the initializer for this declaration.
13357   ParsingInitForAutoVars.erase(ThisDecl);
13358 
13359   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13360   if (!VD)
13361     return;
13362 
13363   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13364   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13365       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13366     if (PragmaClangBSSSection.Valid)
13367       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13368           Context, PragmaClangBSSSection.SectionName,
13369           PragmaClangBSSSection.PragmaLocation,
13370           AttributeCommonInfo::AS_Pragma));
13371     if (PragmaClangDataSection.Valid)
13372       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13373           Context, PragmaClangDataSection.SectionName,
13374           PragmaClangDataSection.PragmaLocation,
13375           AttributeCommonInfo::AS_Pragma));
13376     if (PragmaClangRodataSection.Valid)
13377       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13378           Context, PragmaClangRodataSection.SectionName,
13379           PragmaClangRodataSection.PragmaLocation,
13380           AttributeCommonInfo::AS_Pragma));
13381     if (PragmaClangRelroSection.Valid)
13382       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13383           Context, PragmaClangRelroSection.SectionName,
13384           PragmaClangRelroSection.PragmaLocation,
13385           AttributeCommonInfo::AS_Pragma));
13386   }
13387 
13388   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13389     for (auto *BD : DD->bindings()) {
13390       FinalizeDeclaration(BD);
13391     }
13392   }
13393 
13394   checkAttributesAfterMerging(*this, *VD);
13395 
13396   // Perform TLS alignment check here after attributes attached to the variable
13397   // which may affect the alignment have been processed. Only perform the check
13398   // if the target has a maximum TLS alignment (zero means no constraints).
13399   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13400     // Protect the check so that it's not performed on dependent types and
13401     // dependent alignments (we can't determine the alignment in that case).
13402     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13403         !VD->isInvalidDecl()) {
13404       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13405       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13406         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13407           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13408           << (unsigned)MaxAlignChars.getQuantity();
13409       }
13410     }
13411   }
13412 
13413   if (VD->isStaticLocal())
13414     CheckStaticLocalForDllExport(VD);
13415 
13416   // Perform check for initializers of device-side global variables.
13417   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13418   // 7.5). We must also apply the same checks to all __shared__
13419   // variables whether they are local or not. CUDA also allows
13420   // constant initializers for __constant__ and __device__ variables.
13421   if (getLangOpts().CUDA)
13422     checkAllowedCUDAInitializer(VD);
13423 
13424   // Grab the dllimport or dllexport attribute off of the VarDecl.
13425   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13426 
13427   // Imported static data members cannot be defined out-of-line.
13428   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13429     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13430         VD->isThisDeclarationADefinition()) {
13431       // We allow definitions of dllimport class template static data members
13432       // with a warning.
13433       CXXRecordDecl *Context =
13434         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13435       bool IsClassTemplateMember =
13436           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13437           Context->getDescribedClassTemplate();
13438 
13439       Diag(VD->getLocation(),
13440            IsClassTemplateMember
13441                ? diag::warn_attribute_dllimport_static_field_definition
13442                : diag::err_attribute_dllimport_static_field_definition);
13443       Diag(IA->getLocation(), diag::note_attribute);
13444       if (!IsClassTemplateMember)
13445         VD->setInvalidDecl();
13446     }
13447   }
13448 
13449   // dllimport/dllexport variables cannot be thread local, their TLS index
13450   // isn't exported with the variable.
13451   if (DLLAttr && VD->getTLSKind()) {
13452     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13453     if (F && getDLLAttr(F)) {
13454       assert(VD->isStaticLocal());
13455       // But if this is a static local in a dlimport/dllexport function, the
13456       // function will never be inlined, which means the var would never be
13457       // imported, so having it marked import/export is safe.
13458     } else {
13459       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13460                                                                     << DLLAttr;
13461       VD->setInvalidDecl();
13462     }
13463   }
13464 
13465   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13466     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13467       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13468           << Attr;
13469       VD->dropAttr<UsedAttr>();
13470     }
13471   }
13472   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13473     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13474       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13475           << Attr;
13476       VD->dropAttr<RetainAttr>();
13477     }
13478   }
13479 
13480   const DeclContext *DC = VD->getDeclContext();
13481   // If there's a #pragma GCC visibility in scope, and this isn't a class
13482   // member, set the visibility of this variable.
13483   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13484     AddPushedVisibilityAttribute(VD);
13485 
13486   // FIXME: Warn on unused var template partial specializations.
13487   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13488     MarkUnusedFileScopedDecl(VD);
13489 
13490   // Now we have parsed the initializer and can update the table of magic
13491   // tag values.
13492   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13493       !VD->getType()->isIntegralOrEnumerationType())
13494     return;
13495 
13496   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13497     const Expr *MagicValueExpr = VD->getInit();
13498     if (!MagicValueExpr) {
13499       continue;
13500     }
13501     Optional<llvm::APSInt> MagicValueInt;
13502     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13503       Diag(I->getRange().getBegin(),
13504            diag::err_type_tag_for_datatype_not_ice)
13505         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13506       continue;
13507     }
13508     if (MagicValueInt->getActiveBits() > 64) {
13509       Diag(I->getRange().getBegin(),
13510            diag::err_type_tag_for_datatype_too_large)
13511         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13512       continue;
13513     }
13514     uint64_t MagicValue = MagicValueInt->getZExtValue();
13515     RegisterTypeTagForDatatype(I->getArgumentKind(),
13516                                MagicValue,
13517                                I->getMatchingCType(),
13518                                I->getLayoutCompatible(),
13519                                I->getMustBeNull());
13520   }
13521 }
13522 
13523 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13524   auto *VD = dyn_cast<VarDecl>(DD);
13525   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13526 }
13527 
13528 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13529                                                    ArrayRef<Decl *> Group) {
13530   SmallVector<Decl*, 8> Decls;
13531 
13532   if (DS.isTypeSpecOwned())
13533     Decls.push_back(DS.getRepAsDecl());
13534 
13535   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13536   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13537   bool DiagnosedMultipleDecomps = false;
13538   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13539   bool DiagnosedNonDeducedAuto = false;
13540 
13541   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13542     if (Decl *D = Group[i]) {
13543       // For declarators, there are some additional syntactic-ish checks we need
13544       // to perform.
13545       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13546         if (!FirstDeclaratorInGroup)
13547           FirstDeclaratorInGroup = DD;
13548         if (!FirstDecompDeclaratorInGroup)
13549           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13550         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13551             !hasDeducedAuto(DD))
13552           FirstNonDeducedAutoInGroup = DD;
13553 
13554         if (FirstDeclaratorInGroup != DD) {
13555           // A decomposition declaration cannot be combined with any other
13556           // declaration in the same group.
13557           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13558             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13559                  diag::err_decomp_decl_not_alone)
13560                 << FirstDeclaratorInGroup->getSourceRange()
13561                 << DD->getSourceRange();
13562             DiagnosedMultipleDecomps = true;
13563           }
13564 
13565           // A declarator that uses 'auto' in any way other than to declare a
13566           // variable with a deduced type cannot be combined with any other
13567           // declarator in the same group.
13568           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13569             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13570                  diag::err_auto_non_deduced_not_alone)
13571                 << FirstNonDeducedAutoInGroup->getType()
13572                        ->hasAutoForTrailingReturnType()
13573                 << FirstDeclaratorInGroup->getSourceRange()
13574                 << DD->getSourceRange();
13575             DiagnosedNonDeducedAuto = true;
13576           }
13577         }
13578       }
13579 
13580       Decls.push_back(D);
13581     }
13582   }
13583 
13584   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13585     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13586       handleTagNumbering(Tag, S);
13587       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13588           getLangOpts().CPlusPlus)
13589         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13590     }
13591   }
13592 
13593   return BuildDeclaratorGroup(Decls);
13594 }
13595 
13596 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13597 /// group, performing any necessary semantic checking.
13598 Sema::DeclGroupPtrTy
13599 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13600   // C++14 [dcl.spec.auto]p7: (DR1347)
13601   //   If the type that replaces the placeholder type is not the same in each
13602   //   deduction, the program is ill-formed.
13603   if (Group.size() > 1) {
13604     QualType Deduced;
13605     VarDecl *DeducedDecl = nullptr;
13606     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13607       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13608       if (!D || D->isInvalidDecl())
13609         break;
13610       DeducedType *DT = D->getType()->getContainedDeducedType();
13611       if (!DT || DT->getDeducedType().isNull())
13612         continue;
13613       if (Deduced.isNull()) {
13614         Deduced = DT->getDeducedType();
13615         DeducedDecl = D;
13616       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13617         auto *AT = dyn_cast<AutoType>(DT);
13618         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13619                         diag::err_auto_different_deductions)
13620                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13621                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13622                    << D->getDeclName();
13623         if (DeducedDecl->hasInit())
13624           Dia << DeducedDecl->getInit()->getSourceRange();
13625         if (D->getInit())
13626           Dia << D->getInit()->getSourceRange();
13627         D->setInvalidDecl();
13628         break;
13629       }
13630     }
13631   }
13632 
13633   ActOnDocumentableDecls(Group);
13634 
13635   return DeclGroupPtrTy::make(
13636       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13637 }
13638 
13639 void Sema::ActOnDocumentableDecl(Decl *D) {
13640   ActOnDocumentableDecls(D);
13641 }
13642 
13643 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13644   // Don't parse the comment if Doxygen diagnostics are ignored.
13645   if (Group.empty() || !Group[0])
13646     return;
13647 
13648   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13649                       Group[0]->getLocation()) &&
13650       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13651                       Group[0]->getLocation()))
13652     return;
13653 
13654   if (Group.size() >= 2) {
13655     // This is a decl group.  Normally it will contain only declarations
13656     // produced from declarator list.  But in case we have any definitions or
13657     // additional declaration references:
13658     //   'typedef struct S {} S;'
13659     //   'typedef struct S *S;'
13660     //   'struct S *pS;'
13661     // FinalizeDeclaratorGroup adds these as separate declarations.
13662     Decl *MaybeTagDecl = Group[0];
13663     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13664       Group = Group.slice(1);
13665     }
13666   }
13667 
13668   // FIMXE: We assume every Decl in the group is in the same file.
13669   // This is false when preprocessor constructs the group from decls in
13670   // different files (e. g. macros or #include).
13671   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13672 }
13673 
13674 /// Common checks for a parameter-declaration that should apply to both function
13675 /// parameters and non-type template parameters.
13676 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13677   // Check that there are no default arguments inside the type of this
13678   // parameter.
13679   if (getLangOpts().CPlusPlus)
13680     CheckExtraCXXDefaultArguments(D);
13681 
13682   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13683   if (D.getCXXScopeSpec().isSet()) {
13684     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13685       << D.getCXXScopeSpec().getRange();
13686   }
13687 
13688   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13689   // simple identifier except [...irrelevant cases...].
13690   switch (D.getName().getKind()) {
13691   case UnqualifiedIdKind::IK_Identifier:
13692     break;
13693 
13694   case UnqualifiedIdKind::IK_OperatorFunctionId:
13695   case UnqualifiedIdKind::IK_ConversionFunctionId:
13696   case UnqualifiedIdKind::IK_LiteralOperatorId:
13697   case UnqualifiedIdKind::IK_ConstructorName:
13698   case UnqualifiedIdKind::IK_DestructorName:
13699   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13700   case UnqualifiedIdKind::IK_DeductionGuideName:
13701     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13702       << GetNameForDeclarator(D).getName();
13703     break;
13704 
13705   case UnqualifiedIdKind::IK_TemplateId:
13706   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13707     // GetNameForDeclarator would not produce a useful name in this case.
13708     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13709     break;
13710   }
13711 }
13712 
13713 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13714 /// to introduce parameters into function prototype scope.
13715 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13716   const DeclSpec &DS = D.getDeclSpec();
13717 
13718   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13719 
13720   // C++03 [dcl.stc]p2 also permits 'auto'.
13721   StorageClass SC = SC_None;
13722   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13723     SC = SC_Register;
13724     // In C++11, the 'register' storage class specifier is deprecated.
13725     // In C++17, it is not allowed, but we tolerate it as an extension.
13726     if (getLangOpts().CPlusPlus11) {
13727       Diag(DS.getStorageClassSpecLoc(),
13728            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13729                                      : diag::warn_deprecated_register)
13730         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13731     }
13732   } else if (getLangOpts().CPlusPlus &&
13733              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13734     SC = SC_Auto;
13735   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13736     Diag(DS.getStorageClassSpecLoc(),
13737          diag::err_invalid_storage_class_in_func_decl);
13738     D.getMutableDeclSpec().ClearStorageClassSpecs();
13739   }
13740 
13741   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13742     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13743       << DeclSpec::getSpecifierName(TSCS);
13744   if (DS.isInlineSpecified())
13745     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13746         << getLangOpts().CPlusPlus17;
13747   if (DS.hasConstexprSpecifier())
13748     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13749         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13750 
13751   DiagnoseFunctionSpecifiers(DS);
13752 
13753   CheckFunctionOrTemplateParamDeclarator(S, D);
13754 
13755   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13756   QualType parmDeclType = TInfo->getType();
13757 
13758   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13759   IdentifierInfo *II = D.getIdentifier();
13760   if (II) {
13761     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13762                    ForVisibleRedeclaration);
13763     LookupName(R, S);
13764     if (R.isSingleResult()) {
13765       NamedDecl *PrevDecl = R.getFoundDecl();
13766       if (PrevDecl->isTemplateParameter()) {
13767         // Maybe we will complain about the shadowed template parameter.
13768         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13769         // Just pretend that we didn't see the previous declaration.
13770         PrevDecl = nullptr;
13771       } else if (S->isDeclScope(PrevDecl)) {
13772         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13773         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13774 
13775         // Recover by removing the name
13776         II = nullptr;
13777         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13778         D.setInvalidType(true);
13779       }
13780     }
13781   }
13782 
13783   // Temporarily put parameter variables in the translation unit, not
13784   // the enclosing context.  This prevents them from accidentally
13785   // looking like class members in C++.
13786   ParmVarDecl *New =
13787       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13788                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13789 
13790   if (D.isInvalidType())
13791     New->setInvalidDecl();
13792 
13793   assert(S->isFunctionPrototypeScope());
13794   assert(S->getFunctionPrototypeDepth() >= 1);
13795   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13796                     S->getNextFunctionPrototypeIndex());
13797 
13798   // Add the parameter declaration into this scope.
13799   S->AddDecl(New);
13800   if (II)
13801     IdResolver.AddDecl(New);
13802 
13803   ProcessDeclAttributes(S, New, D);
13804 
13805   if (D.getDeclSpec().isModulePrivateSpecified())
13806     Diag(New->getLocation(), diag::err_module_private_local)
13807         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13808         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13809 
13810   if (New->hasAttr<BlocksAttr>()) {
13811     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13812   }
13813 
13814   if (getLangOpts().OpenCL)
13815     deduceOpenCLAddressSpace(New);
13816 
13817   return New;
13818 }
13819 
13820 /// Synthesizes a variable for a parameter arising from a
13821 /// typedef.
13822 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13823                                               SourceLocation Loc,
13824                                               QualType T) {
13825   /* FIXME: setting StartLoc == Loc.
13826      Would it be worth to modify callers so as to provide proper source
13827      location for the unnamed parameters, embedding the parameter's type? */
13828   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13829                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13830                                            SC_None, nullptr);
13831   Param->setImplicit();
13832   return Param;
13833 }
13834 
13835 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13836   // Don't diagnose unused-parameter errors in template instantiations; we
13837   // will already have done so in the template itself.
13838   if (inTemplateInstantiation())
13839     return;
13840 
13841   for (const ParmVarDecl *Parameter : Parameters) {
13842     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13843         !Parameter->hasAttr<UnusedAttr>()) {
13844       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13845         << Parameter->getDeclName();
13846     }
13847   }
13848 }
13849 
13850 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13851     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13852   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13853     return;
13854 
13855   // Warn if the return value is pass-by-value and larger than the specified
13856   // threshold.
13857   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13858     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13859     if (Size > LangOpts.NumLargeByValueCopy)
13860       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13861   }
13862 
13863   // Warn if any parameter is pass-by-value and larger than the specified
13864   // threshold.
13865   for (const ParmVarDecl *Parameter : Parameters) {
13866     QualType T = Parameter->getType();
13867     if (T->isDependentType() || !T.isPODType(Context))
13868       continue;
13869     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13870     if (Size > LangOpts.NumLargeByValueCopy)
13871       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13872           << Parameter << Size;
13873   }
13874 }
13875 
13876 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13877                                   SourceLocation NameLoc, IdentifierInfo *Name,
13878                                   QualType T, TypeSourceInfo *TSInfo,
13879                                   StorageClass SC) {
13880   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13881   if (getLangOpts().ObjCAutoRefCount &&
13882       T.getObjCLifetime() == Qualifiers::OCL_None &&
13883       T->isObjCLifetimeType()) {
13884 
13885     Qualifiers::ObjCLifetime lifetime;
13886 
13887     // Special cases for arrays:
13888     //   - if it's const, use __unsafe_unretained
13889     //   - otherwise, it's an error
13890     if (T->isArrayType()) {
13891       if (!T.isConstQualified()) {
13892         if (DelayedDiagnostics.shouldDelayDiagnostics())
13893           DelayedDiagnostics.add(
13894               sema::DelayedDiagnostic::makeForbiddenType(
13895               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13896         else
13897           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13898               << TSInfo->getTypeLoc().getSourceRange();
13899       }
13900       lifetime = Qualifiers::OCL_ExplicitNone;
13901     } else {
13902       lifetime = T->getObjCARCImplicitLifetime();
13903     }
13904     T = Context.getLifetimeQualifiedType(T, lifetime);
13905   }
13906 
13907   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13908                                          Context.getAdjustedParameterType(T),
13909                                          TSInfo, SC, nullptr);
13910 
13911   // Make a note if we created a new pack in the scope of a lambda, so that
13912   // we know that references to that pack must also be expanded within the
13913   // lambda scope.
13914   if (New->isParameterPack())
13915     if (auto *LSI = getEnclosingLambda())
13916       LSI->LocalPacks.push_back(New);
13917 
13918   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13919       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13920     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13921                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13922 
13923   // Parameters can not be abstract class types.
13924   // For record types, this is done by the AbstractClassUsageDiagnoser once
13925   // the class has been completely parsed.
13926   if (!CurContext->isRecord() &&
13927       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13928                              AbstractParamType))
13929     New->setInvalidDecl();
13930 
13931   // Parameter declarators cannot be interface types. All ObjC objects are
13932   // passed by reference.
13933   if (T->isObjCObjectType()) {
13934     SourceLocation TypeEndLoc =
13935         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13936     Diag(NameLoc,
13937          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13938       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13939     T = Context.getObjCObjectPointerType(T);
13940     New->setType(T);
13941   }
13942 
13943   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13944   // duration shall not be qualified by an address-space qualifier."
13945   // Since all parameters have automatic store duration, they can not have
13946   // an address space.
13947   if (T.getAddressSpace() != LangAS::Default &&
13948       // OpenCL allows function arguments declared to be an array of a type
13949       // to be qualified with an address space.
13950       !(getLangOpts().OpenCL &&
13951         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13952     Diag(NameLoc, diag::err_arg_with_address_space);
13953     New->setInvalidDecl();
13954   }
13955 
13956   // PPC MMA non-pointer types are not allowed as function argument types.
13957   if (Context.getTargetInfo().getTriple().isPPC64() &&
13958       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13959     New->setInvalidDecl();
13960   }
13961 
13962   return New;
13963 }
13964 
13965 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13966                                            SourceLocation LocAfterDecls) {
13967   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13968 
13969   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13970   // for a K&R function.
13971   if (!FTI.hasPrototype) {
13972     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13973       --i;
13974       if (FTI.Params[i].Param == nullptr) {
13975         SmallString<256> Code;
13976         llvm::raw_svector_ostream(Code)
13977             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13978         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13979             << FTI.Params[i].Ident
13980             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13981 
13982         // Implicitly declare the argument as type 'int' for lack of a better
13983         // type.
13984         AttributeFactory attrs;
13985         DeclSpec DS(attrs);
13986         const char* PrevSpec; // unused
13987         unsigned DiagID; // unused
13988         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13989                            DiagID, Context.getPrintingPolicy());
13990         // Use the identifier location for the type source range.
13991         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13992         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13993         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13994         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13995         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13996       }
13997     }
13998   }
13999 }
14000 
14001 Decl *
14002 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14003                               MultiTemplateParamsArg TemplateParameterLists,
14004                               SkipBodyInfo *SkipBody) {
14005   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14006   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14007   Scope *ParentScope = FnBodyScope->getParent();
14008 
14009   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14010   // we define a non-templated function definition, we will create a declaration
14011   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14012   // The base function declaration will have the equivalent of an `omp declare
14013   // variant` annotation which specifies the mangled definition as a
14014   // specialization function under the OpenMP context defined as part of the
14015   // `omp begin declare variant`.
14016   SmallVector<FunctionDecl *, 4> Bases;
14017   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14018     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14019         ParentScope, D, TemplateParameterLists, Bases);
14020 
14021   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14022   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14023   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14024 
14025   if (!Bases.empty())
14026     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14027 
14028   return Dcl;
14029 }
14030 
14031 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14032   Consumer.HandleInlineFunctionDefinition(D);
14033 }
14034 
14035 static bool
14036 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14037                                 const FunctionDecl *&PossiblePrototype) {
14038   // Don't warn about invalid declarations.
14039   if (FD->isInvalidDecl())
14040     return false;
14041 
14042   // Or declarations that aren't global.
14043   if (!FD->isGlobal())
14044     return false;
14045 
14046   // Don't warn about C++ member functions.
14047   if (isa<CXXMethodDecl>(FD))
14048     return false;
14049 
14050   // Don't warn about 'main'.
14051   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14052     if (IdentifierInfo *II = FD->getIdentifier())
14053       if (II->isStr("main") || II->isStr("efi_main"))
14054         return false;
14055 
14056   // Don't warn about inline functions.
14057   if (FD->isInlined())
14058     return false;
14059 
14060   // Don't warn about function templates.
14061   if (FD->getDescribedFunctionTemplate())
14062     return false;
14063 
14064   // Don't warn about function template specializations.
14065   if (FD->isFunctionTemplateSpecialization())
14066     return false;
14067 
14068   // Don't warn for OpenCL kernels.
14069   if (FD->hasAttr<OpenCLKernelAttr>())
14070     return false;
14071 
14072   // Don't warn on explicitly deleted functions.
14073   if (FD->isDeleted())
14074     return false;
14075 
14076   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14077        Prev; Prev = Prev->getPreviousDecl()) {
14078     // Ignore any declarations that occur in function or method
14079     // scope, because they aren't visible from the header.
14080     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14081       continue;
14082 
14083     PossiblePrototype = Prev;
14084     return Prev->getType()->isFunctionNoProtoType();
14085   }
14086 
14087   return true;
14088 }
14089 
14090 void
14091 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14092                                    const FunctionDecl *EffectiveDefinition,
14093                                    SkipBodyInfo *SkipBody) {
14094   const FunctionDecl *Definition = EffectiveDefinition;
14095   if (!Definition &&
14096       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14097     return;
14098 
14099   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14100     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14101       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14102         // A merged copy of the same function, instantiated as a member of
14103         // the same class, is OK.
14104         if (declaresSameEntity(OrigFD, OrigDef) &&
14105             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14106                                cast<Decl>(FD->getLexicalDeclContext())))
14107           return;
14108       }
14109     }
14110   }
14111 
14112   if (canRedefineFunction(Definition, getLangOpts()))
14113     return;
14114 
14115   // Don't emit an error when this is redefinition of a typo-corrected
14116   // definition.
14117   if (TypoCorrectedFunctionDefinitions.count(Definition))
14118     return;
14119 
14120   // If we don't have a visible definition of the function, and it's inline or
14121   // a template, skip the new definition.
14122   if (SkipBody && !hasVisibleDefinition(Definition) &&
14123       (Definition->getFormalLinkage() == InternalLinkage ||
14124        Definition->isInlined() ||
14125        Definition->getDescribedFunctionTemplate() ||
14126        Definition->getNumTemplateParameterLists())) {
14127     SkipBody->ShouldSkip = true;
14128     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14129     if (auto *TD = Definition->getDescribedFunctionTemplate())
14130       makeMergedDefinitionVisible(TD);
14131     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14132     return;
14133   }
14134 
14135   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14136       Definition->getStorageClass() == SC_Extern)
14137     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14138         << FD << getLangOpts().CPlusPlus;
14139   else
14140     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14141 
14142   Diag(Definition->getLocation(), diag::note_previous_definition);
14143   FD->setInvalidDecl();
14144 }
14145 
14146 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14147                                    Sema &S) {
14148   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14149 
14150   LambdaScopeInfo *LSI = S.PushLambdaScope();
14151   LSI->CallOperator = CallOperator;
14152   LSI->Lambda = LambdaClass;
14153   LSI->ReturnType = CallOperator->getReturnType();
14154   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14155 
14156   if (LCD == LCD_None)
14157     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14158   else if (LCD == LCD_ByCopy)
14159     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14160   else if (LCD == LCD_ByRef)
14161     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14162   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14163 
14164   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14165   LSI->Mutable = !CallOperator->isConst();
14166 
14167   // Add the captures to the LSI so they can be noted as already
14168   // captured within tryCaptureVar.
14169   auto I = LambdaClass->field_begin();
14170   for (const auto &C : LambdaClass->captures()) {
14171     if (C.capturesVariable()) {
14172       VarDecl *VD = C.getCapturedVar();
14173       if (VD->isInitCapture())
14174         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14175       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14176       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14177           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14178           /*EllipsisLoc*/C.isPackExpansion()
14179                          ? C.getEllipsisLoc() : SourceLocation(),
14180           I->getType(), /*Invalid*/false);
14181 
14182     } else if (C.capturesThis()) {
14183       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14184                           C.getCaptureKind() == LCK_StarThis);
14185     } else {
14186       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14187                              I->getType());
14188     }
14189     ++I;
14190   }
14191 }
14192 
14193 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14194                                     SkipBodyInfo *SkipBody) {
14195   if (!D) {
14196     // Parsing the function declaration failed in some way. Push on a fake scope
14197     // anyway so we can try to parse the function body.
14198     PushFunctionScope();
14199     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14200     return D;
14201   }
14202 
14203   FunctionDecl *FD = nullptr;
14204 
14205   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14206     FD = FunTmpl->getTemplatedDecl();
14207   else
14208     FD = cast<FunctionDecl>(D);
14209 
14210   // Do not push if it is a lambda because one is already pushed when building
14211   // the lambda in ActOnStartOfLambdaDefinition().
14212   if (!isLambdaCallOperator(FD))
14213     PushExpressionEvaluationContext(
14214         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14215                           : ExprEvalContexts.back().Context);
14216 
14217   // Check for defining attributes before the check for redefinition.
14218   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14219     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14220     FD->dropAttr<AliasAttr>();
14221     FD->setInvalidDecl();
14222   }
14223   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14224     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14225     FD->dropAttr<IFuncAttr>();
14226     FD->setInvalidDecl();
14227   }
14228 
14229   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14230     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14231         Ctor->isDefaultConstructor() &&
14232         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14233       // If this is an MS ABI dllexport default constructor, instantiate any
14234       // default arguments.
14235       InstantiateDefaultCtorDefaultArgs(Ctor);
14236     }
14237   }
14238 
14239   // See if this is a redefinition. If 'will have body' (or similar) is already
14240   // set, then these checks were already performed when it was set.
14241   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14242       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14243     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14244 
14245     // If we're skipping the body, we're done. Don't enter the scope.
14246     if (SkipBody && SkipBody->ShouldSkip)
14247       return D;
14248   }
14249 
14250   // Mark this function as "will have a body eventually".  This lets users to
14251   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14252   // this function.
14253   FD->setWillHaveBody();
14254 
14255   // If we are instantiating a generic lambda call operator, push
14256   // a LambdaScopeInfo onto the function stack.  But use the information
14257   // that's already been calculated (ActOnLambdaExpr) to prime the current
14258   // LambdaScopeInfo.
14259   // When the template operator is being specialized, the LambdaScopeInfo,
14260   // has to be properly restored so that tryCaptureVariable doesn't try
14261   // and capture any new variables. In addition when calculating potential
14262   // captures during transformation of nested lambdas, it is necessary to
14263   // have the LSI properly restored.
14264   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14265     assert(inTemplateInstantiation() &&
14266            "There should be an active template instantiation on the stack "
14267            "when instantiating a generic lambda!");
14268     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14269   } else {
14270     // Enter a new function scope
14271     PushFunctionScope();
14272   }
14273 
14274   // Builtin functions cannot be defined.
14275   if (unsigned BuiltinID = FD->getBuiltinID()) {
14276     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14277         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14278       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14279       FD->setInvalidDecl();
14280     }
14281   }
14282 
14283   // The return type of a function definition must be complete
14284   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14285   QualType ResultType = FD->getReturnType();
14286   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14287       !FD->isInvalidDecl() &&
14288       RequireCompleteType(FD->getLocation(), ResultType,
14289                           diag::err_func_def_incomplete_result))
14290     FD->setInvalidDecl();
14291 
14292   if (FnBodyScope)
14293     PushDeclContext(FnBodyScope, FD);
14294 
14295   // Check the validity of our function parameters
14296   CheckParmsForFunctionDef(FD->parameters(),
14297                            /*CheckParameterNames=*/true);
14298 
14299   // Add non-parameter declarations already in the function to the current
14300   // scope.
14301   if (FnBodyScope) {
14302     for (Decl *NPD : FD->decls()) {
14303       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14304       if (!NonParmDecl)
14305         continue;
14306       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14307              "parameters should not be in newly created FD yet");
14308 
14309       // If the decl has a name, make it accessible in the current scope.
14310       if (NonParmDecl->getDeclName())
14311         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14312 
14313       // Similarly, dive into enums and fish their constants out, making them
14314       // accessible in this scope.
14315       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14316         for (auto *EI : ED->enumerators())
14317           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14318       }
14319     }
14320   }
14321 
14322   // Introduce our parameters into the function scope
14323   for (auto Param : FD->parameters()) {
14324     Param->setOwningFunction(FD);
14325 
14326     // If this has an identifier, add it to the scope stack.
14327     if (Param->getIdentifier() && FnBodyScope) {
14328       CheckShadow(FnBodyScope, Param);
14329 
14330       PushOnScopeChains(Param, FnBodyScope);
14331     }
14332   }
14333 
14334   // Ensure that the function's exception specification is instantiated.
14335   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14336     ResolveExceptionSpec(D->getLocation(), FPT);
14337 
14338   // dllimport cannot be applied to non-inline function definitions.
14339   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14340       !FD->isTemplateInstantiation()) {
14341     assert(!FD->hasAttr<DLLExportAttr>());
14342     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14343     FD->setInvalidDecl();
14344     return D;
14345   }
14346   // We want to attach documentation to original Decl (which might be
14347   // a function template).
14348   ActOnDocumentableDecl(D);
14349   if (getCurLexicalContext()->isObjCContainer() &&
14350       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14351       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14352     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14353 
14354   return D;
14355 }
14356 
14357 /// Given the set of return statements within a function body,
14358 /// compute the variables that are subject to the named return value
14359 /// optimization.
14360 ///
14361 /// Each of the variables that is subject to the named return value
14362 /// optimization will be marked as NRVO variables in the AST, and any
14363 /// return statement that has a marked NRVO variable as its NRVO candidate can
14364 /// use the named return value optimization.
14365 ///
14366 /// This function applies a very simplistic algorithm for NRVO: if every return
14367 /// statement in the scope of a variable has the same NRVO candidate, that
14368 /// candidate is an NRVO variable.
14369 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14370   ReturnStmt **Returns = Scope->Returns.data();
14371 
14372   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14373     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14374       if (!NRVOCandidate->isNRVOVariable())
14375         Returns[I]->setNRVOCandidate(nullptr);
14376     }
14377   }
14378 }
14379 
14380 bool Sema::canDelayFunctionBody(const Declarator &D) {
14381   // We can't delay parsing the body of a constexpr function template (yet).
14382   if (D.getDeclSpec().hasConstexprSpecifier())
14383     return false;
14384 
14385   // We can't delay parsing the body of a function template with a deduced
14386   // return type (yet).
14387   if (D.getDeclSpec().hasAutoTypeSpec()) {
14388     // If the placeholder introduces a non-deduced trailing return type,
14389     // we can still delay parsing it.
14390     if (D.getNumTypeObjects()) {
14391       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14392       if (Outer.Kind == DeclaratorChunk::Function &&
14393           Outer.Fun.hasTrailingReturnType()) {
14394         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14395         return Ty.isNull() || !Ty->isUndeducedType();
14396       }
14397     }
14398     return false;
14399   }
14400 
14401   return true;
14402 }
14403 
14404 bool Sema::canSkipFunctionBody(Decl *D) {
14405   // We cannot skip the body of a function (or function template) which is
14406   // constexpr, since we may need to evaluate its body in order to parse the
14407   // rest of the file.
14408   // We cannot skip the body of a function with an undeduced return type,
14409   // because any callers of that function need to know the type.
14410   if (const FunctionDecl *FD = D->getAsFunction()) {
14411     if (FD->isConstexpr())
14412       return false;
14413     // We can't simply call Type::isUndeducedType here, because inside template
14414     // auto can be deduced to a dependent type, which is not considered
14415     // "undeduced".
14416     if (FD->getReturnType()->getContainedDeducedType())
14417       return false;
14418   }
14419   return Consumer.shouldSkipFunctionBody(D);
14420 }
14421 
14422 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14423   if (!Decl)
14424     return nullptr;
14425   if (FunctionDecl *FD = Decl->getAsFunction())
14426     FD->setHasSkippedBody();
14427   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14428     MD->setHasSkippedBody();
14429   return Decl;
14430 }
14431 
14432 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14433   return ActOnFinishFunctionBody(D, BodyArg, false);
14434 }
14435 
14436 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14437 /// body.
14438 class ExitFunctionBodyRAII {
14439 public:
14440   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14441   ~ExitFunctionBodyRAII() {
14442     if (!IsLambda)
14443       S.PopExpressionEvaluationContext();
14444   }
14445 
14446 private:
14447   Sema &S;
14448   bool IsLambda = false;
14449 };
14450 
14451 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14452   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14453 
14454   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14455     if (EscapeInfo.count(BD))
14456       return EscapeInfo[BD];
14457 
14458     bool R = false;
14459     const BlockDecl *CurBD = BD;
14460 
14461     do {
14462       R = !CurBD->doesNotEscape();
14463       if (R)
14464         break;
14465       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14466     } while (CurBD);
14467 
14468     return EscapeInfo[BD] = R;
14469   };
14470 
14471   // If the location where 'self' is implicitly retained is inside a escaping
14472   // block, emit a diagnostic.
14473   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14474        S.ImplicitlyRetainedSelfLocs)
14475     if (IsOrNestedInEscapingBlock(P.second))
14476       S.Diag(P.first, diag::warn_implicitly_retains_self)
14477           << FixItHint::CreateInsertion(P.first, "self->");
14478 }
14479 
14480 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14481                                     bool IsInstantiation) {
14482   FunctionScopeInfo *FSI = getCurFunction();
14483   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14484 
14485   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14486     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14487 
14488   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14489   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14490 
14491   if (getLangOpts().Coroutines && FSI->isCoroutine())
14492     CheckCompletedCoroutineBody(FD, Body);
14493 
14494   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14495   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14496   // meant to pop the context added in ActOnStartOfFunctionDef().
14497   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14498 
14499   if (FD) {
14500     FD->setBody(Body);
14501     FD->setWillHaveBody(false);
14502 
14503     if (getLangOpts().CPlusPlus14) {
14504       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14505           FD->getReturnType()->isUndeducedType()) {
14506         // If the function has a deduced result type but contains no 'return'
14507         // statements, the result type as written must be exactly 'auto', and
14508         // the deduced result type is 'void'.
14509         if (!FD->getReturnType()->getAs<AutoType>()) {
14510           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14511               << FD->getReturnType();
14512           FD->setInvalidDecl();
14513         } else {
14514           // Substitute 'void' for the 'auto' in the type.
14515           TypeLoc ResultType = getReturnTypeLoc(FD);
14516           Context.adjustDeducedFunctionResultType(
14517               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14518         }
14519       }
14520     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14521       // In C++11, we don't use 'auto' deduction rules for lambda call
14522       // operators because we don't support return type deduction.
14523       auto *LSI = getCurLambda();
14524       if (LSI->HasImplicitReturnType) {
14525         deduceClosureReturnType(*LSI);
14526 
14527         // C++11 [expr.prim.lambda]p4:
14528         //   [...] if there are no return statements in the compound-statement
14529         //   [the deduced type is] the type void
14530         QualType RetType =
14531             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14532 
14533         // Update the return type to the deduced type.
14534         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14535         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14536                                             Proto->getExtProtoInfo()));
14537       }
14538     }
14539 
14540     // If the function implicitly returns zero (like 'main') or is naked,
14541     // don't complain about missing return statements.
14542     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14543       WP.disableCheckFallThrough();
14544 
14545     // MSVC permits the use of pure specifier (=0) on function definition,
14546     // defined at class scope, warn about this non-standard construct.
14547     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14548       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14549 
14550     if (!FD->isInvalidDecl()) {
14551       // Don't diagnose unused parameters of defaulted or deleted functions.
14552       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14553         DiagnoseUnusedParameters(FD->parameters());
14554       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14555                                              FD->getReturnType(), FD);
14556 
14557       // If this is a structor, we need a vtable.
14558       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14559         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14560       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14561         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14562 
14563       // Try to apply the named return value optimization. We have to check
14564       // if we can do this here because lambdas keep return statements around
14565       // to deduce an implicit return type.
14566       if (FD->getReturnType()->isRecordType() &&
14567           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14568         computeNRVO(Body, FSI);
14569     }
14570 
14571     // GNU warning -Wmissing-prototypes:
14572     //   Warn if a global function is defined without a previous
14573     //   prototype declaration. This warning is issued even if the
14574     //   definition itself provides a prototype. The aim is to detect
14575     //   global functions that fail to be declared in header files.
14576     const FunctionDecl *PossiblePrototype = nullptr;
14577     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14578       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14579 
14580       if (PossiblePrototype) {
14581         // We found a declaration that is not a prototype,
14582         // but that could be a zero-parameter prototype
14583         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14584           TypeLoc TL = TI->getTypeLoc();
14585           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14586             Diag(PossiblePrototype->getLocation(),
14587                  diag::note_declaration_not_a_prototype)
14588                 << (FD->getNumParams() != 0)
14589                 << (FD->getNumParams() == 0
14590                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14591                         : FixItHint{});
14592         }
14593       } else {
14594         // Returns true if the token beginning at this Loc is `const`.
14595         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14596                                 const LangOptions &LangOpts) {
14597           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14598           if (LocInfo.first.isInvalid())
14599             return false;
14600 
14601           bool Invalid = false;
14602           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14603           if (Invalid)
14604             return false;
14605 
14606           if (LocInfo.second > Buffer.size())
14607             return false;
14608 
14609           const char *LexStart = Buffer.data() + LocInfo.second;
14610           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14611 
14612           return StartTok.consume_front("const") &&
14613                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14614                   StartTok.startswith("/*") || StartTok.startswith("//"));
14615         };
14616 
14617         auto findBeginLoc = [&]() {
14618           // If the return type has `const` qualifier, we want to insert
14619           // `static` before `const` (and not before the typename).
14620           if ((FD->getReturnType()->isAnyPointerType() &&
14621                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14622               FD->getReturnType().isConstQualified()) {
14623             // But only do this if we can determine where the `const` is.
14624 
14625             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14626                              getLangOpts()))
14627 
14628               return FD->getBeginLoc();
14629           }
14630           return FD->getTypeSpecStartLoc();
14631         };
14632         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14633             << /* function */ 1
14634             << (FD->getStorageClass() == SC_None
14635                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14636                     : FixItHint{});
14637       }
14638 
14639       // GNU warning -Wstrict-prototypes
14640       //   Warn if K&R function is defined without a previous declaration.
14641       //   This warning is issued only if the definition itself does not provide
14642       //   a prototype. Only K&R definitions do not provide a prototype.
14643       if (!FD->hasWrittenPrototype()) {
14644         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14645         TypeLoc TL = TI->getTypeLoc();
14646         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14647         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14648       }
14649     }
14650 
14651     // Warn on CPUDispatch with an actual body.
14652     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14653       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14654         if (!CmpndBody->body_empty())
14655           Diag(CmpndBody->body_front()->getBeginLoc(),
14656                diag::warn_dispatch_body_ignored);
14657 
14658     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14659       const CXXMethodDecl *KeyFunction;
14660       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14661           MD->isVirtual() &&
14662           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14663           MD == KeyFunction->getCanonicalDecl()) {
14664         // Update the key-function state if necessary for this ABI.
14665         if (FD->isInlined() &&
14666             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14667           Context.setNonKeyFunction(MD);
14668 
14669           // If the newly-chosen key function is already defined, then we
14670           // need to mark the vtable as used retroactively.
14671           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14672           const FunctionDecl *Definition;
14673           if (KeyFunction && KeyFunction->isDefined(Definition))
14674             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14675         } else {
14676           // We just defined they key function; mark the vtable as used.
14677           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14678         }
14679       }
14680     }
14681 
14682     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14683            "Function parsing confused");
14684   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14685     assert(MD == getCurMethodDecl() && "Method parsing confused");
14686     MD->setBody(Body);
14687     if (!MD->isInvalidDecl()) {
14688       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14689                                              MD->getReturnType(), MD);
14690 
14691       if (Body)
14692         computeNRVO(Body, FSI);
14693     }
14694     if (FSI->ObjCShouldCallSuper) {
14695       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14696           << MD->getSelector().getAsString();
14697       FSI->ObjCShouldCallSuper = false;
14698     }
14699     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14700       const ObjCMethodDecl *InitMethod = nullptr;
14701       bool isDesignated =
14702           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14703       assert(isDesignated && InitMethod);
14704       (void)isDesignated;
14705 
14706       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14707         auto IFace = MD->getClassInterface();
14708         if (!IFace)
14709           return false;
14710         auto SuperD = IFace->getSuperClass();
14711         if (!SuperD)
14712           return false;
14713         return SuperD->getIdentifier() ==
14714             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14715       };
14716       // Don't issue this warning for unavailable inits or direct subclasses
14717       // of NSObject.
14718       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14719         Diag(MD->getLocation(),
14720              diag::warn_objc_designated_init_missing_super_call);
14721         Diag(InitMethod->getLocation(),
14722              diag::note_objc_designated_init_marked_here);
14723       }
14724       FSI->ObjCWarnForNoDesignatedInitChain = false;
14725     }
14726     if (FSI->ObjCWarnForNoInitDelegation) {
14727       // Don't issue this warning for unavaialable inits.
14728       if (!MD->isUnavailable())
14729         Diag(MD->getLocation(),
14730              diag::warn_objc_secondary_init_missing_init_call);
14731       FSI->ObjCWarnForNoInitDelegation = false;
14732     }
14733 
14734     diagnoseImplicitlyRetainedSelf(*this);
14735   } else {
14736     // Parsing the function declaration failed in some way. Pop the fake scope
14737     // we pushed on.
14738     PopFunctionScopeInfo(ActivePolicy, dcl);
14739     return nullptr;
14740   }
14741 
14742   if (Body && FSI->HasPotentialAvailabilityViolations)
14743     DiagnoseUnguardedAvailabilityViolations(dcl);
14744 
14745   assert(!FSI->ObjCShouldCallSuper &&
14746          "This should only be set for ObjC methods, which should have been "
14747          "handled in the block above.");
14748 
14749   // Verify and clean out per-function state.
14750   if (Body && (!FD || !FD->isDefaulted())) {
14751     // C++ constructors that have function-try-blocks can't have return
14752     // statements in the handlers of that block. (C++ [except.handle]p14)
14753     // Verify this.
14754     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14755       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14756 
14757     // Verify that gotos and switch cases don't jump into scopes illegally.
14758     if (FSI->NeedsScopeChecking() &&
14759         !PP.isCodeCompletionEnabled())
14760       DiagnoseInvalidJumps(Body);
14761 
14762     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14763       if (!Destructor->getParent()->isDependentType())
14764         CheckDestructor(Destructor);
14765 
14766       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14767                                              Destructor->getParent());
14768     }
14769 
14770     // If any errors have occurred, clear out any temporaries that may have
14771     // been leftover. This ensures that these temporaries won't be picked up for
14772     // deletion in some later function.
14773     if (hasUncompilableErrorOccurred() ||
14774         getDiagnostics().getSuppressAllDiagnostics()) {
14775       DiscardCleanupsInEvaluationContext();
14776     }
14777     if (!hasUncompilableErrorOccurred() &&
14778         !isa<FunctionTemplateDecl>(dcl)) {
14779       // Since the body is valid, issue any analysis-based warnings that are
14780       // enabled.
14781       ActivePolicy = &WP;
14782     }
14783 
14784     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14785         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14786       FD->setInvalidDecl();
14787 
14788     if (FD && FD->hasAttr<NakedAttr>()) {
14789       for (const Stmt *S : Body->children()) {
14790         // Allow local register variables without initializer as they don't
14791         // require prologue.
14792         bool RegisterVariables = false;
14793         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14794           for (const auto *Decl : DS->decls()) {
14795             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14796               RegisterVariables =
14797                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14798               if (!RegisterVariables)
14799                 break;
14800             }
14801           }
14802         }
14803         if (RegisterVariables)
14804           continue;
14805         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14806           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14807           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14808           FD->setInvalidDecl();
14809           break;
14810         }
14811       }
14812     }
14813 
14814     assert(ExprCleanupObjects.size() ==
14815                ExprEvalContexts.back().NumCleanupObjects &&
14816            "Leftover temporaries in function");
14817     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14818     assert(MaybeODRUseExprs.empty() &&
14819            "Leftover expressions for odr-use checking");
14820   }
14821 
14822   if (!IsInstantiation)
14823     PopDeclContext();
14824 
14825   PopFunctionScopeInfo(ActivePolicy, dcl);
14826   // If any errors have occurred, clear out any temporaries that may have
14827   // been leftover. This ensures that these temporaries won't be picked up for
14828   // deletion in some later function.
14829   if (hasUncompilableErrorOccurred()) {
14830     DiscardCleanupsInEvaluationContext();
14831   }
14832 
14833   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14834     auto ES = getEmissionStatus(FD);
14835     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14836         ES == Sema::FunctionEmissionStatus::Unknown)
14837       DeclsToCheckForDeferredDiags.insert(FD);
14838   }
14839 
14840   return dcl;
14841 }
14842 
14843 /// When we finish delayed parsing of an attribute, we must attach it to the
14844 /// relevant Decl.
14845 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14846                                        ParsedAttributes &Attrs) {
14847   // Always attach attributes to the underlying decl.
14848   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14849     D = TD->getTemplatedDecl();
14850   ProcessDeclAttributeList(S, D, Attrs);
14851 
14852   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14853     if (Method->isStatic())
14854       checkThisInStaticMemberFunctionAttributes(Method);
14855 }
14856 
14857 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14858 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14859 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14860                                           IdentifierInfo &II, Scope *S) {
14861   // Find the scope in which the identifier is injected and the corresponding
14862   // DeclContext.
14863   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14864   // In that case, we inject the declaration into the translation unit scope
14865   // instead.
14866   Scope *BlockScope = S;
14867   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14868     BlockScope = BlockScope->getParent();
14869 
14870   Scope *ContextScope = BlockScope;
14871   while (!ContextScope->getEntity())
14872     ContextScope = ContextScope->getParent();
14873   ContextRAII SavedContext(*this, ContextScope->getEntity());
14874 
14875   // Before we produce a declaration for an implicitly defined
14876   // function, see whether there was a locally-scoped declaration of
14877   // this name as a function or variable. If so, use that
14878   // (non-visible) declaration, and complain about it.
14879   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14880   if (ExternCPrev) {
14881     // We still need to inject the function into the enclosing block scope so
14882     // that later (non-call) uses can see it.
14883     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14884 
14885     // C89 footnote 38:
14886     //   If in fact it is not defined as having type "function returning int",
14887     //   the behavior is undefined.
14888     if (!isa<FunctionDecl>(ExternCPrev) ||
14889         !Context.typesAreCompatible(
14890             cast<FunctionDecl>(ExternCPrev)->getType(),
14891             Context.getFunctionNoProtoType(Context.IntTy))) {
14892       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14893           << ExternCPrev << !getLangOpts().C99;
14894       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14895       return ExternCPrev;
14896     }
14897   }
14898 
14899   // Extension in C99.  Legal in C90, but warn about it.
14900   unsigned diag_id;
14901   if (II.getName().startswith("__builtin_"))
14902     diag_id = diag::warn_builtin_unknown;
14903   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14904   else if (getLangOpts().OpenCL)
14905     diag_id = diag::err_opencl_implicit_function_decl;
14906   else if (getLangOpts().C99)
14907     diag_id = diag::ext_implicit_function_decl;
14908   else
14909     diag_id = diag::warn_implicit_function_decl;
14910   Diag(Loc, diag_id) << &II;
14911 
14912   // If we found a prior declaration of this function, don't bother building
14913   // another one. We've already pushed that one into scope, so there's nothing
14914   // more to do.
14915   if (ExternCPrev)
14916     return ExternCPrev;
14917 
14918   // Because typo correction is expensive, only do it if the implicit
14919   // function declaration is going to be treated as an error.
14920   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14921     TypoCorrection Corrected;
14922     DeclFilterCCC<FunctionDecl> CCC{};
14923     if (S && (Corrected =
14924                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14925                               S, nullptr, CCC, CTK_NonError)))
14926       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14927                    /*ErrorRecovery*/false);
14928   }
14929 
14930   // Set a Declarator for the implicit definition: int foo();
14931   const char *Dummy;
14932   AttributeFactory attrFactory;
14933   DeclSpec DS(attrFactory);
14934   unsigned DiagID;
14935   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14936                                   Context.getPrintingPolicy());
14937   (void)Error; // Silence warning.
14938   assert(!Error && "Error setting up implicit decl!");
14939   SourceLocation NoLoc;
14940   Declarator D(DS, DeclaratorContext::Block);
14941   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14942                                              /*IsAmbiguous=*/false,
14943                                              /*LParenLoc=*/NoLoc,
14944                                              /*Params=*/nullptr,
14945                                              /*NumParams=*/0,
14946                                              /*EllipsisLoc=*/NoLoc,
14947                                              /*RParenLoc=*/NoLoc,
14948                                              /*RefQualifierIsLvalueRef=*/true,
14949                                              /*RefQualifierLoc=*/NoLoc,
14950                                              /*MutableLoc=*/NoLoc, EST_None,
14951                                              /*ESpecRange=*/SourceRange(),
14952                                              /*Exceptions=*/nullptr,
14953                                              /*ExceptionRanges=*/nullptr,
14954                                              /*NumExceptions=*/0,
14955                                              /*NoexceptExpr=*/nullptr,
14956                                              /*ExceptionSpecTokens=*/nullptr,
14957                                              /*DeclsInPrototype=*/None, Loc,
14958                                              Loc, D),
14959                 std::move(DS.getAttributes()), SourceLocation());
14960   D.SetIdentifier(&II, Loc);
14961 
14962   // Insert this function into the enclosing block scope.
14963   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14964   FD->setImplicit();
14965 
14966   AddKnownFunctionAttributes(FD);
14967 
14968   return FD;
14969 }
14970 
14971 /// If this function is a C++ replaceable global allocation function
14972 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14973 /// adds any function attributes that we know a priori based on the standard.
14974 ///
14975 /// We need to check for duplicate attributes both here and where user-written
14976 /// attributes are applied to declarations.
14977 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14978     FunctionDecl *FD) {
14979   if (FD->isInvalidDecl())
14980     return;
14981 
14982   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14983       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14984     return;
14985 
14986   Optional<unsigned> AlignmentParam;
14987   bool IsNothrow = false;
14988   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14989     return;
14990 
14991   // C++2a [basic.stc.dynamic.allocation]p4:
14992   //   An allocation function that has a non-throwing exception specification
14993   //   indicates failure by returning a null pointer value. Any other allocation
14994   //   function never returns a null pointer value and indicates failure only by
14995   //   throwing an exception [...]
14996   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14997     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14998 
14999   // C++2a [basic.stc.dynamic.allocation]p2:
15000   //   An allocation function attempts to allocate the requested amount of
15001   //   storage. [...] If the request succeeds, the value returned by a
15002   //   replaceable allocation function is a [...] pointer value p0 different
15003   //   from any previously returned value p1 [...]
15004   //
15005   // However, this particular information is being added in codegen,
15006   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15007 
15008   // C++2a [basic.stc.dynamic.allocation]p2:
15009   //   An allocation function attempts to allocate the requested amount of
15010   //   storage. If it is successful, it returns the address of the start of a
15011   //   block of storage whose length in bytes is at least as large as the
15012   //   requested size.
15013   if (!FD->hasAttr<AllocSizeAttr>()) {
15014     FD->addAttr(AllocSizeAttr::CreateImplicit(
15015         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15016         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15017   }
15018 
15019   // C++2a [basic.stc.dynamic.allocation]p3:
15020   //   For an allocation function [...], the pointer returned on a successful
15021   //   call shall represent the address of storage that is aligned as follows:
15022   //   (3.1) If the allocation function takes an argument of type
15023   //         std​::​align_­val_­t, the storage will have the alignment
15024   //         specified by the value of this argument.
15025   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15026     FD->addAttr(AllocAlignAttr::CreateImplicit(
15027         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15028   }
15029 
15030   // FIXME:
15031   // C++2a [basic.stc.dynamic.allocation]p3:
15032   //   For an allocation function [...], the pointer returned on a successful
15033   //   call shall represent the address of storage that is aligned as follows:
15034   //   (3.2) Otherwise, if the allocation function is named operator new[],
15035   //         the storage is aligned for any object that does not have
15036   //         new-extended alignment ([basic.align]) and is no larger than the
15037   //         requested size.
15038   //   (3.3) Otherwise, the storage is aligned for any object that does not
15039   //         have new-extended alignment and is of the requested size.
15040 }
15041 
15042 /// Adds any function attributes that we know a priori based on
15043 /// the declaration of this function.
15044 ///
15045 /// These attributes can apply both to implicitly-declared builtins
15046 /// (like __builtin___printf_chk) or to library-declared functions
15047 /// like NSLog or printf.
15048 ///
15049 /// We need to check for duplicate attributes both here and where user-written
15050 /// attributes are applied to declarations.
15051 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15052   if (FD->isInvalidDecl())
15053     return;
15054 
15055   // If this is a built-in function, map its builtin attributes to
15056   // actual attributes.
15057   if (unsigned BuiltinID = FD->getBuiltinID()) {
15058     // Handle printf-formatting attributes.
15059     unsigned FormatIdx;
15060     bool HasVAListArg;
15061     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15062       if (!FD->hasAttr<FormatAttr>()) {
15063         const char *fmt = "printf";
15064         unsigned int NumParams = FD->getNumParams();
15065         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15066             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15067           fmt = "NSString";
15068         FD->addAttr(FormatAttr::CreateImplicit(Context,
15069                                                &Context.Idents.get(fmt),
15070                                                FormatIdx+1,
15071                                                HasVAListArg ? 0 : FormatIdx+2,
15072                                                FD->getLocation()));
15073       }
15074     }
15075     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15076                                              HasVAListArg)) {
15077      if (!FD->hasAttr<FormatAttr>())
15078        FD->addAttr(FormatAttr::CreateImplicit(Context,
15079                                               &Context.Idents.get("scanf"),
15080                                               FormatIdx+1,
15081                                               HasVAListArg ? 0 : FormatIdx+2,
15082                                               FD->getLocation()));
15083     }
15084 
15085     // Handle automatically recognized callbacks.
15086     SmallVector<int, 4> Encoding;
15087     if (!FD->hasAttr<CallbackAttr>() &&
15088         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15089       FD->addAttr(CallbackAttr::CreateImplicit(
15090           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15091 
15092     // Mark const if we don't care about errno and that is the only thing
15093     // preventing the function from being const. This allows IRgen to use LLVM
15094     // intrinsics for such functions.
15095     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15096         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15097       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15098 
15099     // We make "fma" on some platforms const because we know it does not set
15100     // errno in those environments even though it could set errno based on the
15101     // C standard.
15102     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15103     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15104         !FD->hasAttr<ConstAttr>()) {
15105       switch (BuiltinID) {
15106       case Builtin::BI__builtin_fma:
15107       case Builtin::BI__builtin_fmaf:
15108       case Builtin::BI__builtin_fmal:
15109       case Builtin::BIfma:
15110       case Builtin::BIfmaf:
15111       case Builtin::BIfmal:
15112         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15113         break;
15114       default:
15115         break;
15116       }
15117     }
15118 
15119     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15120         !FD->hasAttr<ReturnsTwiceAttr>())
15121       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15122                                          FD->getLocation()));
15123     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15124       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15125     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15126       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15127     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15128       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15129     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15130         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15131       // Add the appropriate attribute, depending on the CUDA compilation mode
15132       // and which target the builtin belongs to. For example, during host
15133       // compilation, aux builtins are __device__, while the rest are __host__.
15134       if (getLangOpts().CUDAIsDevice !=
15135           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15136         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15137       else
15138         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15139     }
15140   }
15141 
15142   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15143 
15144   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15145   // throw, add an implicit nothrow attribute to any extern "C" function we come
15146   // across.
15147   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15148       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15149     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15150     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15151       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15152   }
15153 
15154   IdentifierInfo *Name = FD->getIdentifier();
15155   if (!Name)
15156     return;
15157   if ((!getLangOpts().CPlusPlus &&
15158        FD->getDeclContext()->isTranslationUnit()) ||
15159       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15160        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15161        LinkageSpecDecl::lang_c)) {
15162     // Okay: this could be a libc/libm/Objective-C function we know
15163     // about.
15164   } else
15165     return;
15166 
15167   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15168     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15169     // target-specific builtins, perhaps?
15170     if (!FD->hasAttr<FormatAttr>())
15171       FD->addAttr(FormatAttr::CreateImplicit(Context,
15172                                              &Context.Idents.get("printf"), 2,
15173                                              Name->isStr("vasprintf") ? 0 : 3,
15174                                              FD->getLocation()));
15175   }
15176 
15177   if (Name->isStr("__CFStringMakeConstantString")) {
15178     // We already have a __builtin___CFStringMakeConstantString,
15179     // but builds that use -fno-constant-cfstrings don't go through that.
15180     if (!FD->hasAttr<FormatArgAttr>())
15181       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15182                                                 FD->getLocation()));
15183   }
15184 }
15185 
15186 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15187                                     TypeSourceInfo *TInfo) {
15188   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15189   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15190 
15191   if (!TInfo) {
15192     assert(D.isInvalidType() && "no declarator info for valid type");
15193     TInfo = Context.getTrivialTypeSourceInfo(T);
15194   }
15195 
15196   // Scope manipulation handled by caller.
15197   TypedefDecl *NewTD =
15198       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15199                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15200 
15201   // Bail out immediately if we have an invalid declaration.
15202   if (D.isInvalidType()) {
15203     NewTD->setInvalidDecl();
15204     return NewTD;
15205   }
15206 
15207   if (D.getDeclSpec().isModulePrivateSpecified()) {
15208     if (CurContext->isFunctionOrMethod())
15209       Diag(NewTD->getLocation(), diag::err_module_private_local)
15210           << 2 << NewTD
15211           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15212           << FixItHint::CreateRemoval(
15213                  D.getDeclSpec().getModulePrivateSpecLoc());
15214     else
15215       NewTD->setModulePrivate();
15216   }
15217 
15218   // C++ [dcl.typedef]p8:
15219   //   If the typedef declaration defines an unnamed class (or
15220   //   enum), the first typedef-name declared by the declaration
15221   //   to be that class type (or enum type) is used to denote the
15222   //   class type (or enum type) for linkage purposes only.
15223   // We need to check whether the type was declared in the declaration.
15224   switch (D.getDeclSpec().getTypeSpecType()) {
15225   case TST_enum:
15226   case TST_struct:
15227   case TST_interface:
15228   case TST_union:
15229   case TST_class: {
15230     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15231     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15232     break;
15233   }
15234 
15235   default:
15236     break;
15237   }
15238 
15239   return NewTD;
15240 }
15241 
15242 /// Check that this is a valid underlying type for an enum declaration.
15243 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15244   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15245   QualType T = TI->getType();
15246 
15247   if (T->isDependentType())
15248     return false;
15249 
15250   // This doesn't use 'isIntegralType' despite the error message mentioning
15251   // integral type because isIntegralType would also allow enum types in C.
15252   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15253     if (BT->isInteger())
15254       return false;
15255 
15256   if (T->isExtIntType())
15257     return false;
15258 
15259   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15260 }
15261 
15262 /// Check whether this is a valid redeclaration of a previous enumeration.
15263 /// \return true if the redeclaration was invalid.
15264 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15265                                   QualType EnumUnderlyingTy, bool IsFixed,
15266                                   const EnumDecl *Prev) {
15267   if (IsScoped != Prev->isScoped()) {
15268     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15269       << Prev->isScoped();
15270     Diag(Prev->getLocation(), diag::note_previous_declaration);
15271     return true;
15272   }
15273 
15274   if (IsFixed && Prev->isFixed()) {
15275     if (!EnumUnderlyingTy->isDependentType() &&
15276         !Prev->getIntegerType()->isDependentType() &&
15277         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15278                                         Prev->getIntegerType())) {
15279       // TODO: Highlight the underlying type of the redeclaration.
15280       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15281         << EnumUnderlyingTy << Prev->getIntegerType();
15282       Diag(Prev->getLocation(), diag::note_previous_declaration)
15283           << Prev->getIntegerTypeRange();
15284       return true;
15285     }
15286   } else if (IsFixed != Prev->isFixed()) {
15287     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15288       << Prev->isFixed();
15289     Diag(Prev->getLocation(), diag::note_previous_declaration);
15290     return true;
15291   }
15292 
15293   return false;
15294 }
15295 
15296 /// Get diagnostic %select index for tag kind for
15297 /// redeclaration diagnostic message.
15298 /// WARNING: Indexes apply to particular diagnostics only!
15299 ///
15300 /// \returns diagnostic %select index.
15301 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15302   switch (Tag) {
15303   case TTK_Struct: return 0;
15304   case TTK_Interface: return 1;
15305   case TTK_Class:  return 2;
15306   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15307   }
15308 }
15309 
15310 /// Determine if tag kind is a class-key compatible with
15311 /// class for redeclaration (class, struct, or __interface).
15312 ///
15313 /// \returns true iff the tag kind is compatible.
15314 static bool isClassCompatTagKind(TagTypeKind Tag)
15315 {
15316   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15317 }
15318 
15319 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15320                                              TagTypeKind TTK) {
15321   if (isa<TypedefDecl>(PrevDecl))
15322     return NTK_Typedef;
15323   else if (isa<TypeAliasDecl>(PrevDecl))
15324     return NTK_TypeAlias;
15325   else if (isa<ClassTemplateDecl>(PrevDecl))
15326     return NTK_Template;
15327   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15328     return NTK_TypeAliasTemplate;
15329   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15330     return NTK_TemplateTemplateArgument;
15331   switch (TTK) {
15332   case TTK_Struct:
15333   case TTK_Interface:
15334   case TTK_Class:
15335     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15336   case TTK_Union:
15337     return NTK_NonUnion;
15338   case TTK_Enum:
15339     return NTK_NonEnum;
15340   }
15341   llvm_unreachable("invalid TTK");
15342 }
15343 
15344 /// Determine whether a tag with a given kind is acceptable
15345 /// as a redeclaration of the given tag declaration.
15346 ///
15347 /// \returns true if the new tag kind is acceptable, false otherwise.
15348 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15349                                         TagTypeKind NewTag, bool isDefinition,
15350                                         SourceLocation NewTagLoc,
15351                                         const IdentifierInfo *Name) {
15352   // C++ [dcl.type.elab]p3:
15353   //   The class-key or enum keyword present in the
15354   //   elaborated-type-specifier shall agree in kind with the
15355   //   declaration to which the name in the elaborated-type-specifier
15356   //   refers. This rule also applies to the form of
15357   //   elaborated-type-specifier that declares a class-name or
15358   //   friend class since it can be construed as referring to the
15359   //   definition of the class. Thus, in any
15360   //   elaborated-type-specifier, the enum keyword shall be used to
15361   //   refer to an enumeration (7.2), the union class-key shall be
15362   //   used to refer to a union (clause 9), and either the class or
15363   //   struct class-key shall be used to refer to a class (clause 9)
15364   //   declared using the class or struct class-key.
15365   TagTypeKind OldTag = Previous->getTagKind();
15366   if (OldTag != NewTag &&
15367       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15368     return false;
15369 
15370   // Tags are compatible, but we might still want to warn on mismatched tags.
15371   // Non-class tags can't be mismatched at this point.
15372   if (!isClassCompatTagKind(NewTag))
15373     return true;
15374 
15375   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15376   // by our warning analysis. We don't want to warn about mismatches with (eg)
15377   // declarations in system headers that are designed to be specialized, but if
15378   // a user asks us to warn, we should warn if their code contains mismatched
15379   // declarations.
15380   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15381     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15382                                       Loc);
15383   };
15384   if (IsIgnoredLoc(NewTagLoc))
15385     return true;
15386 
15387   auto IsIgnored = [&](const TagDecl *Tag) {
15388     return IsIgnoredLoc(Tag->getLocation());
15389   };
15390   while (IsIgnored(Previous)) {
15391     Previous = Previous->getPreviousDecl();
15392     if (!Previous)
15393       return true;
15394     OldTag = Previous->getTagKind();
15395   }
15396 
15397   bool isTemplate = false;
15398   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15399     isTemplate = Record->getDescribedClassTemplate();
15400 
15401   if (inTemplateInstantiation()) {
15402     if (OldTag != NewTag) {
15403       // In a template instantiation, do not offer fix-its for tag mismatches
15404       // since they usually mess up the template instead of fixing the problem.
15405       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15406         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15407         << getRedeclDiagFromTagKind(OldTag);
15408       // FIXME: Note previous location?
15409     }
15410     return true;
15411   }
15412 
15413   if (isDefinition) {
15414     // On definitions, check all previous tags and issue a fix-it for each
15415     // one that doesn't match the current tag.
15416     if (Previous->getDefinition()) {
15417       // Don't suggest fix-its for redefinitions.
15418       return true;
15419     }
15420 
15421     bool previousMismatch = false;
15422     for (const TagDecl *I : Previous->redecls()) {
15423       if (I->getTagKind() != NewTag) {
15424         // Ignore previous declarations for which the warning was disabled.
15425         if (IsIgnored(I))
15426           continue;
15427 
15428         if (!previousMismatch) {
15429           previousMismatch = true;
15430           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15431             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15432             << getRedeclDiagFromTagKind(I->getTagKind());
15433         }
15434         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15435           << getRedeclDiagFromTagKind(NewTag)
15436           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15437                TypeWithKeyword::getTagTypeKindName(NewTag));
15438       }
15439     }
15440     return true;
15441   }
15442 
15443   // Identify the prevailing tag kind: this is the kind of the definition (if
15444   // there is a non-ignored definition), or otherwise the kind of the prior
15445   // (non-ignored) declaration.
15446   const TagDecl *PrevDef = Previous->getDefinition();
15447   if (PrevDef && IsIgnored(PrevDef))
15448     PrevDef = nullptr;
15449   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15450   if (Redecl->getTagKind() != NewTag) {
15451     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15452       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15453       << getRedeclDiagFromTagKind(OldTag);
15454     Diag(Redecl->getLocation(), diag::note_previous_use);
15455 
15456     // If there is a previous definition, suggest a fix-it.
15457     if (PrevDef) {
15458       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15459         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15460         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15461              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15462     }
15463   }
15464 
15465   return true;
15466 }
15467 
15468 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15469 /// from an outer enclosing namespace or file scope inside a friend declaration.
15470 /// This should provide the commented out code in the following snippet:
15471 ///   namespace N {
15472 ///     struct X;
15473 ///     namespace M {
15474 ///       struct Y { friend struct /*N::*/ X; };
15475 ///     }
15476 ///   }
15477 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15478                                          SourceLocation NameLoc) {
15479   // While the decl is in a namespace, do repeated lookup of that name and see
15480   // if we get the same namespace back.  If we do not, continue until
15481   // translation unit scope, at which point we have a fully qualified NNS.
15482   SmallVector<IdentifierInfo *, 4> Namespaces;
15483   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15484   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15485     // This tag should be declared in a namespace, which can only be enclosed by
15486     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15487     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15488     if (!Namespace || Namespace->isAnonymousNamespace())
15489       return FixItHint();
15490     IdentifierInfo *II = Namespace->getIdentifier();
15491     Namespaces.push_back(II);
15492     NamedDecl *Lookup = SemaRef.LookupSingleName(
15493         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15494     if (Lookup == Namespace)
15495       break;
15496   }
15497 
15498   // Once we have all the namespaces, reverse them to go outermost first, and
15499   // build an NNS.
15500   SmallString<64> Insertion;
15501   llvm::raw_svector_ostream OS(Insertion);
15502   if (DC->isTranslationUnit())
15503     OS << "::";
15504   std::reverse(Namespaces.begin(), Namespaces.end());
15505   for (auto *II : Namespaces)
15506     OS << II->getName() << "::";
15507   return FixItHint::CreateInsertion(NameLoc, Insertion);
15508 }
15509 
15510 /// Determine whether a tag originally declared in context \p OldDC can
15511 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15512 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15513 /// using-declaration).
15514 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15515                                          DeclContext *NewDC) {
15516   OldDC = OldDC->getRedeclContext();
15517   NewDC = NewDC->getRedeclContext();
15518 
15519   if (OldDC->Equals(NewDC))
15520     return true;
15521 
15522   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15523   // encloses the other).
15524   if (S.getLangOpts().MSVCCompat &&
15525       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15526     return true;
15527 
15528   return false;
15529 }
15530 
15531 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15532 /// former case, Name will be non-null.  In the later case, Name will be null.
15533 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15534 /// reference/declaration/definition of a tag.
15535 ///
15536 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15537 /// trailing-type-specifier) other than one in an alias-declaration.
15538 ///
15539 /// \param SkipBody If non-null, will be set to indicate if the caller should
15540 /// skip the definition of this tag and treat it as if it were a declaration.
15541 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15542                      SourceLocation KWLoc, CXXScopeSpec &SS,
15543                      IdentifierInfo *Name, SourceLocation NameLoc,
15544                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15545                      SourceLocation ModulePrivateLoc,
15546                      MultiTemplateParamsArg TemplateParameterLists,
15547                      bool &OwnedDecl, bool &IsDependent,
15548                      SourceLocation ScopedEnumKWLoc,
15549                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15550                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15551                      SkipBodyInfo *SkipBody) {
15552   // If this is not a definition, it must have a name.
15553   IdentifierInfo *OrigName = Name;
15554   assert((Name != nullptr || TUK == TUK_Definition) &&
15555          "Nameless record must be a definition!");
15556   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15557 
15558   OwnedDecl = false;
15559   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15560   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15561 
15562   // FIXME: Check member specializations more carefully.
15563   bool isMemberSpecialization = false;
15564   bool Invalid = false;
15565 
15566   // We only need to do this matching if we have template parameters
15567   // or a scope specifier, which also conveniently avoids this work
15568   // for non-C++ cases.
15569   if (TemplateParameterLists.size() > 0 ||
15570       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15571     if (TemplateParameterList *TemplateParams =
15572             MatchTemplateParametersToScopeSpecifier(
15573                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15574                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15575       if (Kind == TTK_Enum) {
15576         Diag(KWLoc, diag::err_enum_template);
15577         return nullptr;
15578       }
15579 
15580       if (TemplateParams->size() > 0) {
15581         // This is a declaration or definition of a class template (which may
15582         // be a member of another template).
15583 
15584         if (Invalid)
15585           return nullptr;
15586 
15587         OwnedDecl = false;
15588         DeclResult Result = CheckClassTemplate(
15589             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15590             AS, ModulePrivateLoc,
15591             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15592             TemplateParameterLists.data(), SkipBody);
15593         return Result.get();
15594       } else {
15595         // The "template<>" header is extraneous.
15596         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15597           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15598         isMemberSpecialization = true;
15599       }
15600     }
15601 
15602     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15603         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15604       return nullptr;
15605   }
15606 
15607   // Figure out the underlying type if this a enum declaration. We need to do
15608   // this early, because it's needed to detect if this is an incompatible
15609   // redeclaration.
15610   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15611   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15612 
15613   if (Kind == TTK_Enum) {
15614     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15615       // No underlying type explicitly specified, or we failed to parse the
15616       // type, default to int.
15617       EnumUnderlying = Context.IntTy.getTypePtr();
15618     } else if (UnderlyingType.get()) {
15619       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15620       // integral type; any cv-qualification is ignored.
15621       TypeSourceInfo *TI = nullptr;
15622       GetTypeFromParser(UnderlyingType.get(), &TI);
15623       EnumUnderlying = TI;
15624 
15625       if (CheckEnumUnderlyingType(TI))
15626         // Recover by falling back to int.
15627         EnumUnderlying = Context.IntTy.getTypePtr();
15628 
15629       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15630                                           UPPC_FixedUnderlyingType))
15631         EnumUnderlying = Context.IntTy.getTypePtr();
15632 
15633     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15634       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15635       // of 'int'. However, if this is an unfixed forward declaration, don't set
15636       // the underlying type unless the user enables -fms-compatibility. This
15637       // makes unfixed forward declared enums incomplete and is more conforming.
15638       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15639         EnumUnderlying = Context.IntTy.getTypePtr();
15640     }
15641   }
15642 
15643   DeclContext *SearchDC = CurContext;
15644   DeclContext *DC = CurContext;
15645   bool isStdBadAlloc = false;
15646   bool isStdAlignValT = false;
15647 
15648   RedeclarationKind Redecl = forRedeclarationInCurContext();
15649   if (TUK == TUK_Friend || TUK == TUK_Reference)
15650     Redecl = NotForRedeclaration;
15651 
15652   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15653   /// implemented asks for structural equivalence checking, the returned decl
15654   /// here is passed back to the parser, allowing the tag body to be parsed.
15655   auto createTagFromNewDecl = [&]() -> TagDecl * {
15656     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15657     // If there is an identifier, use the location of the identifier as the
15658     // location of the decl, otherwise use the location of the struct/union
15659     // keyword.
15660     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15661     TagDecl *New = nullptr;
15662 
15663     if (Kind == TTK_Enum) {
15664       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15665                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15666       // If this is an undefined enum, bail.
15667       if (TUK != TUK_Definition && !Invalid)
15668         return nullptr;
15669       if (EnumUnderlying) {
15670         EnumDecl *ED = cast<EnumDecl>(New);
15671         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15672           ED->setIntegerTypeSourceInfo(TI);
15673         else
15674           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15675         ED->setPromotionType(ED->getIntegerType());
15676       }
15677     } else { // struct/union
15678       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15679                                nullptr);
15680     }
15681 
15682     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15683       // Add alignment attributes if necessary; these attributes are checked
15684       // when the ASTContext lays out the structure.
15685       //
15686       // It is important for implementing the correct semantics that this
15687       // happen here (in ActOnTag). The #pragma pack stack is
15688       // maintained as a result of parser callbacks which can occur at
15689       // many points during the parsing of a struct declaration (because
15690       // the #pragma tokens are effectively skipped over during the
15691       // parsing of the struct).
15692       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15693         AddAlignmentAttributesForRecord(RD);
15694         AddMsStructLayoutForRecord(RD);
15695       }
15696     }
15697     New->setLexicalDeclContext(CurContext);
15698     return New;
15699   };
15700 
15701   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15702   if (Name && SS.isNotEmpty()) {
15703     // We have a nested-name tag ('struct foo::bar').
15704 
15705     // Check for invalid 'foo::'.
15706     if (SS.isInvalid()) {
15707       Name = nullptr;
15708       goto CreateNewDecl;
15709     }
15710 
15711     // If this is a friend or a reference to a class in a dependent
15712     // context, don't try to make a decl for it.
15713     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15714       DC = computeDeclContext(SS, false);
15715       if (!DC) {
15716         IsDependent = true;
15717         return nullptr;
15718       }
15719     } else {
15720       DC = computeDeclContext(SS, true);
15721       if (!DC) {
15722         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15723           << SS.getRange();
15724         return nullptr;
15725       }
15726     }
15727 
15728     if (RequireCompleteDeclContext(SS, DC))
15729       return nullptr;
15730 
15731     SearchDC = DC;
15732     // Look-up name inside 'foo::'.
15733     LookupQualifiedName(Previous, DC);
15734 
15735     if (Previous.isAmbiguous())
15736       return nullptr;
15737 
15738     if (Previous.empty()) {
15739       // Name lookup did not find anything. However, if the
15740       // nested-name-specifier refers to the current instantiation,
15741       // and that current instantiation has any dependent base
15742       // classes, we might find something at instantiation time: treat
15743       // this as a dependent elaborated-type-specifier.
15744       // But this only makes any sense for reference-like lookups.
15745       if (Previous.wasNotFoundInCurrentInstantiation() &&
15746           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15747         IsDependent = true;
15748         return nullptr;
15749       }
15750 
15751       // A tag 'foo::bar' must already exist.
15752       Diag(NameLoc, diag::err_not_tag_in_scope)
15753         << Kind << Name << DC << SS.getRange();
15754       Name = nullptr;
15755       Invalid = true;
15756       goto CreateNewDecl;
15757     }
15758   } else if (Name) {
15759     // C++14 [class.mem]p14:
15760     //   If T is the name of a class, then each of the following shall have a
15761     //   name different from T:
15762     //    -- every member of class T that is itself a type
15763     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15764         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15765       return nullptr;
15766 
15767     // If this is a named struct, check to see if there was a previous forward
15768     // declaration or definition.
15769     // FIXME: We're looking into outer scopes here, even when we
15770     // shouldn't be. Doing so can result in ambiguities that we
15771     // shouldn't be diagnosing.
15772     LookupName(Previous, S);
15773 
15774     // When declaring or defining a tag, ignore ambiguities introduced
15775     // by types using'ed into this scope.
15776     if (Previous.isAmbiguous() &&
15777         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15778       LookupResult::Filter F = Previous.makeFilter();
15779       while (F.hasNext()) {
15780         NamedDecl *ND = F.next();
15781         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15782                 SearchDC->getRedeclContext()))
15783           F.erase();
15784       }
15785       F.done();
15786     }
15787 
15788     // C++11 [namespace.memdef]p3:
15789     //   If the name in a friend declaration is neither qualified nor
15790     //   a template-id and the declaration is a function or an
15791     //   elaborated-type-specifier, the lookup to determine whether
15792     //   the entity has been previously declared shall not consider
15793     //   any scopes outside the innermost enclosing namespace.
15794     //
15795     // MSVC doesn't implement the above rule for types, so a friend tag
15796     // declaration may be a redeclaration of a type declared in an enclosing
15797     // scope.  They do implement this rule for friend functions.
15798     //
15799     // Does it matter that this should be by scope instead of by
15800     // semantic context?
15801     if (!Previous.empty() && TUK == TUK_Friend) {
15802       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15803       LookupResult::Filter F = Previous.makeFilter();
15804       bool FriendSawTagOutsideEnclosingNamespace = false;
15805       while (F.hasNext()) {
15806         NamedDecl *ND = F.next();
15807         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15808         if (DC->isFileContext() &&
15809             !EnclosingNS->Encloses(ND->getDeclContext())) {
15810           if (getLangOpts().MSVCCompat)
15811             FriendSawTagOutsideEnclosingNamespace = true;
15812           else
15813             F.erase();
15814         }
15815       }
15816       F.done();
15817 
15818       // Diagnose this MSVC extension in the easy case where lookup would have
15819       // unambiguously found something outside the enclosing namespace.
15820       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15821         NamedDecl *ND = Previous.getFoundDecl();
15822         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15823             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15824       }
15825     }
15826 
15827     // Note:  there used to be some attempt at recovery here.
15828     if (Previous.isAmbiguous())
15829       return nullptr;
15830 
15831     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15832       // FIXME: This makes sure that we ignore the contexts associated
15833       // with C structs, unions, and enums when looking for a matching
15834       // tag declaration or definition. See the similar lookup tweak
15835       // in Sema::LookupName; is there a better way to deal with this?
15836       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15837         SearchDC = SearchDC->getParent();
15838     }
15839   }
15840 
15841   if (Previous.isSingleResult() &&
15842       Previous.getFoundDecl()->isTemplateParameter()) {
15843     // Maybe we will complain about the shadowed template parameter.
15844     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15845     // Just pretend that we didn't see the previous declaration.
15846     Previous.clear();
15847   }
15848 
15849   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15850       DC->Equals(getStdNamespace())) {
15851     if (Name->isStr("bad_alloc")) {
15852       // This is a declaration of or a reference to "std::bad_alloc".
15853       isStdBadAlloc = true;
15854 
15855       // If std::bad_alloc has been implicitly declared (but made invisible to
15856       // name lookup), fill in this implicit declaration as the previous
15857       // declaration, so that the declarations get chained appropriately.
15858       if (Previous.empty() && StdBadAlloc)
15859         Previous.addDecl(getStdBadAlloc());
15860     } else if (Name->isStr("align_val_t")) {
15861       isStdAlignValT = true;
15862       if (Previous.empty() && StdAlignValT)
15863         Previous.addDecl(getStdAlignValT());
15864     }
15865   }
15866 
15867   // If we didn't find a previous declaration, and this is a reference
15868   // (or friend reference), move to the correct scope.  In C++, we
15869   // also need to do a redeclaration lookup there, just in case
15870   // there's a shadow friend decl.
15871   if (Name && Previous.empty() &&
15872       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15873     if (Invalid) goto CreateNewDecl;
15874     assert(SS.isEmpty());
15875 
15876     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15877       // C++ [basic.scope.pdecl]p5:
15878       //   -- for an elaborated-type-specifier of the form
15879       //
15880       //          class-key identifier
15881       //
15882       //      if the elaborated-type-specifier is used in the
15883       //      decl-specifier-seq or parameter-declaration-clause of a
15884       //      function defined in namespace scope, the identifier is
15885       //      declared as a class-name in the namespace that contains
15886       //      the declaration; otherwise, except as a friend
15887       //      declaration, the identifier is declared in the smallest
15888       //      non-class, non-function-prototype scope that contains the
15889       //      declaration.
15890       //
15891       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15892       // C structs and unions.
15893       //
15894       // It is an error in C++ to declare (rather than define) an enum
15895       // type, including via an elaborated type specifier.  We'll
15896       // diagnose that later; for now, declare the enum in the same
15897       // scope as we would have picked for any other tag type.
15898       //
15899       // GNU C also supports this behavior as part of its incomplete
15900       // enum types extension, while GNU C++ does not.
15901       //
15902       // Find the context where we'll be declaring the tag.
15903       // FIXME: We would like to maintain the current DeclContext as the
15904       // lexical context,
15905       SearchDC = getTagInjectionContext(SearchDC);
15906 
15907       // Find the scope where we'll be declaring the tag.
15908       S = getTagInjectionScope(S, getLangOpts());
15909     } else {
15910       assert(TUK == TUK_Friend);
15911       // C++ [namespace.memdef]p3:
15912       //   If a friend declaration in a non-local class first declares a
15913       //   class or function, the friend class or function is a member of
15914       //   the innermost enclosing namespace.
15915       SearchDC = SearchDC->getEnclosingNamespaceContext();
15916     }
15917 
15918     // In C++, we need to do a redeclaration lookup to properly
15919     // diagnose some problems.
15920     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15921     // hidden declaration so that we don't get ambiguity errors when using a
15922     // type declared by an elaborated-type-specifier.  In C that is not correct
15923     // and we should instead merge compatible types found by lookup.
15924     if (getLangOpts().CPlusPlus) {
15925       // FIXME: This can perform qualified lookups into function contexts,
15926       // which are meaningless.
15927       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15928       LookupQualifiedName(Previous, SearchDC);
15929     } else {
15930       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15931       LookupName(Previous, S);
15932     }
15933   }
15934 
15935   // If we have a known previous declaration to use, then use it.
15936   if (Previous.empty() && SkipBody && SkipBody->Previous)
15937     Previous.addDecl(SkipBody->Previous);
15938 
15939   if (!Previous.empty()) {
15940     NamedDecl *PrevDecl = Previous.getFoundDecl();
15941     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15942 
15943     // It's okay to have a tag decl in the same scope as a typedef
15944     // which hides a tag decl in the same scope.  Finding this
15945     // insanity with a redeclaration lookup can only actually happen
15946     // in C++.
15947     //
15948     // This is also okay for elaborated-type-specifiers, which is
15949     // technically forbidden by the current standard but which is
15950     // okay according to the likely resolution of an open issue;
15951     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15952     if (getLangOpts().CPlusPlus) {
15953       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15954         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15955           TagDecl *Tag = TT->getDecl();
15956           if (Tag->getDeclName() == Name &&
15957               Tag->getDeclContext()->getRedeclContext()
15958                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15959             PrevDecl = Tag;
15960             Previous.clear();
15961             Previous.addDecl(Tag);
15962             Previous.resolveKind();
15963           }
15964         }
15965       }
15966     }
15967 
15968     // If this is a redeclaration of a using shadow declaration, it must
15969     // declare a tag in the same context. In MSVC mode, we allow a
15970     // redefinition if either context is within the other.
15971     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15972       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15973       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15974           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15975           !(OldTag && isAcceptableTagRedeclContext(
15976                           *this, OldTag->getDeclContext(), SearchDC))) {
15977         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15978         Diag(Shadow->getTargetDecl()->getLocation(),
15979              diag::note_using_decl_target);
15980         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15981             << 0;
15982         // Recover by ignoring the old declaration.
15983         Previous.clear();
15984         goto CreateNewDecl;
15985       }
15986     }
15987 
15988     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15989       // If this is a use of a previous tag, or if the tag is already declared
15990       // in the same scope (so that the definition/declaration completes or
15991       // rementions the tag), reuse the decl.
15992       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15993           isDeclInScope(DirectPrevDecl, SearchDC, S,
15994                         SS.isNotEmpty() || isMemberSpecialization)) {
15995         // Make sure that this wasn't declared as an enum and now used as a
15996         // struct or something similar.
15997         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15998                                           TUK == TUK_Definition, KWLoc,
15999                                           Name)) {
16000           bool SafeToContinue
16001             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16002                Kind != TTK_Enum);
16003           if (SafeToContinue)
16004             Diag(KWLoc, diag::err_use_with_wrong_tag)
16005               << Name
16006               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16007                                               PrevTagDecl->getKindName());
16008           else
16009             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16010           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16011 
16012           if (SafeToContinue)
16013             Kind = PrevTagDecl->getTagKind();
16014           else {
16015             // Recover by making this an anonymous redefinition.
16016             Name = nullptr;
16017             Previous.clear();
16018             Invalid = true;
16019           }
16020         }
16021 
16022         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16023           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16024           if (TUK == TUK_Reference || TUK == TUK_Friend)
16025             return PrevTagDecl;
16026 
16027           QualType EnumUnderlyingTy;
16028           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16029             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16030           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16031             EnumUnderlyingTy = QualType(T, 0);
16032 
16033           // All conflicts with previous declarations are recovered by
16034           // returning the previous declaration, unless this is a definition,
16035           // in which case we want the caller to bail out.
16036           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16037                                      ScopedEnum, EnumUnderlyingTy,
16038                                      IsFixed, PrevEnum))
16039             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16040         }
16041 
16042         // C++11 [class.mem]p1:
16043         //   A member shall not be declared twice in the member-specification,
16044         //   except that a nested class or member class template can be declared
16045         //   and then later defined.
16046         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16047             S->isDeclScope(PrevDecl)) {
16048           Diag(NameLoc, diag::ext_member_redeclared);
16049           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16050         }
16051 
16052         if (!Invalid) {
16053           // If this is a use, just return the declaration we found, unless
16054           // we have attributes.
16055           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16056             if (!Attrs.empty()) {
16057               // FIXME: Diagnose these attributes. For now, we create a new
16058               // declaration to hold them.
16059             } else if (TUK == TUK_Reference &&
16060                        (PrevTagDecl->getFriendObjectKind() ==
16061                             Decl::FOK_Undeclared ||
16062                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16063                        SS.isEmpty()) {
16064               // This declaration is a reference to an existing entity, but
16065               // has different visibility from that entity: it either makes
16066               // a friend visible or it makes a type visible in a new module.
16067               // In either case, create a new declaration. We only do this if
16068               // the declaration would have meant the same thing if no prior
16069               // declaration were found, that is, if it was found in the same
16070               // scope where we would have injected a declaration.
16071               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16072                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16073                 return PrevTagDecl;
16074               // This is in the injected scope, create a new declaration in
16075               // that scope.
16076               S = getTagInjectionScope(S, getLangOpts());
16077             } else {
16078               return PrevTagDecl;
16079             }
16080           }
16081 
16082           // Diagnose attempts to redefine a tag.
16083           if (TUK == TUK_Definition) {
16084             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16085               // If we're defining a specialization and the previous definition
16086               // is from an implicit instantiation, don't emit an error
16087               // here; we'll catch this in the general case below.
16088               bool IsExplicitSpecializationAfterInstantiation = false;
16089               if (isMemberSpecialization) {
16090                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16091                   IsExplicitSpecializationAfterInstantiation =
16092                     RD->getTemplateSpecializationKind() !=
16093                     TSK_ExplicitSpecialization;
16094                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16095                   IsExplicitSpecializationAfterInstantiation =
16096                     ED->getTemplateSpecializationKind() !=
16097                     TSK_ExplicitSpecialization;
16098               }
16099 
16100               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16101               // not keep more that one definition around (merge them). However,
16102               // ensure the decl passes the structural compatibility check in
16103               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16104               NamedDecl *Hidden = nullptr;
16105               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16106                 // There is a definition of this tag, but it is not visible. We
16107                 // explicitly make use of C++'s one definition rule here, and
16108                 // assume that this definition is identical to the hidden one
16109                 // we already have. Make the existing definition visible and
16110                 // use it in place of this one.
16111                 if (!getLangOpts().CPlusPlus) {
16112                   // Postpone making the old definition visible until after we
16113                   // complete parsing the new one and do the structural
16114                   // comparison.
16115                   SkipBody->CheckSameAsPrevious = true;
16116                   SkipBody->New = createTagFromNewDecl();
16117                   SkipBody->Previous = Def;
16118                   return Def;
16119                 } else {
16120                   SkipBody->ShouldSkip = true;
16121                   SkipBody->Previous = Def;
16122                   makeMergedDefinitionVisible(Hidden);
16123                   // Carry on and handle it like a normal definition. We'll
16124                   // skip starting the definitiion later.
16125                 }
16126               } else if (!IsExplicitSpecializationAfterInstantiation) {
16127                 // A redeclaration in function prototype scope in C isn't
16128                 // visible elsewhere, so merely issue a warning.
16129                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16130                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16131                 else
16132                   Diag(NameLoc, diag::err_redefinition) << Name;
16133                 notePreviousDefinition(Def,
16134                                        NameLoc.isValid() ? NameLoc : KWLoc);
16135                 // If this is a redefinition, recover by making this
16136                 // struct be anonymous, which will make any later
16137                 // references get the previous definition.
16138                 Name = nullptr;
16139                 Previous.clear();
16140                 Invalid = true;
16141               }
16142             } else {
16143               // If the type is currently being defined, complain
16144               // about a nested redefinition.
16145               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16146               if (TD->isBeingDefined()) {
16147                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16148                 Diag(PrevTagDecl->getLocation(),
16149                      diag::note_previous_definition);
16150                 Name = nullptr;
16151                 Previous.clear();
16152                 Invalid = true;
16153               }
16154             }
16155 
16156             // Okay, this is definition of a previously declared or referenced
16157             // tag. We're going to create a new Decl for it.
16158           }
16159 
16160           // Okay, we're going to make a redeclaration.  If this is some kind
16161           // of reference, make sure we build the redeclaration in the same DC
16162           // as the original, and ignore the current access specifier.
16163           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16164             SearchDC = PrevTagDecl->getDeclContext();
16165             AS = AS_none;
16166           }
16167         }
16168         // If we get here we have (another) forward declaration or we
16169         // have a definition.  Just create a new decl.
16170 
16171       } else {
16172         // If we get here, this is a definition of a new tag type in a nested
16173         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16174         // new decl/type.  We set PrevDecl to NULL so that the entities
16175         // have distinct types.
16176         Previous.clear();
16177       }
16178       // If we get here, we're going to create a new Decl. If PrevDecl
16179       // is non-NULL, it's a definition of the tag declared by
16180       // PrevDecl. If it's NULL, we have a new definition.
16181 
16182     // Otherwise, PrevDecl is not a tag, but was found with tag
16183     // lookup.  This is only actually possible in C++, where a few
16184     // things like templates still live in the tag namespace.
16185     } else {
16186       // Use a better diagnostic if an elaborated-type-specifier
16187       // found the wrong kind of type on the first
16188       // (non-redeclaration) lookup.
16189       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16190           !Previous.isForRedeclaration()) {
16191         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16192         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16193                                                        << Kind;
16194         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16195         Invalid = true;
16196 
16197       // Otherwise, only diagnose if the declaration is in scope.
16198       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16199                                 SS.isNotEmpty() || isMemberSpecialization)) {
16200         // do nothing
16201 
16202       // Diagnose implicit declarations introduced by elaborated types.
16203       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16204         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16205         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16206         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16207         Invalid = true;
16208 
16209       // Otherwise it's a declaration.  Call out a particularly common
16210       // case here.
16211       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16212         unsigned Kind = 0;
16213         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16214         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16215           << Name << Kind << TND->getUnderlyingType();
16216         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16217         Invalid = true;
16218 
16219       // Otherwise, diagnose.
16220       } else {
16221         // The tag name clashes with something else in the target scope,
16222         // issue an error and recover by making this tag be anonymous.
16223         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16224         notePreviousDefinition(PrevDecl, NameLoc);
16225         Name = nullptr;
16226         Invalid = true;
16227       }
16228 
16229       // The existing declaration isn't relevant to us; we're in a
16230       // new scope, so clear out the previous declaration.
16231       Previous.clear();
16232     }
16233   }
16234 
16235 CreateNewDecl:
16236 
16237   TagDecl *PrevDecl = nullptr;
16238   if (Previous.isSingleResult())
16239     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16240 
16241   // If there is an identifier, use the location of the identifier as the
16242   // location of the decl, otherwise use the location of the struct/union
16243   // keyword.
16244   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16245 
16246   // Otherwise, create a new declaration. If there is a previous
16247   // declaration of the same entity, the two will be linked via
16248   // PrevDecl.
16249   TagDecl *New;
16250 
16251   if (Kind == TTK_Enum) {
16252     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16253     // enum X { A, B, C } D;    D should chain to X.
16254     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16255                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16256                            ScopedEnumUsesClassTag, IsFixed);
16257 
16258     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16259       StdAlignValT = cast<EnumDecl>(New);
16260 
16261     // If this is an undefined enum, warn.
16262     if (TUK != TUK_Definition && !Invalid) {
16263       TagDecl *Def;
16264       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16265         // C++0x: 7.2p2: opaque-enum-declaration.
16266         // Conflicts are diagnosed above. Do nothing.
16267       }
16268       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16269         Diag(Loc, diag::ext_forward_ref_enum_def)
16270           << New;
16271         Diag(Def->getLocation(), diag::note_previous_definition);
16272       } else {
16273         unsigned DiagID = diag::ext_forward_ref_enum;
16274         if (getLangOpts().MSVCCompat)
16275           DiagID = diag::ext_ms_forward_ref_enum;
16276         else if (getLangOpts().CPlusPlus)
16277           DiagID = diag::err_forward_ref_enum;
16278         Diag(Loc, DiagID);
16279       }
16280     }
16281 
16282     if (EnumUnderlying) {
16283       EnumDecl *ED = cast<EnumDecl>(New);
16284       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16285         ED->setIntegerTypeSourceInfo(TI);
16286       else
16287         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16288       ED->setPromotionType(ED->getIntegerType());
16289       assert(ED->isComplete() && "enum with type should be complete");
16290     }
16291   } else {
16292     // struct/union/class
16293 
16294     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16295     // struct X { int A; } D;    D should chain to X.
16296     if (getLangOpts().CPlusPlus) {
16297       // FIXME: Look for a way to use RecordDecl for simple structs.
16298       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16299                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16300 
16301       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16302         StdBadAlloc = cast<CXXRecordDecl>(New);
16303     } else
16304       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16305                                cast_or_null<RecordDecl>(PrevDecl));
16306   }
16307 
16308   // C++11 [dcl.type]p3:
16309   //   A type-specifier-seq shall not define a class or enumeration [...].
16310   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16311       TUK == TUK_Definition) {
16312     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16313       << Context.getTagDeclType(New);
16314     Invalid = true;
16315   }
16316 
16317   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16318       DC->getDeclKind() == Decl::Enum) {
16319     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16320       << Context.getTagDeclType(New);
16321     Invalid = true;
16322   }
16323 
16324   // Maybe add qualifier info.
16325   if (SS.isNotEmpty()) {
16326     if (SS.isSet()) {
16327       // If this is either a declaration or a definition, check the
16328       // nested-name-specifier against the current context.
16329       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16330           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16331                                        isMemberSpecialization))
16332         Invalid = true;
16333 
16334       New->setQualifierInfo(SS.getWithLocInContext(Context));
16335       if (TemplateParameterLists.size() > 0) {
16336         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16337       }
16338     }
16339     else
16340       Invalid = true;
16341   }
16342 
16343   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16344     // Add alignment attributes if necessary; these attributes are checked when
16345     // the ASTContext lays out the structure.
16346     //
16347     // It is important for implementing the correct semantics that this
16348     // happen here (in ActOnTag). The #pragma pack stack is
16349     // maintained as a result of parser callbacks which can occur at
16350     // many points during the parsing of a struct declaration (because
16351     // the #pragma tokens are effectively skipped over during the
16352     // parsing of the struct).
16353     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16354       AddAlignmentAttributesForRecord(RD);
16355       AddMsStructLayoutForRecord(RD);
16356     }
16357   }
16358 
16359   if (ModulePrivateLoc.isValid()) {
16360     if (isMemberSpecialization)
16361       Diag(New->getLocation(), diag::err_module_private_specialization)
16362         << 2
16363         << FixItHint::CreateRemoval(ModulePrivateLoc);
16364     // __module_private__ does not apply to local classes. However, we only
16365     // diagnose this as an error when the declaration specifiers are
16366     // freestanding. Here, we just ignore the __module_private__.
16367     else if (!SearchDC->isFunctionOrMethod())
16368       New->setModulePrivate();
16369   }
16370 
16371   // If this is a specialization of a member class (of a class template),
16372   // check the specialization.
16373   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16374     Invalid = true;
16375 
16376   // If we're declaring or defining a tag in function prototype scope in C,
16377   // note that this type can only be used within the function and add it to
16378   // the list of decls to inject into the function definition scope.
16379   if ((Name || Kind == TTK_Enum) &&
16380       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16381     if (getLangOpts().CPlusPlus) {
16382       // C++ [dcl.fct]p6:
16383       //   Types shall not be defined in return or parameter types.
16384       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16385         Diag(Loc, diag::err_type_defined_in_param_type)
16386             << Name;
16387         Invalid = true;
16388       }
16389     } else if (!PrevDecl) {
16390       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16391     }
16392   }
16393 
16394   if (Invalid)
16395     New->setInvalidDecl();
16396 
16397   // Set the lexical context. If the tag has a C++ scope specifier, the
16398   // lexical context will be different from the semantic context.
16399   New->setLexicalDeclContext(CurContext);
16400 
16401   // Mark this as a friend decl if applicable.
16402   // In Microsoft mode, a friend declaration also acts as a forward
16403   // declaration so we always pass true to setObjectOfFriendDecl to make
16404   // the tag name visible.
16405   if (TUK == TUK_Friend)
16406     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16407 
16408   // Set the access specifier.
16409   if (!Invalid && SearchDC->isRecord())
16410     SetMemberAccessSpecifier(New, PrevDecl, AS);
16411 
16412   if (PrevDecl)
16413     CheckRedeclarationModuleOwnership(New, PrevDecl);
16414 
16415   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16416     New->startDefinition();
16417 
16418   ProcessDeclAttributeList(S, New, Attrs);
16419   AddPragmaAttributes(S, New);
16420 
16421   // If this has an identifier, add it to the scope stack.
16422   if (TUK == TUK_Friend) {
16423     // We might be replacing an existing declaration in the lookup tables;
16424     // if so, borrow its access specifier.
16425     if (PrevDecl)
16426       New->setAccess(PrevDecl->getAccess());
16427 
16428     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16429     DC->makeDeclVisibleInContext(New);
16430     if (Name) // can be null along some error paths
16431       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16432         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16433   } else if (Name) {
16434     S = getNonFieldDeclScope(S);
16435     PushOnScopeChains(New, S, true);
16436   } else {
16437     CurContext->addDecl(New);
16438   }
16439 
16440   // If this is the C FILE type, notify the AST context.
16441   if (IdentifierInfo *II = New->getIdentifier())
16442     if (!New->isInvalidDecl() &&
16443         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16444         II->isStr("FILE"))
16445       Context.setFILEDecl(New);
16446 
16447   if (PrevDecl)
16448     mergeDeclAttributes(New, PrevDecl);
16449 
16450   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16451     inferGslOwnerPointerAttribute(CXXRD);
16452 
16453   // If there's a #pragma GCC visibility in scope, set the visibility of this
16454   // record.
16455   AddPushedVisibilityAttribute(New);
16456 
16457   if (isMemberSpecialization && !New->isInvalidDecl())
16458     CompleteMemberSpecialization(New, Previous);
16459 
16460   OwnedDecl = true;
16461   // In C++, don't return an invalid declaration. We can't recover well from
16462   // the cases where we make the type anonymous.
16463   if (Invalid && getLangOpts().CPlusPlus) {
16464     if (New->isBeingDefined())
16465       if (auto RD = dyn_cast<RecordDecl>(New))
16466         RD->completeDefinition();
16467     return nullptr;
16468   } else if (SkipBody && SkipBody->ShouldSkip) {
16469     return SkipBody->Previous;
16470   } else {
16471     return New;
16472   }
16473 }
16474 
16475 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16476   AdjustDeclIfTemplate(TagD);
16477   TagDecl *Tag = cast<TagDecl>(TagD);
16478 
16479   // Enter the tag context.
16480   PushDeclContext(S, Tag);
16481 
16482   ActOnDocumentableDecl(TagD);
16483 
16484   // If there's a #pragma GCC visibility in scope, set the visibility of this
16485   // record.
16486   AddPushedVisibilityAttribute(Tag);
16487 }
16488 
16489 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16490                                     SkipBodyInfo &SkipBody) {
16491   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16492     return false;
16493 
16494   // Make the previous decl visible.
16495   makeMergedDefinitionVisible(SkipBody.Previous);
16496   return true;
16497 }
16498 
16499 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16500   assert(isa<ObjCContainerDecl>(IDecl) &&
16501          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16502   DeclContext *OCD = cast<DeclContext>(IDecl);
16503   assert(OCD->getLexicalParent() == CurContext &&
16504       "The next DeclContext should be lexically contained in the current one.");
16505   CurContext = OCD;
16506   return IDecl;
16507 }
16508 
16509 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16510                                            SourceLocation FinalLoc,
16511                                            bool IsFinalSpelledSealed,
16512                                            bool IsAbstract,
16513                                            SourceLocation LBraceLoc) {
16514   AdjustDeclIfTemplate(TagD);
16515   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16516 
16517   FieldCollector->StartClass();
16518 
16519   if (!Record->getIdentifier())
16520     return;
16521 
16522   if (IsAbstract)
16523     Record->markAbstract();
16524 
16525   if (FinalLoc.isValid()) {
16526     Record->addAttr(FinalAttr::Create(
16527         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16528         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16529   }
16530   // C++ [class]p2:
16531   //   [...] The class-name is also inserted into the scope of the
16532   //   class itself; this is known as the injected-class-name. For
16533   //   purposes of access checking, the injected-class-name is treated
16534   //   as if it were a public member name.
16535   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16536       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16537       Record->getLocation(), Record->getIdentifier(),
16538       /*PrevDecl=*/nullptr,
16539       /*DelayTypeCreation=*/true);
16540   Context.getTypeDeclType(InjectedClassName, Record);
16541   InjectedClassName->setImplicit();
16542   InjectedClassName->setAccess(AS_public);
16543   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16544       InjectedClassName->setDescribedClassTemplate(Template);
16545   PushOnScopeChains(InjectedClassName, S);
16546   assert(InjectedClassName->isInjectedClassName() &&
16547          "Broken injected-class-name");
16548 }
16549 
16550 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16551                                     SourceRange BraceRange) {
16552   AdjustDeclIfTemplate(TagD);
16553   TagDecl *Tag = cast<TagDecl>(TagD);
16554   Tag->setBraceRange(BraceRange);
16555 
16556   // Make sure we "complete" the definition even it is invalid.
16557   if (Tag->isBeingDefined()) {
16558     assert(Tag->isInvalidDecl() && "We should already have completed it");
16559     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16560       RD->completeDefinition();
16561   }
16562 
16563   if (isa<CXXRecordDecl>(Tag)) {
16564     FieldCollector->FinishClass();
16565   }
16566 
16567   // Exit this scope of this tag's definition.
16568   PopDeclContext();
16569 
16570   if (getCurLexicalContext()->isObjCContainer() &&
16571       Tag->getDeclContext()->isFileContext())
16572     Tag->setTopLevelDeclInObjCContainer();
16573 
16574   // Notify the consumer that we've defined a tag.
16575   if (!Tag->isInvalidDecl())
16576     Consumer.HandleTagDeclDefinition(Tag);
16577 }
16578 
16579 void Sema::ActOnObjCContainerFinishDefinition() {
16580   // Exit this scope of this interface definition.
16581   PopDeclContext();
16582 }
16583 
16584 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16585   assert(DC == CurContext && "Mismatch of container contexts");
16586   OriginalLexicalContext = DC;
16587   ActOnObjCContainerFinishDefinition();
16588 }
16589 
16590 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16591   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16592   OriginalLexicalContext = nullptr;
16593 }
16594 
16595 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16596   AdjustDeclIfTemplate(TagD);
16597   TagDecl *Tag = cast<TagDecl>(TagD);
16598   Tag->setInvalidDecl();
16599 
16600   // Make sure we "complete" the definition even it is invalid.
16601   if (Tag->isBeingDefined()) {
16602     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16603       RD->completeDefinition();
16604   }
16605 
16606   // We're undoing ActOnTagStartDefinition here, not
16607   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16608   // the FieldCollector.
16609 
16610   PopDeclContext();
16611 }
16612 
16613 // Note that FieldName may be null for anonymous bitfields.
16614 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16615                                 IdentifierInfo *FieldName,
16616                                 QualType FieldTy, bool IsMsStruct,
16617                                 Expr *BitWidth, bool *ZeroWidth) {
16618   assert(BitWidth);
16619   if (BitWidth->containsErrors())
16620     return ExprError();
16621 
16622   // Default to true; that shouldn't confuse checks for emptiness
16623   if (ZeroWidth)
16624     *ZeroWidth = true;
16625 
16626   // C99 6.7.2.1p4 - verify the field type.
16627   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16628   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16629     // Handle incomplete and sizeless types with a specific error.
16630     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16631                                  diag::err_field_incomplete_or_sizeless))
16632       return ExprError();
16633     if (FieldName)
16634       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16635         << FieldName << FieldTy << BitWidth->getSourceRange();
16636     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16637       << FieldTy << BitWidth->getSourceRange();
16638   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16639                                              UPPC_BitFieldWidth))
16640     return ExprError();
16641 
16642   // If the bit-width is type- or value-dependent, don't try to check
16643   // it now.
16644   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16645     return BitWidth;
16646 
16647   llvm::APSInt Value;
16648   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16649   if (ICE.isInvalid())
16650     return ICE;
16651   BitWidth = ICE.get();
16652 
16653   if (Value != 0 && ZeroWidth)
16654     *ZeroWidth = false;
16655 
16656   // Zero-width bitfield is ok for anonymous field.
16657   if (Value == 0 && FieldName)
16658     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16659 
16660   if (Value.isSigned() && Value.isNegative()) {
16661     if (FieldName)
16662       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16663                << FieldName << Value.toString(10);
16664     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16665       << Value.toString(10);
16666   }
16667 
16668   // The size of the bit-field must not exceed our maximum permitted object
16669   // size.
16670   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16671     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16672            << !FieldName << FieldName << Value.toString(10);
16673   }
16674 
16675   if (!FieldTy->isDependentType()) {
16676     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16677     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16678     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16679 
16680     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16681     // ABI.
16682     bool CStdConstraintViolation =
16683         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16684     bool MSBitfieldViolation =
16685         Value.ugt(TypeStorageSize) &&
16686         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16687     if (CStdConstraintViolation || MSBitfieldViolation) {
16688       unsigned DiagWidth =
16689           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16690       if (FieldName)
16691         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16692                << FieldName << Value.toString(10)
16693                << !CStdConstraintViolation << DiagWidth;
16694 
16695       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16696              << Value.toString(10) << !CStdConstraintViolation
16697              << DiagWidth;
16698     }
16699 
16700     // Warn on types where the user might conceivably expect to get all
16701     // specified bits as value bits: that's all integral types other than
16702     // 'bool'.
16703     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16704       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16705           << FieldName << Value.toString(10)
16706           << (unsigned)TypeWidth;
16707     }
16708   }
16709 
16710   return BitWidth;
16711 }
16712 
16713 /// ActOnField - Each field of a C struct/union is passed into this in order
16714 /// to create a FieldDecl object for it.
16715 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16716                        Declarator &D, Expr *BitfieldWidth) {
16717   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16718                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16719                                /*InitStyle=*/ICIS_NoInit, AS_public);
16720   return Res;
16721 }
16722 
16723 /// HandleField - Analyze a field of a C struct or a C++ data member.
16724 ///
16725 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16726                              SourceLocation DeclStart,
16727                              Declarator &D, Expr *BitWidth,
16728                              InClassInitStyle InitStyle,
16729                              AccessSpecifier AS) {
16730   if (D.isDecompositionDeclarator()) {
16731     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16732     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16733       << Decomp.getSourceRange();
16734     return nullptr;
16735   }
16736 
16737   IdentifierInfo *II = D.getIdentifier();
16738   SourceLocation Loc = DeclStart;
16739   if (II) Loc = D.getIdentifierLoc();
16740 
16741   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16742   QualType T = TInfo->getType();
16743   if (getLangOpts().CPlusPlus) {
16744     CheckExtraCXXDefaultArguments(D);
16745 
16746     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16747                                         UPPC_DataMemberType)) {
16748       D.setInvalidType();
16749       T = Context.IntTy;
16750       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16751     }
16752   }
16753 
16754   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16755 
16756   if (D.getDeclSpec().isInlineSpecified())
16757     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16758         << getLangOpts().CPlusPlus17;
16759   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16760     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16761          diag::err_invalid_thread)
16762       << DeclSpec::getSpecifierName(TSCS);
16763 
16764   // Check to see if this name was declared as a member previously
16765   NamedDecl *PrevDecl = nullptr;
16766   LookupResult Previous(*this, II, Loc, LookupMemberName,
16767                         ForVisibleRedeclaration);
16768   LookupName(Previous, S);
16769   switch (Previous.getResultKind()) {
16770     case LookupResult::Found:
16771     case LookupResult::FoundUnresolvedValue:
16772       PrevDecl = Previous.getAsSingle<NamedDecl>();
16773       break;
16774 
16775     case LookupResult::FoundOverloaded:
16776       PrevDecl = Previous.getRepresentativeDecl();
16777       break;
16778 
16779     case LookupResult::NotFound:
16780     case LookupResult::NotFoundInCurrentInstantiation:
16781     case LookupResult::Ambiguous:
16782       break;
16783   }
16784   Previous.suppressDiagnostics();
16785 
16786   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16787     // Maybe we will complain about the shadowed template parameter.
16788     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16789     // Just pretend that we didn't see the previous declaration.
16790     PrevDecl = nullptr;
16791   }
16792 
16793   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16794     PrevDecl = nullptr;
16795 
16796   bool Mutable
16797     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16798   SourceLocation TSSL = D.getBeginLoc();
16799   FieldDecl *NewFD
16800     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16801                      TSSL, AS, PrevDecl, &D);
16802 
16803   if (NewFD->isInvalidDecl())
16804     Record->setInvalidDecl();
16805 
16806   if (D.getDeclSpec().isModulePrivateSpecified())
16807     NewFD->setModulePrivate();
16808 
16809   if (NewFD->isInvalidDecl() && PrevDecl) {
16810     // Don't introduce NewFD into scope; there's already something
16811     // with the same name in the same scope.
16812   } else if (II) {
16813     PushOnScopeChains(NewFD, S);
16814   } else
16815     Record->addDecl(NewFD);
16816 
16817   return NewFD;
16818 }
16819 
16820 /// Build a new FieldDecl and check its well-formedness.
16821 ///
16822 /// This routine builds a new FieldDecl given the fields name, type,
16823 /// record, etc. \p PrevDecl should refer to any previous declaration
16824 /// with the same name and in the same scope as the field to be
16825 /// created.
16826 ///
16827 /// \returns a new FieldDecl.
16828 ///
16829 /// \todo The Declarator argument is a hack. It will be removed once
16830 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16831                                 TypeSourceInfo *TInfo,
16832                                 RecordDecl *Record, SourceLocation Loc,
16833                                 bool Mutable, Expr *BitWidth,
16834                                 InClassInitStyle InitStyle,
16835                                 SourceLocation TSSL,
16836                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16837                                 Declarator *D) {
16838   IdentifierInfo *II = Name.getAsIdentifierInfo();
16839   bool InvalidDecl = false;
16840   if (D) InvalidDecl = D->isInvalidType();
16841 
16842   // If we receive a broken type, recover by assuming 'int' and
16843   // marking this declaration as invalid.
16844   if (T.isNull() || T->containsErrors()) {
16845     InvalidDecl = true;
16846     T = Context.IntTy;
16847   }
16848 
16849   QualType EltTy = Context.getBaseElementType(T);
16850   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16851     if (RequireCompleteSizedType(Loc, EltTy,
16852                                  diag::err_field_incomplete_or_sizeless)) {
16853       // Fields of incomplete type force their record to be invalid.
16854       Record->setInvalidDecl();
16855       InvalidDecl = true;
16856     } else {
16857       NamedDecl *Def;
16858       EltTy->isIncompleteType(&Def);
16859       if (Def && Def->isInvalidDecl()) {
16860         Record->setInvalidDecl();
16861         InvalidDecl = true;
16862       }
16863     }
16864   }
16865 
16866   // TR 18037 does not allow fields to be declared with address space
16867   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16868       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16869     Diag(Loc, diag::err_field_with_address_space);
16870     Record->setInvalidDecl();
16871     InvalidDecl = true;
16872   }
16873 
16874   if (LangOpts.OpenCL) {
16875     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16876     // used as structure or union field: image, sampler, event or block types.
16877     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16878         T->isBlockPointerType()) {
16879       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16880       Record->setInvalidDecl();
16881       InvalidDecl = true;
16882     }
16883     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
16884     // is enabled.
16885     if (BitWidth && !getOpenCLOptions().isAvailableOption(
16886                         "__cl_clang_bitfields", LangOpts)) {
16887       Diag(Loc, diag::err_opencl_bitfields);
16888       InvalidDecl = true;
16889     }
16890   }
16891 
16892   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16893   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16894       T.hasQualifiers()) {
16895     InvalidDecl = true;
16896     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16897   }
16898 
16899   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16900   // than a variably modified type.
16901   if (!InvalidDecl && T->isVariablyModifiedType()) {
16902     if (!tryToFixVariablyModifiedVarType(
16903             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16904       InvalidDecl = true;
16905   }
16906 
16907   // Fields can not have abstract class types
16908   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16909                                              diag::err_abstract_type_in_decl,
16910                                              AbstractFieldType))
16911     InvalidDecl = true;
16912 
16913   bool ZeroWidth = false;
16914   if (InvalidDecl)
16915     BitWidth = nullptr;
16916   // If this is declared as a bit-field, check the bit-field.
16917   if (BitWidth) {
16918     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16919                               &ZeroWidth).get();
16920     if (!BitWidth) {
16921       InvalidDecl = true;
16922       BitWidth = nullptr;
16923       ZeroWidth = false;
16924     }
16925   }
16926 
16927   // Check that 'mutable' is consistent with the type of the declaration.
16928   if (!InvalidDecl && Mutable) {
16929     unsigned DiagID = 0;
16930     if (T->isReferenceType())
16931       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16932                                         : diag::err_mutable_reference;
16933     else if (T.isConstQualified())
16934       DiagID = diag::err_mutable_const;
16935 
16936     if (DiagID) {
16937       SourceLocation ErrLoc = Loc;
16938       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16939         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16940       Diag(ErrLoc, DiagID);
16941       if (DiagID != diag::ext_mutable_reference) {
16942         Mutable = false;
16943         InvalidDecl = true;
16944       }
16945     }
16946   }
16947 
16948   // C++11 [class.union]p8 (DR1460):
16949   //   At most one variant member of a union may have a
16950   //   brace-or-equal-initializer.
16951   if (InitStyle != ICIS_NoInit)
16952     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16953 
16954   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16955                                        BitWidth, Mutable, InitStyle);
16956   if (InvalidDecl)
16957     NewFD->setInvalidDecl();
16958 
16959   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16960     Diag(Loc, diag::err_duplicate_member) << II;
16961     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16962     NewFD->setInvalidDecl();
16963   }
16964 
16965   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16966     if (Record->isUnion()) {
16967       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16968         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16969         if (RDecl->getDefinition()) {
16970           // C++ [class.union]p1: An object of a class with a non-trivial
16971           // constructor, a non-trivial copy constructor, a non-trivial
16972           // destructor, or a non-trivial copy assignment operator
16973           // cannot be a member of a union, nor can an array of such
16974           // objects.
16975           if (CheckNontrivialField(NewFD))
16976             NewFD->setInvalidDecl();
16977         }
16978       }
16979 
16980       // C++ [class.union]p1: If a union contains a member of reference type,
16981       // the program is ill-formed, except when compiling with MSVC extensions
16982       // enabled.
16983       if (EltTy->isReferenceType()) {
16984         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16985                                     diag::ext_union_member_of_reference_type :
16986                                     diag::err_union_member_of_reference_type)
16987           << NewFD->getDeclName() << EltTy;
16988         if (!getLangOpts().MicrosoftExt)
16989           NewFD->setInvalidDecl();
16990       }
16991     }
16992   }
16993 
16994   // FIXME: We need to pass in the attributes given an AST
16995   // representation, not a parser representation.
16996   if (D) {
16997     // FIXME: The current scope is almost... but not entirely... correct here.
16998     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16999 
17000     if (NewFD->hasAttrs())
17001       CheckAlignasUnderalignment(NewFD);
17002   }
17003 
17004   // In auto-retain/release, infer strong retension for fields of
17005   // retainable type.
17006   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17007     NewFD->setInvalidDecl();
17008 
17009   if (T.isObjCGCWeak())
17010     Diag(Loc, diag::warn_attribute_weak_on_field);
17011 
17012   // PPC MMA non-pointer types are not allowed as field types.
17013   if (Context.getTargetInfo().getTriple().isPPC64() &&
17014       CheckPPCMMAType(T, NewFD->getLocation()))
17015     NewFD->setInvalidDecl();
17016 
17017   NewFD->setAccess(AS);
17018   return NewFD;
17019 }
17020 
17021 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17022   assert(FD);
17023   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17024 
17025   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17026     return false;
17027 
17028   QualType EltTy = Context.getBaseElementType(FD->getType());
17029   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17030     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17031     if (RDecl->getDefinition()) {
17032       // We check for copy constructors before constructors
17033       // because otherwise we'll never get complaints about
17034       // copy constructors.
17035 
17036       CXXSpecialMember member = CXXInvalid;
17037       // We're required to check for any non-trivial constructors. Since the
17038       // implicit default constructor is suppressed if there are any
17039       // user-declared constructors, we just need to check that there is a
17040       // trivial default constructor and a trivial copy constructor. (We don't
17041       // worry about move constructors here, since this is a C++98 check.)
17042       if (RDecl->hasNonTrivialCopyConstructor())
17043         member = CXXCopyConstructor;
17044       else if (!RDecl->hasTrivialDefaultConstructor())
17045         member = CXXDefaultConstructor;
17046       else if (RDecl->hasNonTrivialCopyAssignment())
17047         member = CXXCopyAssignment;
17048       else if (RDecl->hasNonTrivialDestructor())
17049         member = CXXDestructor;
17050 
17051       if (member != CXXInvalid) {
17052         if (!getLangOpts().CPlusPlus11 &&
17053             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17054           // Objective-C++ ARC: it is an error to have a non-trivial field of
17055           // a union. However, system headers in Objective-C programs
17056           // occasionally have Objective-C lifetime objects within unions,
17057           // and rather than cause the program to fail, we make those
17058           // members unavailable.
17059           SourceLocation Loc = FD->getLocation();
17060           if (getSourceManager().isInSystemHeader(Loc)) {
17061             if (!FD->hasAttr<UnavailableAttr>())
17062               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17063                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17064             return false;
17065           }
17066         }
17067 
17068         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17069                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17070                diag::err_illegal_union_or_anon_struct_member)
17071           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17072         DiagnoseNontrivial(RDecl, member);
17073         return !getLangOpts().CPlusPlus11;
17074       }
17075     }
17076   }
17077 
17078   return false;
17079 }
17080 
17081 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17082 ///  AST enum value.
17083 static ObjCIvarDecl::AccessControl
17084 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17085   switch (ivarVisibility) {
17086   default: llvm_unreachable("Unknown visitibility kind");
17087   case tok::objc_private: return ObjCIvarDecl::Private;
17088   case tok::objc_public: return ObjCIvarDecl::Public;
17089   case tok::objc_protected: return ObjCIvarDecl::Protected;
17090   case tok::objc_package: return ObjCIvarDecl::Package;
17091   }
17092 }
17093 
17094 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17095 /// in order to create an IvarDecl object for it.
17096 Decl *Sema::ActOnIvar(Scope *S,
17097                                 SourceLocation DeclStart,
17098                                 Declarator &D, Expr *BitfieldWidth,
17099                                 tok::ObjCKeywordKind Visibility) {
17100 
17101   IdentifierInfo *II = D.getIdentifier();
17102   Expr *BitWidth = (Expr*)BitfieldWidth;
17103   SourceLocation Loc = DeclStart;
17104   if (II) Loc = D.getIdentifierLoc();
17105 
17106   // FIXME: Unnamed fields can be handled in various different ways, for
17107   // example, unnamed unions inject all members into the struct namespace!
17108 
17109   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17110   QualType T = TInfo->getType();
17111 
17112   if (BitWidth) {
17113     // 6.7.2.1p3, 6.7.2.1p4
17114     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17115     if (!BitWidth)
17116       D.setInvalidType();
17117   } else {
17118     // Not a bitfield.
17119 
17120     // validate II.
17121 
17122   }
17123   if (T->isReferenceType()) {
17124     Diag(Loc, diag::err_ivar_reference_type);
17125     D.setInvalidType();
17126   }
17127   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17128   // than a variably modified type.
17129   else if (T->isVariablyModifiedType()) {
17130     if (!tryToFixVariablyModifiedVarType(
17131             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17132       D.setInvalidType();
17133   }
17134 
17135   // Get the visibility (access control) for this ivar.
17136   ObjCIvarDecl::AccessControl ac =
17137     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17138                                         : ObjCIvarDecl::None;
17139   // Must set ivar's DeclContext to its enclosing interface.
17140   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17141   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17142     return nullptr;
17143   ObjCContainerDecl *EnclosingContext;
17144   if (ObjCImplementationDecl *IMPDecl =
17145       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17146     if (LangOpts.ObjCRuntime.isFragile()) {
17147     // Case of ivar declared in an implementation. Context is that of its class.
17148       EnclosingContext = IMPDecl->getClassInterface();
17149       assert(EnclosingContext && "Implementation has no class interface!");
17150     }
17151     else
17152       EnclosingContext = EnclosingDecl;
17153   } else {
17154     if (ObjCCategoryDecl *CDecl =
17155         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17156       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17157         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17158         return nullptr;
17159       }
17160     }
17161     EnclosingContext = EnclosingDecl;
17162   }
17163 
17164   // Construct the decl.
17165   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17166                                              DeclStart, Loc, II, T,
17167                                              TInfo, ac, (Expr *)BitfieldWidth);
17168 
17169   if (II) {
17170     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17171                                            ForVisibleRedeclaration);
17172     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17173         && !isa<TagDecl>(PrevDecl)) {
17174       Diag(Loc, diag::err_duplicate_member) << II;
17175       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17176       NewID->setInvalidDecl();
17177     }
17178   }
17179 
17180   // Process attributes attached to the ivar.
17181   ProcessDeclAttributes(S, NewID, D);
17182 
17183   if (D.isInvalidType())
17184     NewID->setInvalidDecl();
17185 
17186   // In ARC, infer 'retaining' for ivars of retainable type.
17187   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17188     NewID->setInvalidDecl();
17189 
17190   if (D.getDeclSpec().isModulePrivateSpecified())
17191     NewID->setModulePrivate();
17192 
17193   if (II) {
17194     // FIXME: When interfaces are DeclContexts, we'll need to add
17195     // these to the interface.
17196     S->AddDecl(NewID);
17197     IdResolver.AddDecl(NewID);
17198   }
17199 
17200   if (LangOpts.ObjCRuntime.isNonFragile() &&
17201       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17202     Diag(Loc, diag::warn_ivars_in_interface);
17203 
17204   return NewID;
17205 }
17206 
17207 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17208 /// class and class extensions. For every class \@interface and class
17209 /// extension \@interface, if the last ivar is a bitfield of any type,
17210 /// then add an implicit `char :0` ivar to the end of that interface.
17211 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17212                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17213   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17214     return;
17215 
17216   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17217   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17218 
17219   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17220     return;
17221   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17222   if (!ID) {
17223     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17224       if (!CD->IsClassExtension())
17225         return;
17226     }
17227     // No need to add this to end of @implementation.
17228     else
17229       return;
17230   }
17231   // All conditions are met. Add a new bitfield to the tail end of ivars.
17232   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17233   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17234 
17235   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17236                               DeclLoc, DeclLoc, nullptr,
17237                               Context.CharTy,
17238                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17239                                                                DeclLoc),
17240                               ObjCIvarDecl::Private, BW,
17241                               true);
17242   AllIvarDecls.push_back(Ivar);
17243 }
17244 
17245 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17246                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17247                        SourceLocation RBrac,
17248                        const ParsedAttributesView &Attrs) {
17249   assert(EnclosingDecl && "missing record or interface decl");
17250 
17251   // If this is an Objective-C @implementation or category and we have
17252   // new fields here we should reset the layout of the interface since
17253   // it will now change.
17254   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17255     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17256     switch (DC->getKind()) {
17257     default: break;
17258     case Decl::ObjCCategory:
17259       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17260       break;
17261     case Decl::ObjCImplementation:
17262       Context.
17263         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17264       break;
17265     }
17266   }
17267 
17268   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17269   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17270 
17271   // Start counting up the number of named members; make sure to include
17272   // members of anonymous structs and unions in the total.
17273   unsigned NumNamedMembers = 0;
17274   if (Record) {
17275     for (const auto *I : Record->decls()) {
17276       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17277         if (IFD->getDeclName())
17278           ++NumNamedMembers;
17279     }
17280   }
17281 
17282   // Verify that all the fields are okay.
17283   SmallVector<FieldDecl*, 32> RecFields;
17284 
17285   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17286        i != end; ++i) {
17287     FieldDecl *FD = cast<FieldDecl>(*i);
17288 
17289     // Get the type for the field.
17290     const Type *FDTy = FD->getType().getTypePtr();
17291 
17292     if (!FD->isAnonymousStructOrUnion()) {
17293       // Remember all fields written by the user.
17294       RecFields.push_back(FD);
17295     }
17296 
17297     // If the field is already invalid for some reason, don't emit more
17298     // diagnostics about it.
17299     if (FD->isInvalidDecl()) {
17300       EnclosingDecl->setInvalidDecl();
17301       continue;
17302     }
17303 
17304     // C99 6.7.2.1p2:
17305     //   A structure or union shall not contain a member with
17306     //   incomplete or function type (hence, a structure shall not
17307     //   contain an instance of itself, but may contain a pointer to
17308     //   an instance of itself), except that the last member of a
17309     //   structure with more than one named member may have incomplete
17310     //   array type; such a structure (and any union containing,
17311     //   possibly recursively, a member that is such a structure)
17312     //   shall not be a member of a structure or an element of an
17313     //   array.
17314     bool IsLastField = (i + 1 == Fields.end());
17315     if (FDTy->isFunctionType()) {
17316       // Field declared as a function.
17317       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17318         << FD->getDeclName();
17319       FD->setInvalidDecl();
17320       EnclosingDecl->setInvalidDecl();
17321       continue;
17322     } else if (FDTy->isIncompleteArrayType() &&
17323                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17324       if (Record) {
17325         // Flexible array member.
17326         // Microsoft and g++ is more permissive regarding flexible array.
17327         // It will accept flexible array in union and also
17328         // as the sole element of a struct/class.
17329         unsigned DiagID = 0;
17330         if (!Record->isUnion() && !IsLastField) {
17331           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17332             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17333           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17334           FD->setInvalidDecl();
17335           EnclosingDecl->setInvalidDecl();
17336           continue;
17337         } else if (Record->isUnion())
17338           DiagID = getLangOpts().MicrosoftExt
17339                        ? diag::ext_flexible_array_union_ms
17340                        : getLangOpts().CPlusPlus
17341                              ? diag::ext_flexible_array_union_gnu
17342                              : diag::err_flexible_array_union;
17343         else if (NumNamedMembers < 1)
17344           DiagID = getLangOpts().MicrosoftExt
17345                        ? diag::ext_flexible_array_empty_aggregate_ms
17346                        : getLangOpts().CPlusPlus
17347                              ? diag::ext_flexible_array_empty_aggregate_gnu
17348                              : diag::err_flexible_array_empty_aggregate;
17349 
17350         if (DiagID)
17351           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17352                                           << Record->getTagKind();
17353         // While the layout of types that contain virtual bases is not specified
17354         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17355         // virtual bases after the derived members.  This would make a flexible
17356         // array member declared at the end of an object not adjacent to the end
17357         // of the type.
17358         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17359           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17360               << FD->getDeclName() << Record->getTagKind();
17361         if (!getLangOpts().C99)
17362           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17363             << FD->getDeclName() << Record->getTagKind();
17364 
17365         // If the element type has a non-trivial destructor, we would not
17366         // implicitly destroy the elements, so disallow it for now.
17367         //
17368         // FIXME: GCC allows this. We should probably either implicitly delete
17369         // the destructor of the containing class, or just allow this.
17370         QualType BaseElem = Context.getBaseElementType(FD->getType());
17371         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17372           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17373             << FD->getDeclName() << FD->getType();
17374           FD->setInvalidDecl();
17375           EnclosingDecl->setInvalidDecl();
17376           continue;
17377         }
17378         // Okay, we have a legal flexible array member at the end of the struct.
17379         Record->setHasFlexibleArrayMember(true);
17380       } else {
17381         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17382         // unless they are followed by another ivar. That check is done
17383         // elsewhere, after synthesized ivars are known.
17384       }
17385     } else if (!FDTy->isDependentType() &&
17386                RequireCompleteSizedType(
17387                    FD->getLocation(), FD->getType(),
17388                    diag::err_field_incomplete_or_sizeless)) {
17389       // Incomplete type
17390       FD->setInvalidDecl();
17391       EnclosingDecl->setInvalidDecl();
17392       continue;
17393     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17394       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17395         // A type which contains a flexible array member is considered to be a
17396         // flexible array member.
17397         Record->setHasFlexibleArrayMember(true);
17398         if (!Record->isUnion()) {
17399           // If this is a struct/class and this is not the last element, reject
17400           // it.  Note that GCC supports variable sized arrays in the middle of
17401           // structures.
17402           if (!IsLastField)
17403             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17404               << FD->getDeclName() << FD->getType();
17405           else {
17406             // We support flexible arrays at the end of structs in
17407             // other structs as an extension.
17408             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17409               << FD->getDeclName();
17410           }
17411         }
17412       }
17413       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17414           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17415                                  diag::err_abstract_type_in_decl,
17416                                  AbstractIvarType)) {
17417         // Ivars can not have abstract class types
17418         FD->setInvalidDecl();
17419       }
17420       if (Record && FDTTy->getDecl()->hasObjectMember())
17421         Record->setHasObjectMember(true);
17422       if (Record && FDTTy->getDecl()->hasVolatileMember())
17423         Record->setHasVolatileMember(true);
17424     } else if (FDTy->isObjCObjectType()) {
17425       /// A field cannot be an Objective-c object
17426       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17427         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17428       QualType T = Context.getObjCObjectPointerType(FD->getType());
17429       FD->setType(T);
17430     } else if (Record && Record->isUnion() &&
17431                FD->getType().hasNonTrivialObjCLifetime() &&
17432                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17433                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17434                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17435                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17436       // For backward compatibility, fields of C unions declared in system
17437       // headers that have non-trivial ObjC ownership qualifications are marked
17438       // as unavailable unless the qualifier is explicit and __strong. This can
17439       // break ABI compatibility between programs compiled with ARC and MRR, but
17440       // is a better option than rejecting programs using those unions under
17441       // ARC.
17442       FD->addAttr(UnavailableAttr::CreateImplicit(
17443           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17444           FD->getLocation()));
17445     } else if (getLangOpts().ObjC &&
17446                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17447                !Record->hasObjectMember()) {
17448       if (FD->getType()->isObjCObjectPointerType() ||
17449           FD->getType().isObjCGCStrong())
17450         Record->setHasObjectMember(true);
17451       else if (Context.getAsArrayType(FD->getType())) {
17452         QualType BaseType = Context.getBaseElementType(FD->getType());
17453         if (BaseType->isRecordType() &&
17454             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17455           Record->setHasObjectMember(true);
17456         else if (BaseType->isObjCObjectPointerType() ||
17457                  BaseType.isObjCGCStrong())
17458                Record->setHasObjectMember(true);
17459       }
17460     }
17461 
17462     if (Record && !getLangOpts().CPlusPlus &&
17463         !shouldIgnoreForRecordTriviality(FD)) {
17464       QualType FT = FD->getType();
17465       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17466         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17467         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17468             Record->isUnion())
17469           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17470       }
17471       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17472       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17473         Record->setNonTrivialToPrimitiveCopy(true);
17474         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17475           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17476       }
17477       if (FT.isDestructedType()) {
17478         Record->setNonTrivialToPrimitiveDestroy(true);
17479         Record->setParamDestroyedInCallee(true);
17480         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17481           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17482       }
17483 
17484       if (const auto *RT = FT->getAs<RecordType>()) {
17485         if (RT->getDecl()->getArgPassingRestrictions() ==
17486             RecordDecl::APK_CanNeverPassInRegs)
17487           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17488       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17489         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17490     }
17491 
17492     if (Record && FD->getType().isVolatileQualified())
17493       Record->setHasVolatileMember(true);
17494     // Keep track of the number of named members.
17495     if (FD->getIdentifier())
17496       ++NumNamedMembers;
17497   }
17498 
17499   // Okay, we successfully defined 'Record'.
17500   if (Record) {
17501     bool Completed = false;
17502     if (CXXRecord) {
17503       if (!CXXRecord->isInvalidDecl()) {
17504         // Set access bits correctly on the directly-declared conversions.
17505         for (CXXRecordDecl::conversion_iterator
17506                I = CXXRecord->conversion_begin(),
17507                E = CXXRecord->conversion_end(); I != E; ++I)
17508           I.setAccess((*I)->getAccess());
17509       }
17510 
17511       // Add any implicitly-declared members to this class.
17512       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17513 
17514       if (!CXXRecord->isDependentType()) {
17515         if (!CXXRecord->isInvalidDecl()) {
17516           // If we have virtual base classes, we may end up finding multiple
17517           // final overriders for a given virtual function. Check for this
17518           // problem now.
17519           if (CXXRecord->getNumVBases()) {
17520             CXXFinalOverriderMap FinalOverriders;
17521             CXXRecord->getFinalOverriders(FinalOverriders);
17522 
17523             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17524                                              MEnd = FinalOverriders.end();
17525                  M != MEnd; ++M) {
17526               for (OverridingMethods::iterator SO = M->second.begin(),
17527                                             SOEnd = M->second.end();
17528                    SO != SOEnd; ++SO) {
17529                 assert(SO->second.size() > 0 &&
17530                        "Virtual function without overriding functions?");
17531                 if (SO->second.size() == 1)
17532                   continue;
17533 
17534                 // C++ [class.virtual]p2:
17535                 //   In a derived class, if a virtual member function of a base
17536                 //   class subobject has more than one final overrider the
17537                 //   program is ill-formed.
17538                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17539                   << (const NamedDecl *)M->first << Record;
17540                 Diag(M->first->getLocation(),
17541                      diag::note_overridden_virtual_function);
17542                 for (OverridingMethods::overriding_iterator
17543                           OM = SO->second.begin(),
17544                        OMEnd = SO->second.end();
17545                      OM != OMEnd; ++OM)
17546                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17547                     << (const NamedDecl *)M->first << OM->Method->getParent();
17548 
17549                 Record->setInvalidDecl();
17550               }
17551             }
17552             CXXRecord->completeDefinition(&FinalOverriders);
17553             Completed = true;
17554           }
17555         }
17556       }
17557     }
17558 
17559     if (!Completed)
17560       Record->completeDefinition();
17561 
17562     // Handle attributes before checking the layout.
17563     ProcessDeclAttributeList(S, Record, Attrs);
17564 
17565     // We may have deferred checking for a deleted destructor. Check now.
17566     if (CXXRecord) {
17567       auto *Dtor = CXXRecord->getDestructor();
17568       if (Dtor && Dtor->isImplicit() &&
17569           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17570         CXXRecord->setImplicitDestructorIsDeleted();
17571         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17572       }
17573     }
17574 
17575     if (Record->hasAttrs()) {
17576       CheckAlignasUnderalignment(Record);
17577 
17578       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17579         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17580                                            IA->getRange(), IA->getBestCase(),
17581                                            IA->getInheritanceModel());
17582     }
17583 
17584     // Check if the structure/union declaration is a type that can have zero
17585     // size in C. For C this is a language extension, for C++ it may cause
17586     // compatibility problems.
17587     bool CheckForZeroSize;
17588     if (!getLangOpts().CPlusPlus) {
17589       CheckForZeroSize = true;
17590     } else {
17591       // For C++ filter out types that cannot be referenced in C code.
17592       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17593       CheckForZeroSize =
17594           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17595           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17596           CXXRecord->isCLike();
17597     }
17598     if (CheckForZeroSize) {
17599       bool ZeroSize = true;
17600       bool IsEmpty = true;
17601       unsigned NonBitFields = 0;
17602       for (RecordDecl::field_iterator I = Record->field_begin(),
17603                                       E = Record->field_end();
17604            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17605         IsEmpty = false;
17606         if (I->isUnnamedBitfield()) {
17607           if (!I->isZeroLengthBitField(Context))
17608             ZeroSize = false;
17609         } else {
17610           ++NonBitFields;
17611           QualType FieldType = I->getType();
17612           if (FieldType->isIncompleteType() ||
17613               !Context.getTypeSizeInChars(FieldType).isZero())
17614             ZeroSize = false;
17615         }
17616       }
17617 
17618       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17619       // allowed in C++, but warn if its declaration is inside
17620       // extern "C" block.
17621       if (ZeroSize) {
17622         Diag(RecLoc, getLangOpts().CPlusPlus ?
17623                          diag::warn_zero_size_struct_union_in_extern_c :
17624                          diag::warn_zero_size_struct_union_compat)
17625           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17626       }
17627 
17628       // Structs without named members are extension in C (C99 6.7.2.1p7),
17629       // but are accepted by GCC.
17630       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17631         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17632                                diag::ext_no_named_members_in_struct_union)
17633           << Record->isUnion();
17634       }
17635     }
17636   } else {
17637     ObjCIvarDecl **ClsFields =
17638       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17639     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17640       ID->setEndOfDefinitionLoc(RBrac);
17641       // Add ivar's to class's DeclContext.
17642       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17643         ClsFields[i]->setLexicalDeclContext(ID);
17644         ID->addDecl(ClsFields[i]);
17645       }
17646       // Must enforce the rule that ivars in the base classes may not be
17647       // duplicates.
17648       if (ID->getSuperClass())
17649         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17650     } else if (ObjCImplementationDecl *IMPDecl =
17651                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17652       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17653       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17654         // Ivar declared in @implementation never belongs to the implementation.
17655         // Only it is in implementation's lexical context.
17656         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17657       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17658       IMPDecl->setIvarLBraceLoc(LBrac);
17659       IMPDecl->setIvarRBraceLoc(RBrac);
17660     } else if (ObjCCategoryDecl *CDecl =
17661                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17662       // case of ivars in class extension; all other cases have been
17663       // reported as errors elsewhere.
17664       // FIXME. Class extension does not have a LocEnd field.
17665       // CDecl->setLocEnd(RBrac);
17666       // Add ivar's to class extension's DeclContext.
17667       // Diagnose redeclaration of private ivars.
17668       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17669       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17670         if (IDecl) {
17671           if (const ObjCIvarDecl *ClsIvar =
17672               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17673             Diag(ClsFields[i]->getLocation(),
17674                  diag::err_duplicate_ivar_declaration);
17675             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17676             continue;
17677           }
17678           for (const auto *Ext : IDecl->known_extensions()) {
17679             if (const ObjCIvarDecl *ClsExtIvar
17680                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17681               Diag(ClsFields[i]->getLocation(),
17682                    diag::err_duplicate_ivar_declaration);
17683               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17684               continue;
17685             }
17686           }
17687         }
17688         ClsFields[i]->setLexicalDeclContext(CDecl);
17689         CDecl->addDecl(ClsFields[i]);
17690       }
17691       CDecl->setIvarLBraceLoc(LBrac);
17692       CDecl->setIvarRBraceLoc(RBrac);
17693     }
17694   }
17695 }
17696 
17697 /// Determine whether the given integral value is representable within
17698 /// the given type T.
17699 static bool isRepresentableIntegerValue(ASTContext &Context,
17700                                         llvm::APSInt &Value,
17701                                         QualType T) {
17702   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17703          "Integral type required!");
17704   unsigned BitWidth = Context.getIntWidth(T);
17705 
17706   if (Value.isUnsigned() || Value.isNonNegative()) {
17707     if (T->isSignedIntegerOrEnumerationType())
17708       --BitWidth;
17709     return Value.getActiveBits() <= BitWidth;
17710   }
17711   return Value.getMinSignedBits() <= BitWidth;
17712 }
17713 
17714 // Given an integral type, return the next larger integral type
17715 // (or a NULL type of no such type exists).
17716 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17717   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17718   // enum checking below.
17719   assert((T->isIntegralType(Context) ||
17720          T->isEnumeralType()) && "Integral type required!");
17721   const unsigned NumTypes = 4;
17722   QualType SignedIntegralTypes[NumTypes] = {
17723     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17724   };
17725   QualType UnsignedIntegralTypes[NumTypes] = {
17726     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17727     Context.UnsignedLongLongTy
17728   };
17729 
17730   unsigned BitWidth = Context.getTypeSize(T);
17731   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17732                                                         : UnsignedIntegralTypes;
17733   for (unsigned I = 0; I != NumTypes; ++I)
17734     if (Context.getTypeSize(Types[I]) > BitWidth)
17735       return Types[I];
17736 
17737   return QualType();
17738 }
17739 
17740 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17741                                           EnumConstantDecl *LastEnumConst,
17742                                           SourceLocation IdLoc,
17743                                           IdentifierInfo *Id,
17744                                           Expr *Val) {
17745   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17746   llvm::APSInt EnumVal(IntWidth);
17747   QualType EltTy;
17748 
17749   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17750     Val = nullptr;
17751 
17752   if (Val)
17753     Val = DefaultLvalueConversion(Val).get();
17754 
17755   if (Val) {
17756     if (Enum->isDependentType() || Val->isTypeDependent())
17757       EltTy = Context.DependentTy;
17758     else {
17759       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17760       // underlying type, but do allow it in all other contexts.
17761       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17762         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17763         // constant-expression in the enumerator-definition shall be a converted
17764         // constant expression of the underlying type.
17765         EltTy = Enum->getIntegerType();
17766         ExprResult Converted =
17767           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17768                                            CCEK_Enumerator);
17769         if (Converted.isInvalid())
17770           Val = nullptr;
17771         else
17772           Val = Converted.get();
17773       } else if (!Val->isValueDependent() &&
17774                  !(Val =
17775                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17776                            .get())) {
17777         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17778       } else {
17779         if (Enum->isComplete()) {
17780           EltTy = Enum->getIntegerType();
17781 
17782           // In Obj-C and Microsoft mode, require the enumeration value to be
17783           // representable in the underlying type of the enumeration. In C++11,
17784           // we perform a non-narrowing conversion as part of converted constant
17785           // expression checking.
17786           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17787             if (Context.getTargetInfo()
17788                     .getTriple()
17789                     .isWindowsMSVCEnvironment()) {
17790               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17791             } else {
17792               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17793             }
17794           }
17795 
17796           // Cast to the underlying type.
17797           Val = ImpCastExprToType(Val, EltTy,
17798                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17799                                                          : CK_IntegralCast)
17800                     .get();
17801         } else if (getLangOpts().CPlusPlus) {
17802           // C++11 [dcl.enum]p5:
17803           //   If the underlying type is not fixed, the type of each enumerator
17804           //   is the type of its initializing value:
17805           //     - If an initializer is specified for an enumerator, the
17806           //       initializing value has the same type as the expression.
17807           EltTy = Val->getType();
17808         } else {
17809           // C99 6.7.2.2p2:
17810           //   The expression that defines the value of an enumeration constant
17811           //   shall be an integer constant expression that has a value
17812           //   representable as an int.
17813 
17814           // Complain if the value is not representable in an int.
17815           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17816             Diag(IdLoc, diag::ext_enum_value_not_int)
17817               << EnumVal.toString(10) << Val->getSourceRange()
17818               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17819           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17820             // Force the type of the expression to 'int'.
17821             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17822           }
17823           EltTy = Val->getType();
17824         }
17825       }
17826     }
17827   }
17828 
17829   if (!Val) {
17830     if (Enum->isDependentType())
17831       EltTy = Context.DependentTy;
17832     else if (!LastEnumConst) {
17833       // C++0x [dcl.enum]p5:
17834       //   If the underlying type is not fixed, the type of each enumerator
17835       //   is the type of its initializing value:
17836       //     - If no initializer is specified for the first enumerator, the
17837       //       initializing value has an unspecified integral type.
17838       //
17839       // GCC uses 'int' for its unspecified integral type, as does
17840       // C99 6.7.2.2p3.
17841       if (Enum->isFixed()) {
17842         EltTy = Enum->getIntegerType();
17843       }
17844       else {
17845         EltTy = Context.IntTy;
17846       }
17847     } else {
17848       // Assign the last value + 1.
17849       EnumVal = LastEnumConst->getInitVal();
17850       ++EnumVal;
17851       EltTy = LastEnumConst->getType();
17852 
17853       // Check for overflow on increment.
17854       if (EnumVal < LastEnumConst->getInitVal()) {
17855         // C++0x [dcl.enum]p5:
17856         //   If the underlying type is not fixed, the type of each enumerator
17857         //   is the type of its initializing value:
17858         //
17859         //     - Otherwise the type of the initializing value is the same as
17860         //       the type of the initializing value of the preceding enumerator
17861         //       unless the incremented value is not representable in that type,
17862         //       in which case the type is an unspecified integral type
17863         //       sufficient to contain the incremented value. If no such type
17864         //       exists, the program is ill-formed.
17865         QualType T = getNextLargerIntegralType(Context, EltTy);
17866         if (T.isNull() || Enum->isFixed()) {
17867           // There is no integral type larger enough to represent this
17868           // value. Complain, then allow the value to wrap around.
17869           EnumVal = LastEnumConst->getInitVal();
17870           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17871           ++EnumVal;
17872           if (Enum->isFixed())
17873             // When the underlying type is fixed, this is ill-formed.
17874             Diag(IdLoc, diag::err_enumerator_wrapped)
17875               << EnumVal.toString(10)
17876               << EltTy;
17877           else
17878             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17879               << EnumVal.toString(10);
17880         } else {
17881           EltTy = T;
17882         }
17883 
17884         // Retrieve the last enumerator's value, extent that type to the
17885         // type that is supposed to be large enough to represent the incremented
17886         // value, then increment.
17887         EnumVal = LastEnumConst->getInitVal();
17888         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17889         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17890         ++EnumVal;
17891 
17892         // If we're not in C++, diagnose the overflow of enumerator values,
17893         // which in C99 means that the enumerator value is not representable in
17894         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17895         // permits enumerator values that are representable in some larger
17896         // integral type.
17897         if (!getLangOpts().CPlusPlus && !T.isNull())
17898           Diag(IdLoc, diag::warn_enum_value_overflow);
17899       } else if (!getLangOpts().CPlusPlus &&
17900                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17901         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17902         Diag(IdLoc, diag::ext_enum_value_not_int)
17903           << EnumVal.toString(10) << 1;
17904       }
17905     }
17906   }
17907 
17908   if (!EltTy->isDependentType()) {
17909     // Make the enumerator value match the signedness and size of the
17910     // enumerator's type.
17911     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17912     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17913   }
17914 
17915   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17916                                   Val, EnumVal);
17917 }
17918 
17919 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17920                                                 SourceLocation IILoc) {
17921   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17922       !getLangOpts().CPlusPlus)
17923     return SkipBodyInfo();
17924 
17925   // We have an anonymous enum definition. Look up the first enumerator to
17926   // determine if we should merge the definition with an existing one and
17927   // skip the body.
17928   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17929                                          forRedeclarationInCurContext());
17930   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17931   if (!PrevECD)
17932     return SkipBodyInfo();
17933 
17934   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17935   NamedDecl *Hidden;
17936   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17937     SkipBodyInfo Skip;
17938     Skip.Previous = Hidden;
17939     return Skip;
17940   }
17941 
17942   return SkipBodyInfo();
17943 }
17944 
17945 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17946                               SourceLocation IdLoc, IdentifierInfo *Id,
17947                               const ParsedAttributesView &Attrs,
17948                               SourceLocation EqualLoc, Expr *Val) {
17949   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17950   EnumConstantDecl *LastEnumConst =
17951     cast_or_null<EnumConstantDecl>(lastEnumConst);
17952 
17953   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17954   // we find one that is.
17955   S = getNonFieldDeclScope(S);
17956 
17957   // Verify that there isn't already something declared with this name in this
17958   // scope.
17959   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17960   LookupName(R, S);
17961   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17962 
17963   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17964     // Maybe we will complain about the shadowed template parameter.
17965     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17966     // Just pretend that we didn't see the previous declaration.
17967     PrevDecl = nullptr;
17968   }
17969 
17970   // C++ [class.mem]p15:
17971   // If T is the name of a class, then each of the following shall have a name
17972   // different from T:
17973   // - every enumerator of every member of class T that is an unscoped
17974   // enumerated type
17975   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17976     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17977                             DeclarationNameInfo(Id, IdLoc));
17978 
17979   EnumConstantDecl *New =
17980     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17981   if (!New)
17982     return nullptr;
17983 
17984   if (PrevDecl) {
17985     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17986       // Check for other kinds of shadowing not already handled.
17987       CheckShadow(New, PrevDecl, R);
17988     }
17989 
17990     // When in C++, we may get a TagDecl with the same name; in this case the
17991     // enum constant will 'hide' the tag.
17992     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17993            "Received TagDecl when not in C++!");
17994     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17995       if (isa<EnumConstantDecl>(PrevDecl))
17996         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17997       else
17998         Diag(IdLoc, diag::err_redefinition) << Id;
17999       notePreviousDefinition(PrevDecl, IdLoc);
18000       return nullptr;
18001     }
18002   }
18003 
18004   // Process attributes.
18005   ProcessDeclAttributeList(S, New, Attrs);
18006   AddPragmaAttributes(S, New);
18007 
18008   // Register this decl in the current scope stack.
18009   New->setAccess(TheEnumDecl->getAccess());
18010   PushOnScopeChains(New, S);
18011 
18012   ActOnDocumentableDecl(New);
18013 
18014   return New;
18015 }
18016 
18017 // Returns true when the enum initial expression does not trigger the
18018 // duplicate enum warning.  A few common cases are exempted as follows:
18019 // Element2 = Element1
18020 // Element2 = Element1 + 1
18021 // Element2 = Element1 - 1
18022 // Where Element2 and Element1 are from the same enum.
18023 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18024   Expr *InitExpr = ECD->getInitExpr();
18025   if (!InitExpr)
18026     return true;
18027   InitExpr = InitExpr->IgnoreImpCasts();
18028 
18029   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18030     if (!BO->isAdditiveOp())
18031       return true;
18032     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18033     if (!IL)
18034       return true;
18035     if (IL->getValue() != 1)
18036       return true;
18037 
18038     InitExpr = BO->getLHS();
18039   }
18040 
18041   // This checks if the elements are from the same enum.
18042   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18043   if (!DRE)
18044     return true;
18045 
18046   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18047   if (!EnumConstant)
18048     return true;
18049 
18050   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18051       Enum)
18052     return true;
18053 
18054   return false;
18055 }
18056 
18057 // Emits a warning when an element is implicitly set a value that
18058 // a previous element has already been set to.
18059 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18060                                         EnumDecl *Enum, QualType EnumType) {
18061   // Avoid anonymous enums
18062   if (!Enum->getIdentifier())
18063     return;
18064 
18065   // Only check for small enums.
18066   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18067     return;
18068 
18069   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18070     return;
18071 
18072   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18073   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18074 
18075   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18076 
18077   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18078   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18079 
18080   // Use int64_t as a key to avoid needing special handling for map keys.
18081   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18082     llvm::APSInt Val = D->getInitVal();
18083     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18084   };
18085 
18086   DuplicatesVector DupVector;
18087   ValueToVectorMap EnumMap;
18088 
18089   // Populate the EnumMap with all values represented by enum constants without
18090   // an initializer.
18091   for (auto *Element : Elements) {
18092     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18093 
18094     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18095     // this constant.  Skip this enum since it may be ill-formed.
18096     if (!ECD) {
18097       return;
18098     }
18099 
18100     // Constants with initalizers are handled in the next loop.
18101     if (ECD->getInitExpr())
18102       continue;
18103 
18104     // Duplicate values are handled in the next loop.
18105     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18106   }
18107 
18108   if (EnumMap.size() == 0)
18109     return;
18110 
18111   // Create vectors for any values that has duplicates.
18112   for (auto *Element : Elements) {
18113     // The last loop returned if any constant was null.
18114     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18115     if (!ValidDuplicateEnum(ECD, Enum))
18116       continue;
18117 
18118     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18119     if (Iter == EnumMap.end())
18120       continue;
18121 
18122     DeclOrVector& Entry = Iter->second;
18123     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18124       // Ensure constants are different.
18125       if (D == ECD)
18126         continue;
18127 
18128       // Create new vector and push values onto it.
18129       auto Vec = std::make_unique<ECDVector>();
18130       Vec->push_back(D);
18131       Vec->push_back(ECD);
18132 
18133       // Update entry to point to the duplicates vector.
18134       Entry = Vec.get();
18135 
18136       // Store the vector somewhere we can consult later for quick emission of
18137       // diagnostics.
18138       DupVector.emplace_back(std::move(Vec));
18139       continue;
18140     }
18141 
18142     ECDVector *Vec = Entry.get<ECDVector*>();
18143     // Make sure constants are not added more than once.
18144     if (*Vec->begin() == ECD)
18145       continue;
18146 
18147     Vec->push_back(ECD);
18148   }
18149 
18150   // Emit diagnostics.
18151   for (const auto &Vec : DupVector) {
18152     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18153 
18154     // Emit warning for one enum constant.
18155     auto *FirstECD = Vec->front();
18156     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18157       << FirstECD << FirstECD->getInitVal().toString(10)
18158       << FirstECD->getSourceRange();
18159 
18160     // Emit one note for each of the remaining enum constants with
18161     // the same value.
18162     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18163       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18164         << ECD << ECD->getInitVal().toString(10)
18165         << ECD->getSourceRange();
18166   }
18167 }
18168 
18169 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18170                              bool AllowMask) const {
18171   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18172   assert(ED->isCompleteDefinition() && "expected enum definition");
18173 
18174   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18175   llvm::APInt &FlagBits = R.first->second;
18176 
18177   if (R.second) {
18178     for (auto *E : ED->enumerators()) {
18179       const auto &EVal = E->getInitVal();
18180       // Only single-bit enumerators introduce new flag values.
18181       if (EVal.isPowerOf2())
18182         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18183     }
18184   }
18185 
18186   // A value is in a flag enum if either its bits are a subset of the enum's
18187   // flag bits (the first condition) or we are allowing masks and the same is
18188   // true of its complement (the second condition). When masks are allowed, we
18189   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18190   //
18191   // While it's true that any value could be used as a mask, the assumption is
18192   // that a mask will have all of the insignificant bits set. Anything else is
18193   // likely a logic error.
18194   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18195   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18196 }
18197 
18198 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18199                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18200                          const ParsedAttributesView &Attrs) {
18201   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18202   QualType EnumType = Context.getTypeDeclType(Enum);
18203 
18204   ProcessDeclAttributeList(S, Enum, Attrs);
18205 
18206   if (Enum->isDependentType()) {
18207     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18208       EnumConstantDecl *ECD =
18209         cast_or_null<EnumConstantDecl>(Elements[i]);
18210       if (!ECD) continue;
18211 
18212       ECD->setType(EnumType);
18213     }
18214 
18215     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18216     return;
18217   }
18218 
18219   // TODO: If the result value doesn't fit in an int, it must be a long or long
18220   // long value.  ISO C does not support this, but GCC does as an extension,
18221   // emit a warning.
18222   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18223   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18224   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18225 
18226   // Verify that all the values are okay, compute the size of the values, and
18227   // reverse the list.
18228   unsigned NumNegativeBits = 0;
18229   unsigned NumPositiveBits = 0;
18230 
18231   // Keep track of whether all elements have type int.
18232   bool AllElementsInt = true;
18233 
18234   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18235     EnumConstantDecl *ECD =
18236       cast_or_null<EnumConstantDecl>(Elements[i]);
18237     if (!ECD) continue;  // Already issued a diagnostic.
18238 
18239     const llvm::APSInt &InitVal = ECD->getInitVal();
18240 
18241     // Keep track of the size of positive and negative values.
18242     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18243       NumPositiveBits = std::max(NumPositiveBits,
18244                                  (unsigned)InitVal.getActiveBits());
18245     else
18246       NumNegativeBits = std::max(NumNegativeBits,
18247                                  (unsigned)InitVal.getMinSignedBits());
18248 
18249     // Keep track of whether every enum element has type int (very common).
18250     if (AllElementsInt)
18251       AllElementsInt = ECD->getType() == Context.IntTy;
18252   }
18253 
18254   // Figure out the type that should be used for this enum.
18255   QualType BestType;
18256   unsigned BestWidth;
18257 
18258   // C++0x N3000 [conv.prom]p3:
18259   //   An rvalue of an unscoped enumeration type whose underlying
18260   //   type is not fixed can be converted to an rvalue of the first
18261   //   of the following types that can represent all the values of
18262   //   the enumeration: int, unsigned int, long int, unsigned long
18263   //   int, long long int, or unsigned long long int.
18264   // C99 6.4.4.3p2:
18265   //   An identifier declared as an enumeration constant has type int.
18266   // The C99 rule is modified by a gcc extension
18267   QualType BestPromotionType;
18268 
18269   bool Packed = Enum->hasAttr<PackedAttr>();
18270   // -fshort-enums is the equivalent to specifying the packed attribute on all
18271   // enum definitions.
18272   if (LangOpts.ShortEnums)
18273     Packed = true;
18274 
18275   // If the enum already has a type because it is fixed or dictated by the
18276   // target, promote that type instead of analyzing the enumerators.
18277   if (Enum->isComplete()) {
18278     BestType = Enum->getIntegerType();
18279     if (BestType->isPromotableIntegerType())
18280       BestPromotionType = Context.getPromotedIntegerType(BestType);
18281     else
18282       BestPromotionType = BestType;
18283 
18284     BestWidth = Context.getIntWidth(BestType);
18285   }
18286   else if (NumNegativeBits) {
18287     // If there is a negative value, figure out the smallest integer type (of
18288     // int/long/longlong) that fits.
18289     // If it's packed, check also if it fits a char or a short.
18290     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18291       BestType = Context.SignedCharTy;
18292       BestWidth = CharWidth;
18293     } else if (Packed && NumNegativeBits <= ShortWidth &&
18294                NumPositiveBits < ShortWidth) {
18295       BestType = Context.ShortTy;
18296       BestWidth = ShortWidth;
18297     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18298       BestType = Context.IntTy;
18299       BestWidth = IntWidth;
18300     } else {
18301       BestWidth = Context.getTargetInfo().getLongWidth();
18302 
18303       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18304         BestType = Context.LongTy;
18305       } else {
18306         BestWidth = Context.getTargetInfo().getLongLongWidth();
18307 
18308         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18309           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18310         BestType = Context.LongLongTy;
18311       }
18312     }
18313     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18314   } else {
18315     // If there is no negative value, figure out the smallest type that fits
18316     // all of the enumerator values.
18317     // If it's packed, check also if it fits a char or a short.
18318     if (Packed && NumPositiveBits <= CharWidth) {
18319       BestType = Context.UnsignedCharTy;
18320       BestPromotionType = Context.IntTy;
18321       BestWidth = CharWidth;
18322     } else if (Packed && NumPositiveBits <= ShortWidth) {
18323       BestType = Context.UnsignedShortTy;
18324       BestPromotionType = Context.IntTy;
18325       BestWidth = ShortWidth;
18326     } else if (NumPositiveBits <= IntWidth) {
18327       BestType = Context.UnsignedIntTy;
18328       BestWidth = IntWidth;
18329       BestPromotionType
18330         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18331                            ? Context.UnsignedIntTy : Context.IntTy;
18332     } else if (NumPositiveBits <=
18333                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18334       BestType = Context.UnsignedLongTy;
18335       BestPromotionType
18336         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18337                            ? Context.UnsignedLongTy : Context.LongTy;
18338     } else {
18339       BestWidth = Context.getTargetInfo().getLongLongWidth();
18340       assert(NumPositiveBits <= BestWidth &&
18341              "How could an initializer get larger than ULL?");
18342       BestType = Context.UnsignedLongLongTy;
18343       BestPromotionType
18344         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18345                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18346     }
18347   }
18348 
18349   // Loop over all of the enumerator constants, changing their types to match
18350   // the type of the enum if needed.
18351   for (auto *D : Elements) {
18352     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18353     if (!ECD) continue;  // Already issued a diagnostic.
18354 
18355     // Standard C says the enumerators have int type, but we allow, as an
18356     // extension, the enumerators to be larger than int size.  If each
18357     // enumerator value fits in an int, type it as an int, otherwise type it the
18358     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18359     // that X has type 'int', not 'unsigned'.
18360 
18361     // Determine whether the value fits into an int.
18362     llvm::APSInt InitVal = ECD->getInitVal();
18363 
18364     // If it fits into an integer type, force it.  Otherwise force it to match
18365     // the enum decl type.
18366     QualType NewTy;
18367     unsigned NewWidth;
18368     bool NewSign;
18369     if (!getLangOpts().CPlusPlus &&
18370         !Enum->isFixed() &&
18371         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18372       NewTy = Context.IntTy;
18373       NewWidth = IntWidth;
18374       NewSign = true;
18375     } else if (ECD->getType() == BestType) {
18376       // Already the right type!
18377       if (getLangOpts().CPlusPlus)
18378         // C++ [dcl.enum]p4: Following the closing brace of an
18379         // enum-specifier, each enumerator has the type of its
18380         // enumeration.
18381         ECD->setType(EnumType);
18382       continue;
18383     } else {
18384       NewTy = BestType;
18385       NewWidth = BestWidth;
18386       NewSign = BestType->isSignedIntegerOrEnumerationType();
18387     }
18388 
18389     // Adjust the APSInt value.
18390     InitVal = InitVal.extOrTrunc(NewWidth);
18391     InitVal.setIsSigned(NewSign);
18392     ECD->setInitVal(InitVal);
18393 
18394     // Adjust the Expr initializer and type.
18395     if (ECD->getInitExpr() &&
18396         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18397       ECD->setInitExpr(ImplicitCastExpr::Create(
18398           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18399           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18400     if (getLangOpts().CPlusPlus)
18401       // C++ [dcl.enum]p4: Following the closing brace of an
18402       // enum-specifier, each enumerator has the type of its
18403       // enumeration.
18404       ECD->setType(EnumType);
18405     else
18406       ECD->setType(NewTy);
18407   }
18408 
18409   Enum->completeDefinition(BestType, BestPromotionType,
18410                            NumPositiveBits, NumNegativeBits);
18411 
18412   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18413 
18414   if (Enum->isClosedFlag()) {
18415     for (Decl *D : Elements) {
18416       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18417       if (!ECD) continue;  // Already issued a diagnostic.
18418 
18419       llvm::APSInt InitVal = ECD->getInitVal();
18420       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18421           !IsValueInFlagEnum(Enum, InitVal, true))
18422         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18423           << ECD << Enum;
18424     }
18425   }
18426 
18427   // Now that the enum type is defined, ensure it's not been underaligned.
18428   if (Enum->hasAttrs())
18429     CheckAlignasUnderalignment(Enum);
18430 }
18431 
18432 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18433                                   SourceLocation StartLoc,
18434                                   SourceLocation EndLoc) {
18435   StringLiteral *AsmString = cast<StringLiteral>(expr);
18436 
18437   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18438                                                    AsmString, StartLoc,
18439                                                    EndLoc);
18440   CurContext->addDecl(New);
18441   return New;
18442 }
18443 
18444 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18445                                       IdentifierInfo* AliasName,
18446                                       SourceLocation PragmaLoc,
18447                                       SourceLocation NameLoc,
18448                                       SourceLocation AliasNameLoc) {
18449   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18450                                          LookupOrdinaryName);
18451   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18452                            AttributeCommonInfo::AS_Pragma);
18453   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18454       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18455 
18456   // If a declaration that:
18457   // 1) declares a function or a variable
18458   // 2) has external linkage
18459   // already exists, add a label attribute to it.
18460   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18461     if (isDeclExternC(PrevDecl))
18462       PrevDecl->addAttr(Attr);
18463     else
18464       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18465           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18466   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18467   } else
18468     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18469 }
18470 
18471 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18472                              SourceLocation PragmaLoc,
18473                              SourceLocation NameLoc) {
18474   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18475 
18476   if (PrevDecl) {
18477     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18478   } else {
18479     (void)WeakUndeclaredIdentifiers.insert(
18480       std::pair<IdentifierInfo*,WeakInfo>
18481         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18482   }
18483 }
18484 
18485 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18486                                 IdentifierInfo* AliasName,
18487                                 SourceLocation PragmaLoc,
18488                                 SourceLocation NameLoc,
18489                                 SourceLocation AliasNameLoc) {
18490   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18491                                     LookupOrdinaryName);
18492   WeakInfo W = WeakInfo(Name, NameLoc);
18493 
18494   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18495     if (!PrevDecl->hasAttr<AliasAttr>())
18496       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18497         DeclApplyPragmaWeak(TUScope, ND, W);
18498   } else {
18499     (void)WeakUndeclaredIdentifiers.insert(
18500       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18501   }
18502 }
18503 
18504 Decl *Sema::getObjCDeclContext() const {
18505   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18506 }
18507 
18508 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18509                                                      bool Final) {
18510   assert(FD && "Expected non-null FunctionDecl");
18511 
18512   // SYCL functions can be template, so we check if they have appropriate
18513   // attribute prior to checking if it is a template.
18514   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18515     return FunctionEmissionStatus::Emitted;
18516 
18517   // Templates are emitted when they're instantiated.
18518   if (FD->isDependentContext())
18519     return FunctionEmissionStatus::TemplateDiscarded;
18520 
18521   // Check whether this function is an externally visible definition.
18522   auto IsEmittedForExternalSymbol = [this, FD]() {
18523     // We have to check the GVA linkage of the function's *definition* -- if we
18524     // only have a declaration, we don't know whether or not the function will
18525     // be emitted, because (say) the definition could include "inline".
18526     FunctionDecl *Def = FD->getDefinition();
18527 
18528     return Def && !isDiscardableGVALinkage(
18529                       getASTContext().GetGVALinkageForFunction(Def));
18530   };
18531 
18532   if (LangOpts.OpenMPIsDevice) {
18533     // In OpenMP device mode we will not emit host only functions, or functions
18534     // we don't need due to their linkage.
18535     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18536         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18537     // DevTy may be changed later by
18538     //  #pragma omp declare target to(*) device_type(*).
18539     // Therefore DevTy having no value does not imply host. The emission status
18540     // will be checked again at the end of compilation unit with Final = true.
18541     if (DevTy.hasValue())
18542       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18543         return FunctionEmissionStatus::OMPDiscarded;
18544     // If we have an explicit value for the device type, or we are in a target
18545     // declare context, we need to emit all extern and used symbols.
18546     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18547       if (IsEmittedForExternalSymbol())
18548         return FunctionEmissionStatus::Emitted;
18549     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18550     // we'll omit it.
18551     if (Final)
18552       return FunctionEmissionStatus::OMPDiscarded;
18553   } else if (LangOpts.OpenMP > 45) {
18554     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18555     // function. In 5.0, no_host was introduced which might cause a function to
18556     // be ommitted.
18557     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18558         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18559     if (DevTy.hasValue())
18560       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18561         return FunctionEmissionStatus::OMPDiscarded;
18562   }
18563 
18564   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18565     return FunctionEmissionStatus::Emitted;
18566 
18567   if (LangOpts.CUDA) {
18568     // When compiling for device, host functions are never emitted.  Similarly,
18569     // when compiling for host, device and global functions are never emitted.
18570     // (Technically, we do emit a host-side stub for global functions, but this
18571     // doesn't count for our purposes here.)
18572     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18573     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18574       return FunctionEmissionStatus::CUDADiscarded;
18575     if (!LangOpts.CUDAIsDevice &&
18576         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18577       return FunctionEmissionStatus::CUDADiscarded;
18578 
18579     if (IsEmittedForExternalSymbol())
18580       return FunctionEmissionStatus::Emitted;
18581   }
18582 
18583   // Otherwise, the function is known-emitted if it's in our set of
18584   // known-emitted functions.
18585   return FunctionEmissionStatus::Unknown;
18586 }
18587 
18588 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18589   // Host-side references to a __global__ function refer to the stub, so the
18590   // function itself is never emitted and therefore should not be marked.
18591   // If we have host fn calls kernel fn calls host+device, the HD function
18592   // does not get instantiated on the host. We model this by omitting at the
18593   // call to the kernel from the callgraph. This ensures that, when compiling
18594   // for host, only HD functions actually called from the host get marked as
18595   // known-emitted.
18596   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18597          IdentifyCUDATarget(Callee) == CFT_Global;
18598 }
18599