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___ibm128:
145   case tok::kw_wchar_t:
146   case tok::kw_bool:
147   case tok::kw___underlying_type:
148   case tok::kw___auto_type:
149     return true;
150 
151   case tok::annot_typename:
152   case tok::kw_char16_t:
153   case tok::kw_char32_t:
154   case tok::kw_typeof:
155   case tok::annot_decltype:
156   case tok::kw_decltype:
157     return getLangOpts().CPlusPlus;
158 
159   case tok::kw_char8_t:
160     return getLangOpts().Char8;
161 
162   default:
163     break;
164   }
165 
166   return false;
167 }
168 
169 namespace {
170 enum class UnqualifiedTypeNameLookupResult {
171   NotFound,
172   FoundNonType,
173   FoundType
174 };
175 } // end anonymous namespace
176 
177 /// Tries to perform unqualified lookup of the type decls in bases for
178 /// dependent class.
179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180 /// type decl, \a FoundType if only type decls are found.
181 static UnqualifiedTypeNameLookupResult
182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
183                                 SourceLocation NameLoc,
184                                 const CXXRecordDecl *RD) {
185   if (!RD->hasDefinition())
186     return UnqualifiedTypeNameLookupResult::NotFound;
187   // Look for type decls in base classes.
188   UnqualifiedTypeNameLookupResult FoundTypeDecl =
189       UnqualifiedTypeNameLookupResult::NotFound;
190   for (const auto &Base : RD->bases()) {
191     const CXXRecordDecl *BaseRD = nullptr;
192     if (auto *BaseTT = Base.getType()->getAs<TagType>())
193       BaseRD = BaseTT->getAsCXXRecordDecl();
194     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195       // Look for type decls in dependent base classes that have known primary
196       // templates.
197       if (!TST || !TST->isDependentType())
198         continue;
199       auto *TD = TST->getTemplateName().getAsTemplateDecl();
200       if (!TD)
201         continue;
202       if (auto *BasePrimaryTemplate =
203           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205           BaseRD = BasePrimaryTemplate;
206         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207           if (const ClassTemplatePartialSpecializationDecl *PS =
208                   CTD->findPartialSpecialization(Base.getType()))
209             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210               BaseRD = PS;
211         }
212       }
213     }
214     if (BaseRD) {
215       for (NamedDecl *ND : BaseRD->lookup(&II)) {
216         if (!isa<TypeDecl>(ND))
217           return UnqualifiedTypeNameLookupResult::FoundNonType;
218         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219       }
220       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222         case UnqualifiedTypeNameLookupResult::FoundNonType:
223           return UnqualifiedTypeNameLookupResult::FoundNonType;
224         case UnqualifiedTypeNameLookupResult::FoundType:
225           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226           break;
227         case UnqualifiedTypeNameLookupResult::NotFound:
228           break;
229         }
230       }
231     }
232   }
233 
234   return FoundTypeDecl;
235 }
236 
237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
238                                                       const IdentifierInfo &II,
239                                                       SourceLocation NameLoc) {
240   // Lookup in the parent class template context, if any.
241   const CXXRecordDecl *RD = nullptr;
242   UnqualifiedTypeNameLookupResult FoundTypeDecl =
243       UnqualifiedTypeNameLookupResult::NotFound;
244   for (DeclContext *DC = S.CurContext;
245        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246        DC = DC->getParent()) {
247     // Look for type decls in dependent base classes that have known primary
248     // templates.
249     RD = dyn_cast<CXXRecordDecl>(DC);
250     if (RD && RD->getDescribedClassTemplate())
251       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252   }
253   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254     return nullptr;
255 
256   // We found some types in dependent base classes.  Recover as if the user
257   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
258   // lookup during template instantiation.
259   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
260 
261   ASTContext &Context = S.Context;
262   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263                                           cast<Type>(Context.getRecordType(RD)));
264   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265 
266   CXXScopeSpec SS;
267   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268 
269   TypeLocBuilder Builder;
270   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271   DepTL.setNameLoc(NameLoc);
272   DepTL.setElaboratedKeywordLoc(SourceLocation());
273   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275 }
276 
277 /// If the identifier refers to a type name within this scope,
278 /// return the declaration of that type.
279 ///
280 /// This routine performs ordinary name lookup of the identifier II
281 /// within the given scope, with optional C++ scope specifier SS, to
282 /// determine whether the name refers to a type. If so, returns an
283 /// opaque pointer (actually a QualType) corresponding to that
284 /// type. Otherwise, returns NULL.
285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
286                              Scope *S, CXXScopeSpec *SS,
287                              bool isClassName, bool HasTrailingDot,
288                              ParsedType ObjectTypePtr,
289                              bool IsCtorOrDtorName,
290                              bool WantNontrivialTypeSourceInfo,
291                              bool IsClassTemplateDeductionContext,
292                              IdentifierInfo **CorrectedII) {
293   // FIXME: Consider allowing this outside C++1z mode as an extension.
294   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296                               !isClassName && !HasTrailingDot;
297 
298   // Determine where we will perform name lookup.
299   DeclContext *LookupCtx = nullptr;
300   if (ObjectTypePtr) {
301     QualType ObjectType = ObjectTypePtr.get();
302     if (ObjectType->isRecordType())
303       LookupCtx = computeDeclContext(ObjectType);
304   } else if (SS && SS->isNotEmpty()) {
305     LookupCtx = computeDeclContext(*SS, false);
306 
307     if (!LookupCtx) {
308       if (isDependentScopeSpecifier(*SS)) {
309         // C++ [temp.res]p3:
310         //   A qualified-id that refers to a type and in which the
311         //   nested-name-specifier depends on a template-parameter (14.6.2)
312         //   shall be prefixed by the keyword typename to indicate that the
313         //   qualified-id denotes a type, forming an
314         //   elaborated-type-specifier (7.1.5.3).
315         //
316         // We therefore do not perform any name lookup if the result would
317         // refer to a member of an unknown specialization.
318         if (!isClassName && !IsCtorOrDtorName)
319           return nullptr;
320 
321         // We know from the grammar that this name refers to a type,
322         // so build a dependent node to describe the type.
323         if (WantNontrivialTypeSourceInfo)
324           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325 
326         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328                                        II, NameLoc);
329         return ParsedType::make(T);
330       }
331 
332       return nullptr;
333     }
334 
335     if (!LookupCtx->isDependentContext() &&
336         RequireCompleteDeclContext(*SS, LookupCtx))
337       return nullptr;
338   }
339 
340   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341   // lookup for class-names.
342   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
343                                       LookupOrdinaryName;
344   LookupResult Result(*this, &II, NameLoc, Kind);
345   if (LookupCtx) {
346     // Perform "qualified" name lookup into the declaration context we
347     // computed, which is either the type of the base of a member access
348     // expression or the declaration context associated with a prior
349     // nested-name-specifier.
350     LookupQualifiedName(Result, LookupCtx);
351 
352     if (ObjectTypePtr && Result.empty()) {
353       // C++ [basic.lookup.classref]p3:
354       //   If the unqualified-id is ~type-name, the type-name is looked up
355       //   in the context of the entire postfix-expression. If the type T of
356       //   the object expression is of a class type C, the type-name is also
357       //   looked up in the scope of class C. At least one of the lookups shall
358       //   find a name that refers to (possibly cv-qualified) T.
359       LookupName(Result, S);
360     }
361   } else {
362     // Perform unqualified name lookup.
363     LookupName(Result, S);
364 
365     // For unqualified lookup in a class template in MSVC mode, look into
366     // dependent base classes where the primary class template is known.
367     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
368       if (ParsedType TypeInBase =
369               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370         return TypeInBase;
371     }
372   }
373 
374   NamedDecl *IIDecl = nullptr;
375   switch (Result.getResultKind()) {
376   case LookupResult::NotFound:
377   case LookupResult::NotFoundInCurrentInstantiation:
378     if (CorrectedII) {
379       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
380                                AllowDeducedTemplate);
381       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
382                                               S, SS, CCC, CTK_ErrorRecovery);
383       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
384       TemplateTy Template;
385       bool MemberOfUnknownSpecialization;
386       UnqualifiedId TemplateName;
387       TemplateName.setIdentifier(NewII, NameLoc);
388       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
389       CXXScopeSpec NewSS, *NewSSPtr = SS;
390       if (SS && NNS) {
391         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
392         NewSSPtr = &NewSS;
393       }
394       if (Correction && (NNS || NewII != &II) &&
395           // Ignore a correction to a template type as the to-be-corrected
396           // identifier is not a template (typo correction for template names
397           // is handled elsewhere).
398           !(getLangOpts().CPlusPlus && NewSSPtr &&
399             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
400                            Template, MemberOfUnknownSpecialization))) {
401         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
402                                     isClassName, HasTrailingDot, ObjectTypePtr,
403                                     IsCtorOrDtorName,
404                                     WantNontrivialTypeSourceInfo,
405                                     IsClassTemplateDeductionContext);
406         if (Ty) {
407           diagnoseTypo(Correction,
408                        PDiag(diag::err_unknown_type_or_class_name_suggest)
409                          << Result.getLookupName() << isClassName);
410           if (SS && NNS)
411             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
412           *CorrectedII = NewII;
413           return Ty;
414         }
415       }
416     }
417     // If typo correction failed or was not performed, fall through
418     LLVM_FALLTHROUGH;
419   case LookupResult::FoundOverloaded:
420   case LookupResult::FoundUnresolvedValue:
421     Result.suppressDiagnostics();
422     return nullptr;
423 
424   case LookupResult::Ambiguous:
425     // Recover from type-hiding ambiguities by hiding the type.  We'll
426     // do the lookup again when looking for an object, and we can
427     // diagnose the error then.  If we don't do this, then the error
428     // about hiding the type will be immediately followed by an error
429     // that only makes sense if the identifier was treated like a type.
430     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
431       Result.suppressDiagnostics();
432       return nullptr;
433     }
434 
435     // Look to see if we have a type anywhere in the list of results.
436     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
437          Res != ResEnd; ++Res) {
438       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
439       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
440               RealRes) ||
441           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
442         if (!IIDecl ||
443             // Make the selection of the recovery decl deterministic.
444             RealRes->getLocation() < IIDecl->getLocation())
445           IIDecl = RealRes;
446       }
447     }
448 
449     if (!IIDecl) {
450       // None of the entities we found is a type, so there is no way
451       // to even assume that the result is a type. In this case, don't
452       // complain about the ambiguity. The parser will either try to
453       // perform this lookup again (e.g., as an object name), which
454       // will produce the ambiguity, or will complain that it expected
455       // a type name.
456       Result.suppressDiagnostics();
457       return nullptr;
458     }
459 
460     // We found a type within the ambiguous lookup; diagnose the
461     // ambiguity and then return that type. This might be the right
462     // answer, or it might not be, but it suppresses any attempt to
463     // perform the name lookup again.
464     break;
465 
466   case LookupResult::Found:
467     IIDecl = Result.getFoundDecl();
468     break;
469   }
470 
471   assert(IIDecl && "Didn't find decl");
472 
473   QualType T;
474   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
475     // C++ [class.qual]p2: A lookup that would find the injected-class-name
476     // instead names the constructors of the class, except when naming a class.
477     // This is ill-formed when we're not actually forming a ctor or dtor name.
478     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
479     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
480     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
481         FoundRD->isInjectedClassName() &&
482         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
483       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
484           << &II << /*Type*/1;
485 
486     DiagnoseUseOfDecl(IIDecl, NameLoc);
487 
488     T = Context.getTypeDeclType(TD);
489     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
490   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
491     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
492     if (!HasTrailingDot)
493       T = Context.getObjCInterfaceType(IDecl);
494   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
495     (void)DiagnoseUseOfDecl(UD, NameLoc);
496     // Recover with 'int'
497     T = Context.IntTy;
498   } else if (AllowDeducedTemplate) {
499     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
500       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
501                                                        QualType(), false);
502   }
503 
504   if (T.isNull()) {
505     // If it's not plausibly a type, suppress diagnostics.
506     Result.suppressDiagnostics();
507     return nullptr;
508   }
509 
510   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
511   // constructor or destructor name (in such a case, the scope specifier
512   // will be attached to the enclosing Expr or Decl node).
513   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
514       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
515     if (WantNontrivialTypeSourceInfo) {
516       // Construct a type with type-source information.
517       TypeLocBuilder Builder;
518       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
519 
520       T = getElaboratedType(ETK_None, *SS, T);
521       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
522       ElabTL.setElaboratedKeywordLoc(SourceLocation());
523       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
524       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
525     } else {
526       T = getElaboratedType(ETK_None, *SS, T);
527     }
528   }
529 
530   return ParsedType::make(T);
531 }
532 
533 // Builds a fake NNS for the given decl context.
534 static NestedNameSpecifier *
535 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
536   for (;; DC = DC->getLookupParent()) {
537     DC = DC->getPrimaryContext();
538     auto *ND = dyn_cast<NamespaceDecl>(DC);
539     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
540       return NestedNameSpecifier::Create(Context, nullptr, ND);
541     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
542       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
543                                          RD->getTypeForDecl());
544     else if (isa<TranslationUnitDecl>(DC))
545       return NestedNameSpecifier::GlobalSpecifier(Context);
546   }
547   llvm_unreachable("something isn't in TU scope?");
548 }
549 
550 /// Find the parent class with dependent bases of the innermost enclosing method
551 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
552 /// up allowing unqualified dependent type names at class-level, which MSVC
553 /// correctly rejects.
554 static const CXXRecordDecl *
555 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
556   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
557     DC = DC->getPrimaryContext();
558     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
559       if (MD->getParent()->hasAnyDependentBases())
560         return MD->getParent();
561   }
562   return nullptr;
563 }
564 
565 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
566                                           SourceLocation NameLoc,
567                                           bool IsTemplateTypeArg) {
568   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
569 
570   NestedNameSpecifier *NNS = nullptr;
571   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
572     // If we weren't able to parse a default template argument, delay lookup
573     // until instantiation time by making a non-dependent DependentTypeName. We
574     // pretend we saw a NestedNameSpecifier referring to the current scope, and
575     // lookup is retried.
576     // FIXME: This hurts our diagnostic quality, since we get errors like "no
577     // type named 'Foo' in 'current_namespace'" when the user didn't write any
578     // name specifiers.
579     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
580     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
581   } else if (const CXXRecordDecl *RD =
582                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
583     // Build a DependentNameType that will perform lookup into RD at
584     // instantiation time.
585     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
586                                       RD->getTypeForDecl());
587 
588     // Diagnose that this identifier was undeclared, and retry the lookup during
589     // template instantiation.
590     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
591                                                                       << RD;
592   } else {
593     // This is not a situation that we should recover from.
594     return ParsedType();
595   }
596 
597   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
598 
599   // Build type location information.  We synthesized the qualifier, so we have
600   // to build a fake NestedNameSpecifierLoc.
601   NestedNameSpecifierLocBuilder NNSLocBuilder;
602   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
603   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
604 
605   TypeLocBuilder Builder;
606   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
607   DepTL.setNameLoc(NameLoc);
608   DepTL.setElaboratedKeywordLoc(SourceLocation());
609   DepTL.setQualifierLoc(QualifierLoc);
610   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
611 }
612 
613 /// isTagName() - This method is called *for error recovery purposes only*
614 /// to determine if the specified name is a valid tag name ("struct foo").  If
615 /// so, this returns the TST for the tag corresponding to it (TST_enum,
616 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
617 /// cases in C where the user forgot to specify the tag.
618 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
619   // Do a tag name lookup in this scope.
620   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
621   LookupName(R, S, false);
622   R.suppressDiagnostics();
623   if (R.getResultKind() == LookupResult::Found)
624     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
625       switch (TD->getTagKind()) {
626       case TTK_Struct: return DeclSpec::TST_struct;
627       case TTK_Interface: return DeclSpec::TST_interface;
628       case TTK_Union:  return DeclSpec::TST_union;
629       case TTK_Class:  return DeclSpec::TST_class;
630       case TTK_Enum:   return DeclSpec::TST_enum;
631       }
632     }
633 
634   return DeclSpec::TST_unspecified;
635 }
636 
637 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
638 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
639 /// then downgrade the missing typename error to a warning.
640 /// This is needed for MSVC compatibility; Example:
641 /// @code
642 /// template<class T> class A {
643 /// public:
644 ///   typedef int TYPE;
645 /// };
646 /// template<class T> class B : public A<T> {
647 /// public:
648 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
649 /// };
650 /// @endcode
651 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
652   if (CurContext->isRecord()) {
653     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
654       return true;
655 
656     const Type *Ty = SS->getScopeRep()->getAsType();
657 
658     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
659     for (const auto &Base : RD->bases())
660       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
661         return true;
662     return S->isFunctionPrototypeScope();
663   }
664   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
665 }
666 
667 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
668                                    SourceLocation IILoc,
669                                    Scope *S,
670                                    CXXScopeSpec *SS,
671                                    ParsedType &SuggestedType,
672                                    bool IsTemplateName) {
673   // Don't report typename errors for editor placeholders.
674   if (II->isEditorPlaceholder())
675     return;
676   // We don't have anything to suggest (yet).
677   SuggestedType = nullptr;
678 
679   // There may have been a typo in the name of the type. Look up typo
680   // results, in case we have something that we can suggest.
681   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
682                            /*AllowTemplates=*/IsTemplateName,
683                            /*AllowNonTemplates=*/!IsTemplateName);
684   if (TypoCorrection Corrected =
685           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
686                       CCC, CTK_ErrorRecovery)) {
687     // FIXME: Support error recovery for the template-name case.
688     bool CanRecover = !IsTemplateName;
689     if (Corrected.isKeyword()) {
690       // We corrected to a keyword.
691       diagnoseTypo(Corrected,
692                    PDiag(IsTemplateName ? diag::err_no_template_suggest
693                                         : diag::err_unknown_typename_suggest)
694                        << II);
695       II = Corrected.getCorrectionAsIdentifierInfo();
696     } else {
697       // We found a similarly-named type or interface; suggest that.
698       if (!SS || !SS->isSet()) {
699         diagnoseTypo(Corrected,
700                      PDiag(IsTemplateName ? diag::err_no_template_suggest
701                                           : diag::err_unknown_typename_suggest)
702                          << II, CanRecover);
703       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
704         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
705         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
706                                 II->getName().equals(CorrectedStr);
707         diagnoseTypo(Corrected,
708                      PDiag(IsTemplateName
709                                ? diag::err_no_member_template_suggest
710                                : diag::err_unknown_nested_typename_suggest)
711                          << II << DC << DroppedSpecifier << SS->getRange(),
712                      CanRecover);
713       } else {
714         llvm_unreachable("could not have corrected a typo here");
715       }
716 
717       if (!CanRecover)
718         return;
719 
720       CXXScopeSpec tmpSS;
721       if (Corrected.getCorrectionSpecifier())
722         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
723                           SourceRange(IILoc));
724       // FIXME: Support class template argument deduction here.
725       SuggestedType =
726           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
727                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
728                       /*IsCtorOrDtorName=*/false,
729                       /*WantNontrivialTypeSourceInfo=*/true);
730     }
731     return;
732   }
733 
734   if (getLangOpts().CPlusPlus && !IsTemplateName) {
735     // See if II is a class template that the user forgot to pass arguments to.
736     UnqualifiedId Name;
737     Name.setIdentifier(II, IILoc);
738     CXXScopeSpec EmptySS;
739     TemplateTy TemplateResult;
740     bool MemberOfUnknownSpecialization;
741     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
742                        Name, nullptr, true, TemplateResult,
743                        MemberOfUnknownSpecialization) == TNK_Type_template) {
744       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
745       return;
746     }
747   }
748 
749   // FIXME: Should we move the logic that tries to recover from a missing tag
750   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
751 
752   if (!SS || (!SS->isSet() && !SS->isInvalid()))
753     Diag(IILoc, IsTemplateName ? diag::err_no_template
754                                : diag::err_unknown_typename)
755         << II;
756   else if (DeclContext *DC = computeDeclContext(*SS, false))
757     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
758                                : diag::err_typename_nested_not_found)
759         << II << DC << SS->getRange();
760   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
761     SuggestedType =
762         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
763   } else if (isDependentScopeSpecifier(*SS)) {
764     unsigned DiagID = diag::err_typename_missing;
765     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
766       DiagID = diag::ext_typename_missing;
767 
768     Diag(SS->getRange().getBegin(), DiagID)
769       << SS->getScopeRep() << II->getName()
770       << SourceRange(SS->getRange().getBegin(), IILoc)
771       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
772     SuggestedType = ActOnTypenameType(S, SourceLocation(),
773                                       *SS, *II, IILoc).get();
774   } else {
775     assert(SS && SS->isInvalid() &&
776            "Invalid scope specifier has already been diagnosed");
777   }
778 }
779 
780 /// Determine whether the given result set contains either a type name
781 /// or
782 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
783   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
784                        NextToken.is(tok::less);
785 
786   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
787     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
788       return true;
789 
790     if (CheckTemplate && isa<TemplateDecl>(*I))
791       return true;
792   }
793 
794   return false;
795 }
796 
797 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
798                                     Scope *S, CXXScopeSpec &SS,
799                                     IdentifierInfo *&Name,
800                                     SourceLocation NameLoc) {
801   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
802   SemaRef.LookupParsedName(R, S, &SS);
803   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
804     StringRef FixItTagName;
805     switch (Tag->getTagKind()) {
806       case TTK_Class:
807         FixItTagName = "class ";
808         break;
809 
810       case TTK_Enum:
811         FixItTagName = "enum ";
812         break;
813 
814       case TTK_Struct:
815         FixItTagName = "struct ";
816         break;
817 
818       case TTK_Interface:
819         FixItTagName = "__interface ";
820         break;
821 
822       case TTK_Union:
823         FixItTagName = "union ";
824         break;
825     }
826 
827     StringRef TagName = FixItTagName.drop_back();
828     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
829       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
830       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
831 
832     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
833          I != IEnd; ++I)
834       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
835         << Name << TagName;
836 
837     // Replace lookup results with just the tag decl.
838     Result.clear(Sema::LookupTagName);
839     SemaRef.LookupParsedName(Result, S, &SS);
840     return true;
841   }
842 
843   return false;
844 }
845 
846 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
847 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
848                                   QualType T, SourceLocation NameLoc) {
849   ASTContext &Context = S.Context;
850 
851   TypeLocBuilder Builder;
852   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
853 
854   T = S.getElaboratedType(ETK_None, SS, T);
855   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
856   ElabTL.setElaboratedKeywordLoc(SourceLocation());
857   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
858   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
859 }
860 
861 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
862                                             IdentifierInfo *&Name,
863                                             SourceLocation NameLoc,
864                                             const Token &NextToken,
865                                             CorrectionCandidateCallback *CCC) {
866   DeclarationNameInfo NameInfo(Name, NameLoc);
867   ObjCMethodDecl *CurMethod = getCurMethodDecl();
868 
869   assert(NextToken.isNot(tok::coloncolon) &&
870          "parse nested name specifiers before calling ClassifyName");
871   if (getLangOpts().CPlusPlus && SS.isSet() &&
872       isCurrentClassName(*Name, S, &SS)) {
873     // Per [class.qual]p2, this names the constructors of SS, not the
874     // injected-class-name. We don't have a classification for that.
875     // There's not much point caching this result, since the parser
876     // will reject it later.
877     return NameClassification::Unknown();
878   }
879 
880   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
881   LookupParsedName(Result, S, &SS, !CurMethod);
882 
883   if (SS.isInvalid())
884     return NameClassification::Error();
885 
886   // For unqualified lookup in a class template in MSVC mode, look into
887   // dependent base classes where the primary class template is known.
888   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
889     if (ParsedType TypeInBase =
890             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
891       return TypeInBase;
892   }
893 
894   // Perform lookup for Objective-C instance variables (including automatically
895   // synthesized instance variables), if we're in an Objective-C method.
896   // FIXME: This lookup really, really needs to be folded in to the normal
897   // unqualified lookup mechanism.
898   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
899     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
900     if (Ivar.isInvalid())
901       return NameClassification::Error();
902     if (Ivar.isUsable())
903       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
904 
905     // We defer builtin creation until after ivar lookup inside ObjC methods.
906     if (Result.empty())
907       LookupBuiltin(Result);
908   }
909 
910   bool SecondTry = false;
911   bool IsFilteredTemplateName = false;
912 
913 Corrected:
914   switch (Result.getResultKind()) {
915   case LookupResult::NotFound:
916     // If an unqualified-id is followed by a '(', then we have a function
917     // call.
918     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
919       // In C++, this is an ADL-only call.
920       // FIXME: Reference?
921       if (getLangOpts().CPlusPlus)
922         return NameClassification::UndeclaredNonType();
923 
924       // C90 6.3.2.2:
925       //   If the expression that precedes the parenthesized argument list in a
926       //   function call consists solely of an identifier, and if no
927       //   declaration is visible for this identifier, the identifier is
928       //   implicitly declared exactly as if, in the innermost block containing
929       //   the function call, the declaration
930       //
931       //     extern int identifier ();
932       //
933       //   appeared.
934       //
935       // We also allow this in C99 as an extension.
936       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
937         return NameClassification::NonType(D);
938     }
939 
940     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
941       // In C++20 onwards, this could be an ADL-only call to a function
942       // template, and we're required to assume that this is a template name.
943       //
944       // FIXME: Find a way to still do typo correction in this case.
945       TemplateName Template =
946           Context.getAssumedTemplateName(NameInfo.getName());
947       return NameClassification::UndeclaredTemplate(Template);
948     }
949 
950     // In C, we first see whether there is a tag type by the same name, in
951     // which case it's likely that the user just forgot to write "enum",
952     // "struct", or "union".
953     if (!getLangOpts().CPlusPlus && !SecondTry &&
954         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
955       break;
956     }
957 
958     // Perform typo correction to determine if there is another name that is
959     // close to this name.
960     if (!SecondTry && CCC) {
961       SecondTry = true;
962       if (TypoCorrection Corrected =
963               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
964                           &SS, *CCC, CTK_ErrorRecovery)) {
965         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
966         unsigned QualifiedDiag = diag::err_no_member_suggest;
967 
968         NamedDecl *FirstDecl = Corrected.getFoundDecl();
969         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
970         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
971             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
972           UnqualifiedDiag = diag::err_no_template_suggest;
973           QualifiedDiag = diag::err_no_member_template_suggest;
974         } else if (UnderlyingFirstDecl &&
975                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
976                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
977                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
978           UnqualifiedDiag = diag::err_unknown_typename_suggest;
979           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
980         }
981 
982         if (SS.isEmpty()) {
983           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
984         } else {// FIXME: is this even reachable? Test it.
985           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
986           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
987                                   Name->getName().equals(CorrectedStr);
988           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
989                                     << Name << computeDeclContext(SS, false)
990                                     << DroppedSpecifier << SS.getRange());
991         }
992 
993         // Update the name, so that the caller has the new name.
994         Name = Corrected.getCorrectionAsIdentifierInfo();
995 
996         // Typo correction corrected to a keyword.
997         if (Corrected.isKeyword())
998           return Name;
999 
1000         // Also update the LookupResult...
1001         // FIXME: This should probably go away at some point
1002         Result.clear();
1003         Result.setLookupName(Corrected.getCorrection());
1004         if (FirstDecl)
1005           Result.addDecl(FirstDecl);
1006 
1007         // If we found an Objective-C instance variable, let
1008         // LookupInObjCMethod build the appropriate expression to
1009         // reference the ivar.
1010         // FIXME: This is a gross hack.
1011         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1012           DeclResult R =
1013               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1014           if (R.isInvalid())
1015             return NameClassification::Error();
1016           if (R.isUsable())
1017             return NameClassification::NonType(Ivar);
1018         }
1019 
1020         goto Corrected;
1021       }
1022     }
1023 
1024     // We failed to correct; just fall through and let the parser deal with it.
1025     Result.suppressDiagnostics();
1026     return NameClassification::Unknown();
1027 
1028   case LookupResult::NotFoundInCurrentInstantiation: {
1029     // We performed name lookup into the current instantiation, and there were
1030     // dependent bases, so we treat this result the same way as any other
1031     // dependent nested-name-specifier.
1032 
1033     // C++ [temp.res]p2:
1034     //   A name used in a template declaration or definition and that is
1035     //   dependent on a template-parameter is assumed not to name a type
1036     //   unless the applicable name lookup finds a type name or the name is
1037     //   qualified by the keyword typename.
1038     //
1039     // FIXME: If the next token is '<', we might want to ask the parser to
1040     // perform some heroics to see if we actually have a
1041     // template-argument-list, which would indicate a missing 'template'
1042     // keyword here.
1043     return NameClassification::DependentNonType();
1044   }
1045 
1046   case LookupResult::Found:
1047   case LookupResult::FoundOverloaded:
1048   case LookupResult::FoundUnresolvedValue:
1049     break;
1050 
1051   case LookupResult::Ambiguous:
1052     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1053         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1054                                       /*AllowDependent=*/false)) {
1055       // C++ [temp.local]p3:
1056       //   A lookup that finds an injected-class-name (10.2) can result in an
1057       //   ambiguity in certain cases (for example, if it is found in more than
1058       //   one base class). If all of the injected-class-names that are found
1059       //   refer to specializations of the same class template, and if the name
1060       //   is followed by a template-argument-list, the reference refers to the
1061       //   class template itself and not a specialization thereof, and is not
1062       //   ambiguous.
1063       //
1064       // This filtering can make an ambiguous result into an unambiguous one,
1065       // so try again after filtering out template names.
1066       FilterAcceptableTemplateNames(Result);
1067       if (!Result.isAmbiguous()) {
1068         IsFilteredTemplateName = true;
1069         break;
1070       }
1071     }
1072 
1073     // Diagnose the ambiguity and return an error.
1074     return NameClassification::Error();
1075   }
1076 
1077   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1078       (IsFilteredTemplateName ||
1079        hasAnyAcceptableTemplateNames(
1080            Result, /*AllowFunctionTemplates=*/true,
1081            /*AllowDependent=*/false,
1082            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1083                getLangOpts().CPlusPlus20))) {
1084     // C++ [temp.names]p3:
1085     //   After name lookup (3.4) finds that a name is a template-name or that
1086     //   an operator-function-id or a literal- operator-id refers to a set of
1087     //   overloaded functions any member of which is a function template if
1088     //   this is followed by a <, the < is always taken as the delimiter of a
1089     //   template-argument-list and never as the less-than operator.
1090     // C++2a [temp.names]p2:
1091     //   A name is also considered to refer to a template if it is an
1092     //   unqualified-id followed by a < and name lookup finds either one
1093     //   or more functions or finds nothing.
1094     if (!IsFilteredTemplateName)
1095       FilterAcceptableTemplateNames(Result);
1096 
1097     bool IsFunctionTemplate;
1098     bool IsVarTemplate;
1099     TemplateName Template;
1100     if (Result.end() - Result.begin() > 1) {
1101       IsFunctionTemplate = true;
1102       Template = Context.getOverloadedTemplateName(Result.begin(),
1103                                                    Result.end());
1104     } else if (!Result.empty()) {
1105       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1106           *Result.begin(), /*AllowFunctionTemplates=*/true,
1107           /*AllowDependent=*/false));
1108       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1109       IsVarTemplate = isa<VarTemplateDecl>(TD);
1110 
1111       if (SS.isNotEmpty())
1112         Template =
1113             Context.getQualifiedTemplateName(SS.getScopeRep(),
1114                                              /*TemplateKeyword=*/false, TD);
1115       else
1116         Template = TemplateName(TD);
1117     } else {
1118       // All results were non-template functions. This is a function template
1119       // name.
1120       IsFunctionTemplate = true;
1121       Template = Context.getAssumedTemplateName(NameInfo.getName());
1122     }
1123 
1124     if (IsFunctionTemplate) {
1125       // Function templates always go through overload resolution, at which
1126       // point we'll perform the various checks (e.g., accessibility) we need
1127       // to based on which function we selected.
1128       Result.suppressDiagnostics();
1129 
1130       return NameClassification::FunctionTemplate(Template);
1131     }
1132 
1133     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1134                          : NameClassification::TypeTemplate(Template);
1135   }
1136 
1137   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1138   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1139     DiagnoseUseOfDecl(Type, NameLoc);
1140     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1148   if (!Class) {
1149     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1150     if (ObjCCompatibleAliasDecl *Alias =
1151             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1152       Class = Alias->getClassInterface();
1153   }
1154 
1155   if (Class) {
1156     DiagnoseUseOfDecl(Class, NameLoc);
1157 
1158     if (NextToken.is(tok::period)) {
1159       // Interface. <something> is parsed as a property reference expression.
1160       // Just return "unknown" as a fall-through for now.
1161       Result.suppressDiagnostics();
1162       return NameClassification::Unknown();
1163     }
1164 
1165     QualType T = Context.getObjCInterfaceType(Class);
1166     return ParsedType::make(T);
1167   }
1168 
1169   if (isa<ConceptDecl>(FirstDecl))
1170     return NameClassification::Concept(
1171         TemplateName(cast<TemplateDecl>(FirstDecl)));
1172 
1173   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1174     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1175     return NameClassification::Error();
1176   }
1177 
1178   // We can have a type template here if we're classifying a template argument.
1179   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1180       !isa<VarTemplateDecl>(FirstDecl))
1181     return NameClassification::TypeTemplate(
1182         TemplateName(cast<TemplateDecl>(FirstDecl)));
1183 
1184   // Check for a tag type hidden by a non-type decl in a few cases where it
1185   // seems likely a type is wanted instead of the non-type that was found.
1186   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1187   if ((NextToken.is(tok::identifier) ||
1188        (NextIsOp &&
1189         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1190       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1191     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1192     DiagnoseUseOfDecl(Type, NameLoc);
1193     QualType T = Context.getTypeDeclType(Type);
1194     if (SS.isNotEmpty())
1195       return buildNestedType(*this, SS, T, NameLoc);
1196     return ParsedType::make(T);
1197   }
1198 
1199   // If we already know which single declaration is referenced, just annotate
1200   // that declaration directly. Defer resolving even non-overloaded class
1201   // member accesses, as we need to defer certain access checks until we know
1202   // the context.
1203   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1204   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1205     return NameClassification::NonType(Result.getRepresentativeDecl());
1206 
1207   // Otherwise, this is an overload set that we will need to resolve later.
1208   Result.suppressDiagnostics();
1209   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1210       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1211       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1212       Result.begin(), Result.end()));
1213 }
1214 
1215 ExprResult
1216 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1217                                              SourceLocation NameLoc) {
1218   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1219   CXXScopeSpec SS;
1220   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1221   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1222 }
1223 
1224 ExprResult
1225 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1226                                             IdentifierInfo *Name,
1227                                             SourceLocation NameLoc,
1228                                             bool IsAddressOfOperand) {
1229   DeclarationNameInfo NameInfo(Name, NameLoc);
1230   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1231                                     NameInfo, IsAddressOfOperand,
1232                                     /*TemplateArgs=*/nullptr);
1233 }
1234 
1235 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1236                                               NamedDecl *Found,
1237                                               SourceLocation NameLoc,
1238                                               const Token &NextToken) {
1239   if (getCurMethodDecl() && SS.isEmpty())
1240     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1241       return BuildIvarRefExpr(S, NameLoc, Ivar);
1242 
1243   // Reconstruct the lookup result.
1244   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1245   Result.addDecl(Found);
1246   Result.resolveKind();
1247 
1248   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1249   return BuildDeclarationNameExpr(SS, Result, ADL);
1250 }
1251 
1252 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1253   // For an implicit class member access, transform the result into a member
1254   // access expression if necessary.
1255   auto *ULE = cast<UnresolvedLookupExpr>(E);
1256   if ((*ULE->decls_begin())->isCXXClassMember()) {
1257     CXXScopeSpec SS;
1258     SS.Adopt(ULE->getQualifierLoc());
1259 
1260     // Reconstruct the lookup result.
1261     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1262                         LookupOrdinaryName);
1263     Result.setNamingClass(ULE->getNamingClass());
1264     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1265       Result.addDecl(*I, I.getAccess());
1266     Result.resolveKind();
1267     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1268                                            nullptr, S);
1269   }
1270 
1271   // Otherwise, this is already in the form we needed, and no further checks
1272   // are necessary.
1273   return ULE;
1274 }
1275 
1276 Sema::TemplateNameKindForDiagnostics
1277 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1278   auto *TD = Name.getAsTemplateDecl();
1279   if (!TD)
1280     return TemplateNameKindForDiagnostics::DependentTemplate;
1281   if (isa<ClassTemplateDecl>(TD))
1282     return TemplateNameKindForDiagnostics::ClassTemplate;
1283   if (isa<FunctionTemplateDecl>(TD))
1284     return TemplateNameKindForDiagnostics::FunctionTemplate;
1285   if (isa<VarTemplateDecl>(TD))
1286     return TemplateNameKindForDiagnostics::VarTemplate;
1287   if (isa<TypeAliasTemplateDecl>(TD))
1288     return TemplateNameKindForDiagnostics::AliasTemplate;
1289   if (isa<TemplateTemplateParmDecl>(TD))
1290     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1291   if (isa<ConceptDecl>(TD))
1292     return TemplateNameKindForDiagnostics::Concept;
1293   return TemplateNameKindForDiagnostics::DependentTemplate;
1294 }
1295 
1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1297   assert(DC->getLexicalParent() == CurContext &&
1298       "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = DC;
1300   S->setEntity(DC);
1301 }
1302 
1303 void Sema::PopDeclContext() {
1304   assert(CurContext && "DeclContext imbalance!");
1305 
1306   CurContext = CurContext->getLexicalParent();
1307   assert(CurContext && "Popped translation unit!");
1308 }
1309 
1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1311                                                                     Decl *D) {
1312   // Unlike PushDeclContext, the context to which we return is not necessarily
1313   // the containing DC of TD, because the new context will be some pre-existing
1314   // TagDecl definition instead of a fresh one.
1315   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1316   CurContext = cast<TagDecl>(D)->getDefinition();
1317   assert(CurContext && "skipping definition of undefined tag");
1318   // Start lookups from the parent of the current context; we don't want to look
1319   // into the pre-existing complete definition.
1320   S->setEntity(CurContext->getLookupParent());
1321   return Result;
1322 }
1323 
1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1325   CurContext = static_cast<decltype(CurContext)>(Context);
1326 }
1327 
1328 /// EnterDeclaratorContext - Used when we must lookup names in the context
1329 /// of a declarator's nested name specifier.
1330 ///
1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1332   // C++0x [basic.lookup.unqual]p13:
1333   //   A name used in the definition of a static data member of class
1334   //   X (after the qualified-id of the static member) is looked up as
1335   //   if the name was used in a member function of X.
1336   // C++0x [basic.lookup.unqual]p14:
1337   //   If a variable member of a namespace is defined outside of the
1338   //   scope of its namespace then any name used in the definition of
1339   //   the variable member (after the declarator-id) is looked up as
1340   //   if the definition of the variable member occurred in its
1341   //   namespace.
1342   // Both of these imply that we should push a scope whose context
1343   // is the semantic context of the declaration.  We can't use
1344   // PushDeclContext here because that context is not necessarily
1345   // lexically contained in the current context.  Fortunately,
1346   // the containing scope should have the appropriate information.
1347 
1348   assert(!S->getEntity() && "scope already has entity");
1349 
1350 #ifndef NDEBUG
1351   Scope *Ancestor = S->getParent();
1352   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1353   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1354 #endif
1355 
1356   CurContext = DC;
1357   S->setEntity(DC);
1358 
1359   if (S->getParent()->isTemplateParamScope()) {
1360     // Also set the corresponding entities for all immediately-enclosing
1361     // template parameter scopes.
1362     EnterTemplatedContext(S->getParent(), DC);
1363   }
1364 }
1365 
1366 void Sema::ExitDeclaratorContext(Scope *S) {
1367   assert(S->getEntity() == CurContext && "Context imbalance!");
1368 
1369   // Switch back to the lexical context.  The safety of this is
1370   // enforced by an assert in EnterDeclaratorContext.
1371   Scope *Ancestor = S->getParent();
1372   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1373   CurContext = Ancestor->getEntity();
1374 
1375   // We don't need to do anything with the scope, which is going to
1376   // disappear.
1377 }
1378 
1379 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1380   assert(S->isTemplateParamScope() &&
1381          "expected to be initializing a template parameter scope");
1382 
1383   // C++20 [temp.local]p7:
1384   //   In the definition of a member of a class template that appears outside
1385   //   of the class template definition, the name of a member of the class
1386   //   template hides the name of a template-parameter of any enclosing class
1387   //   templates (but not a template-parameter of the member if the member is a
1388   //   class or function template).
1389   // C++20 [temp.local]p9:
1390   //   In the definition of a class template or in the definition of a member
1391   //   of such a template that appears outside of the template definition, for
1392   //   each non-dependent base class (13.8.2.1), if the name of the base class
1393   //   or the name of a member of the base class is the same as the name of a
1394   //   template-parameter, the base class name or member name hides the
1395   //   template-parameter name (6.4.10).
1396   //
1397   // This means that a template parameter scope should be searched immediately
1398   // after searching the DeclContext for which it is a template parameter
1399   // scope. For example, for
1400   //   template<typename T> template<typename U> template<typename V>
1401   //     void N::A<T>::B<U>::f(...)
1402   // we search V then B<U> (and base classes) then U then A<T> (and base
1403   // classes) then T then N then ::.
1404   unsigned ScopeDepth = getTemplateDepth(S);
1405   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1406     DeclContext *SearchDCAfterScope = DC;
1407     for (; DC; DC = DC->getLookupParent()) {
1408       if (const TemplateParameterList *TPL =
1409               cast<Decl>(DC)->getDescribedTemplateParams()) {
1410         unsigned DCDepth = TPL->getDepth() + 1;
1411         if (DCDepth > ScopeDepth)
1412           continue;
1413         if (ScopeDepth == DCDepth)
1414           SearchDCAfterScope = DC = DC->getLookupParent();
1415         break;
1416       }
1417     }
1418     S->setLookupEntity(SearchDCAfterScope);
1419   }
1420 }
1421 
1422 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1423   // We assume that the caller has already called
1424   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1425   FunctionDecl *FD = D->getAsFunction();
1426   if (!FD)
1427     return;
1428 
1429   // Same implementation as PushDeclContext, but enters the context
1430   // from the lexical parent, rather than the top-level class.
1431   assert(CurContext == FD->getLexicalParent() &&
1432     "The next DeclContext should be lexically contained in the current one.");
1433   CurContext = FD;
1434   S->setEntity(CurContext);
1435 
1436   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1437     ParmVarDecl *Param = FD->getParamDecl(P);
1438     // If the parameter has an identifier, then add it to the scope
1439     if (Param->getIdentifier()) {
1440       S->AddDecl(Param);
1441       IdResolver.AddDecl(Param);
1442     }
1443   }
1444 }
1445 
1446 void Sema::ActOnExitFunctionContext() {
1447   // Same implementation as PopDeclContext, but returns to the lexical parent,
1448   // rather than the top-level class.
1449   assert(CurContext && "DeclContext imbalance!");
1450   CurContext = CurContext->getLexicalParent();
1451   assert(CurContext && "Popped translation unit!");
1452 }
1453 
1454 /// Determine whether we allow overloading of the function
1455 /// PrevDecl with another declaration.
1456 ///
1457 /// This routine determines whether overloading is possible, not
1458 /// whether some new function is actually an overload. It will return
1459 /// true in C++ (where we can always provide overloads) or, as an
1460 /// extension, in C when the previous function is already an
1461 /// overloaded function declaration or has the "overloadable"
1462 /// attribute.
1463 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1464                                        ASTContext &Context,
1465                                        const FunctionDecl *New) {
1466   if (Context.getLangOpts().CPlusPlus)
1467     return true;
1468 
1469   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1470     return true;
1471 
1472   return Previous.getResultKind() == LookupResult::Found &&
1473          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1474           New->hasAttr<OverloadableAttr>());
1475 }
1476 
1477 /// Add this decl to the scope shadowed decl chains.
1478 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1479   // Move up the scope chain until we find the nearest enclosing
1480   // non-transparent context. The declaration will be introduced into this
1481   // scope.
1482   while (S->getEntity() && S->getEntity()->isTransparentContext())
1483     S = S->getParent();
1484 
1485   // Add scoped declarations into their context, so that they can be
1486   // found later. Declarations without a context won't be inserted
1487   // into any context.
1488   if (AddToContext)
1489     CurContext->addDecl(D);
1490 
1491   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1492   // are function-local declarations.
1493   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1494     return;
1495 
1496   // Template instantiations should also not be pushed into scope.
1497   if (isa<FunctionDecl>(D) &&
1498       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1499     return;
1500 
1501   // If this replaces anything in the current scope,
1502   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1503                                IEnd = IdResolver.end();
1504   for (; I != IEnd; ++I) {
1505     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1506       S->RemoveDecl(*I);
1507       IdResolver.RemoveDecl(*I);
1508 
1509       // Should only need to replace one decl.
1510       break;
1511     }
1512   }
1513 
1514   S->AddDecl(D);
1515 
1516   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1517     // Implicitly-generated labels may end up getting generated in an order that
1518     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1519     // the label at the appropriate place in the identifier chain.
1520     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1521       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1522       if (IDC == CurContext) {
1523         if (!S->isDeclScope(*I))
1524           continue;
1525       } else if (IDC->Encloses(CurContext))
1526         break;
1527     }
1528 
1529     IdResolver.InsertDeclAfter(I, D);
1530   } else {
1531     IdResolver.AddDecl(D);
1532   }
1533   warnOnReservedIdentifier(D);
1534 }
1535 
1536 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1537                          bool AllowInlineNamespace) {
1538   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1539 }
1540 
1541 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1542   DeclContext *TargetDC = DC->getPrimaryContext();
1543   do {
1544     if (DeclContext *ScopeDC = S->getEntity())
1545       if (ScopeDC->getPrimaryContext() == TargetDC)
1546         return S;
1547   } while ((S = S->getParent()));
1548 
1549   return nullptr;
1550 }
1551 
1552 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1553                                             DeclContext*,
1554                                             ASTContext&);
1555 
1556 /// Filters out lookup results that don't fall within the given scope
1557 /// as determined by isDeclInScope.
1558 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1559                                 bool ConsiderLinkage,
1560                                 bool AllowInlineNamespace) {
1561   LookupResult::Filter F = R.makeFilter();
1562   while (F.hasNext()) {
1563     NamedDecl *D = F.next();
1564 
1565     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1566       continue;
1567 
1568     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1569       continue;
1570 
1571     F.erase();
1572   }
1573 
1574   F.done();
1575 }
1576 
1577 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1578 /// have compatible owning modules.
1579 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1580   // FIXME: The Modules TS is not clear about how friend declarations are
1581   // to be treated. It's not meaningful to have different owning modules for
1582   // linkage in redeclarations of the same entity, so for now allow the
1583   // redeclaration and change the owning modules to match.
1584   if (New->getFriendObjectKind() &&
1585       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1586     New->setLocalOwningModule(Old->getOwningModule());
1587     makeMergedDefinitionVisible(New);
1588     return false;
1589   }
1590 
1591   Module *NewM = New->getOwningModule();
1592   Module *OldM = Old->getOwningModule();
1593 
1594   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1595     NewM = NewM->Parent;
1596   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1597     OldM = OldM->Parent;
1598 
1599   if (NewM == OldM)
1600     return false;
1601 
1602   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1603   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1604   if (NewIsModuleInterface || OldIsModuleInterface) {
1605     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1606     //   if a declaration of D [...] appears in the purview of a module, all
1607     //   other such declarations shall appear in the purview of the same module
1608     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1609       << New
1610       << NewIsModuleInterface
1611       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1612       << OldIsModuleInterface
1613       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1614     Diag(Old->getLocation(), diag::note_previous_declaration);
1615     New->setInvalidDecl();
1616     return true;
1617   }
1618 
1619   return false;
1620 }
1621 
1622 static bool isUsingDecl(NamedDecl *D) {
1623   return isa<UsingShadowDecl>(D) ||
1624          isa<UnresolvedUsingTypenameDecl>(D) ||
1625          isa<UnresolvedUsingValueDecl>(D);
1626 }
1627 
1628 /// Removes using shadow declarations from the lookup results.
1629 static void RemoveUsingDecls(LookupResult &R) {
1630   LookupResult::Filter F = R.makeFilter();
1631   while (F.hasNext())
1632     if (isUsingDecl(F.next()))
1633       F.erase();
1634 
1635   F.done();
1636 }
1637 
1638 /// Check for this common pattern:
1639 /// @code
1640 /// class S {
1641 ///   S(const S&); // DO NOT IMPLEMENT
1642 ///   void operator=(const S&); // DO NOT IMPLEMENT
1643 /// };
1644 /// @endcode
1645 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1646   // FIXME: Should check for private access too but access is set after we get
1647   // the decl here.
1648   if (D->doesThisDeclarationHaveABody())
1649     return false;
1650 
1651   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1652     return CD->isCopyConstructor();
1653   return D->isCopyAssignmentOperator();
1654 }
1655 
1656 // We need this to handle
1657 //
1658 // typedef struct {
1659 //   void *foo() { return 0; }
1660 // } A;
1661 //
1662 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1663 // for example. If 'A', foo will have external linkage. If we have '*A',
1664 // foo will have no linkage. Since we can't know until we get to the end
1665 // of the typedef, this function finds out if D might have non-external linkage.
1666 // Callers should verify at the end of the TU if it D has external linkage or
1667 // not.
1668 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1669   const DeclContext *DC = D->getDeclContext();
1670   while (!DC->isTranslationUnit()) {
1671     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1672       if (!RD->hasNameForLinkage())
1673         return true;
1674     }
1675     DC = DC->getParent();
1676   }
1677 
1678   return !D->isExternallyVisible();
1679 }
1680 
1681 // FIXME: This needs to be refactored; some other isInMainFile users want
1682 // these semantics.
1683 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1684   if (S.TUKind != TU_Complete)
1685     return false;
1686   return S.SourceMgr.isInMainFile(Loc);
1687 }
1688 
1689 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1690   assert(D);
1691 
1692   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1693     return false;
1694 
1695   // Ignore all entities declared within templates, and out-of-line definitions
1696   // of members of class templates.
1697   if (D->getDeclContext()->isDependentContext() ||
1698       D->getLexicalDeclContext()->isDependentContext())
1699     return false;
1700 
1701   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1702     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1703       return false;
1704     // A non-out-of-line declaration of a member specialization was implicitly
1705     // instantiated; it's the out-of-line declaration that we're interested in.
1706     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1707         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1708       return false;
1709 
1710     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1711       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1712         return false;
1713     } else {
1714       // 'static inline' functions are defined in headers; don't warn.
1715       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1716         return false;
1717     }
1718 
1719     if (FD->doesThisDeclarationHaveABody() &&
1720         Context.DeclMustBeEmitted(FD))
1721       return false;
1722   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1723     // Constants and utility variables are defined in headers with internal
1724     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1725     // like "inline".)
1726     if (!isMainFileLoc(*this, VD->getLocation()))
1727       return false;
1728 
1729     if (Context.DeclMustBeEmitted(VD))
1730       return false;
1731 
1732     if (VD->isStaticDataMember() &&
1733         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1734       return false;
1735     if (VD->isStaticDataMember() &&
1736         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1737         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1738       return false;
1739 
1740     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1741       return false;
1742   } else {
1743     return false;
1744   }
1745 
1746   // Only warn for unused decls internal to the translation unit.
1747   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1748   // for inline functions defined in the main source file, for instance.
1749   return mightHaveNonExternalLinkage(D);
1750 }
1751 
1752 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1753   if (!D)
1754     return;
1755 
1756   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1757     const FunctionDecl *First = FD->getFirstDecl();
1758     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1759       return; // First should already be in the vector.
1760   }
1761 
1762   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1763     const VarDecl *First = VD->getFirstDecl();
1764     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1765       return; // First should already be in the vector.
1766   }
1767 
1768   if (ShouldWarnIfUnusedFileScopedDecl(D))
1769     UnusedFileScopedDecls.push_back(D);
1770 }
1771 
1772 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1773   if (D->isInvalidDecl())
1774     return false;
1775 
1776   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1777     // For a decomposition declaration, warn if none of the bindings are
1778     // referenced, instead of if the variable itself is referenced (which
1779     // it is, by the bindings' expressions).
1780     for (auto *BD : DD->bindings())
1781       if (BD->isReferenced())
1782         return false;
1783   } else if (!D->getDeclName()) {
1784     return false;
1785   } else if (D->isReferenced() || D->isUsed()) {
1786     return false;
1787   }
1788 
1789   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1790     return false;
1791 
1792   if (isa<LabelDecl>(D))
1793     return true;
1794 
1795   // Except for labels, we only care about unused decls that are local to
1796   // functions.
1797   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1798   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1799     // For dependent types, the diagnostic is deferred.
1800     WithinFunction =
1801         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1802   if (!WithinFunction)
1803     return false;
1804 
1805   if (isa<TypedefNameDecl>(D))
1806     return true;
1807 
1808   // White-list anything that isn't a local variable.
1809   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1810     return false;
1811 
1812   // Types of valid local variables should be complete, so this should succeed.
1813   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1814 
1815     // White-list anything with an __attribute__((unused)) type.
1816     const auto *Ty = VD->getType().getTypePtr();
1817 
1818     // Only look at the outermost level of typedef.
1819     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1820       if (TT->getDecl()->hasAttr<UnusedAttr>())
1821         return false;
1822     }
1823 
1824     // If we failed to complete the type for some reason, or if the type is
1825     // dependent, don't diagnose the variable.
1826     if (Ty->isIncompleteType() || Ty->isDependentType())
1827       return false;
1828 
1829     // Look at the element type to ensure that the warning behaviour is
1830     // consistent for both scalars and arrays.
1831     Ty = Ty->getBaseElementTypeUnsafe();
1832 
1833     if (const TagType *TT = Ty->getAs<TagType>()) {
1834       const TagDecl *Tag = TT->getDecl();
1835       if (Tag->hasAttr<UnusedAttr>())
1836         return false;
1837 
1838       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1839         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1840           return false;
1841 
1842         if (const Expr *Init = VD->getInit()) {
1843           if (const ExprWithCleanups *Cleanups =
1844                   dyn_cast<ExprWithCleanups>(Init))
1845             Init = Cleanups->getSubExpr();
1846           const CXXConstructExpr *Construct =
1847             dyn_cast<CXXConstructExpr>(Init);
1848           if (Construct && !Construct->isElidable()) {
1849             CXXConstructorDecl *CD = Construct->getConstructor();
1850             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1851                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1852               return false;
1853           }
1854 
1855           // Suppress the warning if we don't know how this is constructed, and
1856           // it could possibly be non-trivial constructor.
1857           if (Init->isTypeDependent())
1858             for (const CXXConstructorDecl *Ctor : RD->ctors())
1859               if (!Ctor->isTrivial())
1860                 return false;
1861         }
1862       }
1863     }
1864 
1865     // TODO: __attribute__((unused)) templates?
1866   }
1867 
1868   return true;
1869 }
1870 
1871 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1872                                      FixItHint &Hint) {
1873   if (isa<LabelDecl>(D)) {
1874     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1875         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1876         true);
1877     if (AfterColon.isInvalid())
1878       return;
1879     Hint = FixItHint::CreateRemoval(
1880         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1881   }
1882 }
1883 
1884 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1885   if (D->getTypeForDecl()->isDependentType())
1886     return;
1887 
1888   for (auto *TmpD : D->decls()) {
1889     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1890       DiagnoseUnusedDecl(T);
1891     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1892       DiagnoseUnusedNestedTypedefs(R);
1893   }
1894 }
1895 
1896 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1897 /// unless they are marked attr(unused).
1898 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1899   if (!ShouldDiagnoseUnusedDecl(D))
1900     return;
1901 
1902   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1903     // typedefs can be referenced later on, so the diagnostics are emitted
1904     // at end-of-translation-unit.
1905     UnusedLocalTypedefNameCandidates.insert(TD);
1906     return;
1907   }
1908 
1909   FixItHint Hint;
1910   GenerateFixForUnusedDecl(D, Context, Hint);
1911 
1912   unsigned DiagID;
1913   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1914     DiagID = diag::warn_unused_exception_param;
1915   else if (isa<LabelDecl>(D))
1916     DiagID = diag::warn_unused_label;
1917   else
1918     DiagID = diag::warn_unused_variable;
1919 
1920   Diag(D->getLocation(), DiagID) << D << Hint;
1921 }
1922 
1923 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1924   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
1925   // it's not really unused.
1926   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
1927       VD->hasAttr<CleanupAttr>())
1928     return;
1929 
1930   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1931 
1932   if (Ty->isReferenceType() || Ty->isDependentType())
1933     return;
1934 
1935   if (const TagType *TT = Ty->getAs<TagType>()) {
1936     const TagDecl *Tag = TT->getDecl();
1937     if (Tag->hasAttr<UnusedAttr>())
1938       return;
1939     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1940     // mimic gcc's behavior.
1941     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1942       if (!RD->hasAttr<WarnUnusedAttr>())
1943         return;
1944     }
1945   }
1946 
1947   auto iter = RefsMinusAssignments.find(VD);
1948   if (iter == RefsMinusAssignments.end())
1949     return;
1950 
1951   assert(iter->getSecond() >= 0 &&
1952          "Found a negative number of references to a VarDecl");
1953   if (iter->getSecond() != 0)
1954     return;
1955   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1956                                          : diag::warn_unused_but_set_variable;
1957   Diag(VD->getLocation(), DiagID) << VD;
1958 }
1959 
1960 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1961   // Verify that we have no forward references left.  If so, there was a goto
1962   // or address of a label taken, but no definition of it.  Label fwd
1963   // definitions are indicated with a null substmt which is also not a resolved
1964   // MS inline assembly label name.
1965   bool Diagnose = false;
1966   if (L->isMSAsmLabel())
1967     Diagnose = !L->isResolvedMSAsmLabel();
1968   else
1969     Diagnose = L->getStmt() == nullptr;
1970   if (Diagnose)
1971     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1972 }
1973 
1974 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1975   S->mergeNRVOIntoParent();
1976 
1977   if (S->decl_empty()) return;
1978   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1979          "Scope shouldn't contain decls!");
1980 
1981   for (auto *TmpD : S->decls()) {
1982     assert(TmpD && "This decl didn't get pushed??");
1983 
1984     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1985     NamedDecl *D = cast<NamedDecl>(TmpD);
1986 
1987     // Diagnose unused variables in this scope.
1988     if (!S->hasUnrecoverableErrorOccurred()) {
1989       DiagnoseUnusedDecl(D);
1990       if (const auto *RD = dyn_cast<RecordDecl>(D))
1991         DiagnoseUnusedNestedTypedefs(RD);
1992       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1993         DiagnoseUnusedButSetDecl(VD);
1994         RefsMinusAssignments.erase(VD);
1995       }
1996     }
1997 
1998     if (!D->getDeclName()) continue;
1999 
2000     // If this was a forward reference to a label, verify it was defined.
2001     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2002       CheckPoppedLabel(LD, *this);
2003 
2004     // Remove this name from our lexical scope, and warn on it if we haven't
2005     // already.
2006     IdResolver.RemoveDecl(D);
2007     auto ShadowI = ShadowingDecls.find(D);
2008     if (ShadowI != ShadowingDecls.end()) {
2009       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2010         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2011             << D << FD << FD->getParent();
2012         Diag(FD->getLocation(), diag::note_previous_declaration);
2013       }
2014       ShadowingDecls.erase(ShadowI);
2015     }
2016   }
2017 }
2018 
2019 /// Look for an Objective-C class in the translation unit.
2020 ///
2021 /// \param Id The name of the Objective-C class we're looking for. If
2022 /// typo-correction fixes this name, the Id will be updated
2023 /// to the fixed name.
2024 ///
2025 /// \param IdLoc The location of the name in the translation unit.
2026 ///
2027 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2028 /// if there is no class with the given name.
2029 ///
2030 /// \returns The declaration of the named Objective-C class, or NULL if the
2031 /// class could not be found.
2032 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2033                                               SourceLocation IdLoc,
2034                                               bool DoTypoCorrection) {
2035   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2036   // creation from this context.
2037   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2038 
2039   if (!IDecl && DoTypoCorrection) {
2040     // Perform typo correction at the given location, but only if we
2041     // find an Objective-C class name.
2042     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2043     if (TypoCorrection C =
2044             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2045                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2046       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2047       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2048       Id = IDecl->getIdentifier();
2049     }
2050   }
2051   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2052   // This routine must always return a class definition, if any.
2053   if (Def && Def->getDefinition())
2054       Def = Def->getDefinition();
2055   return Def;
2056 }
2057 
2058 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2059 /// from S, where a non-field would be declared. This routine copes
2060 /// with the difference between C and C++ scoping rules in structs and
2061 /// unions. For example, the following code is well-formed in C but
2062 /// ill-formed in C++:
2063 /// @code
2064 /// struct S6 {
2065 ///   enum { BAR } e;
2066 /// };
2067 ///
2068 /// void test_S6() {
2069 ///   struct S6 a;
2070 ///   a.e = BAR;
2071 /// }
2072 /// @endcode
2073 /// For the declaration of BAR, this routine will return a different
2074 /// scope. The scope S will be the scope of the unnamed enumeration
2075 /// within S6. In C++, this routine will return the scope associated
2076 /// with S6, because the enumeration's scope is a transparent
2077 /// context but structures can contain non-field names. In C, this
2078 /// routine will return the translation unit scope, since the
2079 /// enumeration's scope is a transparent context and structures cannot
2080 /// contain non-field names.
2081 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2082   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2083          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2084          (S->isClassScope() && !getLangOpts().CPlusPlus))
2085     S = S->getParent();
2086   return S;
2087 }
2088 
2089 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2090                                ASTContext::GetBuiltinTypeError Error) {
2091   switch (Error) {
2092   case ASTContext::GE_None:
2093     return "";
2094   case ASTContext::GE_Missing_type:
2095     return BuiltinInfo.getHeaderName(ID);
2096   case ASTContext::GE_Missing_stdio:
2097     return "stdio.h";
2098   case ASTContext::GE_Missing_setjmp:
2099     return "setjmp.h";
2100   case ASTContext::GE_Missing_ucontext:
2101     return "ucontext.h";
2102   }
2103   llvm_unreachable("unhandled error kind");
2104 }
2105 
2106 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2107                                   unsigned ID, SourceLocation Loc) {
2108   DeclContext *Parent = Context.getTranslationUnitDecl();
2109 
2110   if (getLangOpts().CPlusPlus) {
2111     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2112         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2113     CLinkageDecl->setImplicit();
2114     Parent->addDecl(CLinkageDecl);
2115     Parent = CLinkageDecl;
2116   }
2117 
2118   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2119                                            /*TInfo=*/nullptr, SC_Extern,
2120                                            getCurFPFeatures().isFPConstrained(),
2121                                            false, Type->isFunctionProtoType());
2122   New->setImplicit();
2123   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2124 
2125   // Create Decl objects for each parameter, adding them to the
2126   // FunctionDecl.
2127   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2128     SmallVector<ParmVarDecl *, 16> Params;
2129     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2130       ParmVarDecl *parm = ParmVarDecl::Create(
2131           Context, New, SourceLocation(), SourceLocation(), nullptr,
2132           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2133       parm->setScopeInfo(0, i);
2134       Params.push_back(parm);
2135     }
2136     New->setParams(Params);
2137   }
2138 
2139   AddKnownFunctionAttributes(New);
2140   return New;
2141 }
2142 
2143 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2144 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2145 /// if we're creating this built-in in anticipation of redeclaring the
2146 /// built-in.
2147 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2148                                      Scope *S, bool ForRedeclaration,
2149                                      SourceLocation Loc) {
2150   LookupNecessaryTypesForBuiltin(S, ID);
2151 
2152   ASTContext::GetBuiltinTypeError Error;
2153   QualType R = Context.GetBuiltinType(ID, Error);
2154   if (Error) {
2155     if (!ForRedeclaration)
2156       return nullptr;
2157 
2158     // If we have a builtin without an associated type we should not emit a
2159     // warning when we were not able to find a type for it.
2160     if (Error == ASTContext::GE_Missing_type ||
2161         Context.BuiltinInfo.allowTypeMismatch(ID))
2162       return nullptr;
2163 
2164     // If we could not find a type for setjmp it is because the jmp_buf type was
2165     // not defined prior to the setjmp declaration.
2166     if (Error == ASTContext::GE_Missing_setjmp) {
2167       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2168           << Context.BuiltinInfo.getName(ID);
2169       return nullptr;
2170     }
2171 
2172     // Generally, we emit a warning that the declaration requires the
2173     // appropriate header.
2174     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2175         << getHeaderName(Context.BuiltinInfo, ID, Error)
2176         << Context.BuiltinInfo.getName(ID);
2177     return nullptr;
2178   }
2179 
2180   if (!ForRedeclaration &&
2181       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2182        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2183     Diag(Loc, diag::ext_implicit_lib_function_decl)
2184         << Context.BuiltinInfo.getName(ID) << R;
2185     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2186       Diag(Loc, diag::note_include_header_or_declare)
2187           << Header << Context.BuiltinInfo.getName(ID);
2188   }
2189 
2190   if (R.isNull())
2191     return nullptr;
2192 
2193   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2194   RegisterLocallyScopedExternCDecl(New, S);
2195 
2196   // TUScope is the translation-unit scope to insert this function into.
2197   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2198   // relate Scopes to DeclContexts, and probably eliminate CurContext
2199   // entirely, but we're not there yet.
2200   DeclContext *SavedContext = CurContext;
2201   CurContext = New->getDeclContext();
2202   PushOnScopeChains(New, TUScope);
2203   CurContext = SavedContext;
2204   return New;
2205 }
2206 
2207 /// Typedef declarations don't have linkage, but they still denote the same
2208 /// entity if their types are the same.
2209 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2210 /// isSameEntity.
2211 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2212                                                      TypedefNameDecl *Decl,
2213                                                      LookupResult &Previous) {
2214   // This is only interesting when modules are enabled.
2215   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2216     return;
2217 
2218   // Empty sets are uninteresting.
2219   if (Previous.empty())
2220     return;
2221 
2222   LookupResult::Filter Filter = Previous.makeFilter();
2223   while (Filter.hasNext()) {
2224     NamedDecl *Old = Filter.next();
2225 
2226     // Non-hidden declarations are never ignored.
2227     if (S.isVisible(Old))
2228       continue;
2229 
2230     // Declarations of the same entity are not ignored, even if they have
2231     // different linkages.
2232     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2233       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2234                                 Decl->getUnderlyingType()))
2235         continue;
2236 
2237       // If both declarations give a tag declaration a typedef name for linkage
2238       // purposes, then they declare the same entity.
2239       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2240           Decl->getAnonDeclWithTypedefName())
2241         continue;
2242     }
2243 
2244     Filter.erase();
2245   }
2246 
2247   Filter.done();
2248 }
2249 
2250 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2251   QualType OldType;
2252   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2253     OldType = OldTypedef->getUnderlyingType();
2254   else
2255     OldType = Context.getTypeDeclType(Old);
2256   QualType NewType = New->getUnderlyingType();
2257 
2258   if (NewType->isVariablyModifiedType()) {
2259     // Must not redefine a typedef with a variably-modified type.
2260     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2261     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2262       << Kind << NewType;
2263     if (Old->getLocation().isValid())
2264       notePreviousDefinition(Old, New->getLocation());
2265     New->setInvalidDecl();
2266     return true;
2267   }
2268 
2269   if (OldType != NewType &&
2270       !OldType->isDependentType() &&
2271       !NewType->isDependentType() &&
2272       !Context.hasSameType(OldType, NewType)) {
2273     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2274     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2275       << Kind << NewType << OldType;
2276     if (Old->getLocation().isValid())
2277       notePreviousDefinition(Old, New->getLocation());
2278     New->setInvalidDecl();
2279     return true;
2280   }
2281   return false;
2282 }
2283 
2284 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2285 /// same name and scope as a previous declaration 'Old'.  Figure out
2286 /// how to resolve this situation, merging decls or emitting
2287 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2288 ///
2289 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2290                                 LookupResult &OldDecls) {
2291   // If the new decl is known invalid already, don't bother doing any
2292   // merging checks.
2293   if (New->isInvalidDecl()) return;
2294 
2295   // Allow multiple definitions for ObjC built-in typedefs.
2296   // FIXME: Verify the underlying types are equivalent!
2297   if (getLangOpts().ObjC) {
2298     const IdentifierInfo *TypeID = New->getIdentifier();
2299     switch (TypeID->getLength()) {
2300     default: break;
2301     case 2:
2302       {
2303         if (!TypeID->isStr("id"))
2304           break;
2305         QualType T = New->getUnderlyingType();
2306         if (!T->isPointerType())
2307           break;
2308         if (!T->isVoidPointerType()) {
2309           QualType PT = T->castAs<PointerType>()->getPointeeType();
2310           if (!PT->isStructureType())
2311             break;
2312         }
2313         Context.setObjCIdRedefinitionType(T);
2314         // Install the built-in type for 'id', ignoring the current definition.
2315         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2316         return;
2317       }
2318     case 5:
2319       if (!TypeID->isStr("Class"))
2320         break;
2321       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2322       // Install the built-in type for 'Class', ignoring the current definition.
2323       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2324       return;
2325     case 3:
2326       if (!TypeID->isStr("SEL"))
2327         break;
2328       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2329       // Install the built-in type for 'SEL', ignoring the current definition.
2330       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2331       return;
2332     }
2333     // Fall through - the typedef name was not a builtin type.
2334   }
2335 
2336   // Verify the old decl was also a type.
2337   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2338   if (!Old) {
2339     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2340       << New->getDeclName();
2341 
2342     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2343     if (OldD->getLocation().isValid())
2344       notePreviousDefinition(OldD, New->getLocation());
2345 
2346     return New->setInvalidDecl();
2347   }
2348 
2349   // If the old declaration is invalid, just give up here.
2350   if (Old->isInvalidDecl())
2351     return New->setInvalidDecl();
2352 
2353   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2354     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2355     auto *NewTag = New->getAnonDeclWithTypedefName();
2356     NamedDecl *Hidden = nullptr;
2357     if (OldTag && NewTag &&
2358         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2359         !hasVisibleDefinition(OldTag, &Hidden)) {
2360       // There is a definition of this tag, but it is not visible. Use it
2361       // instead of our tag.
2362       New->setTypeForDecl(OldTD->getTypeForDecl());
2363       if (OldTD->isModed())
2364         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2365                                     OldTD->getUnderlyingType());
2366       else
2367         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2368 
2369       // Make the old tag definition visible.
2370       makeMergedDefinitionVisible(Hidden);
2371 
2372       // If this was an unscoped enumeration, yank all of its enumerators
2373       // out of the scope.
2374       if (isa<EnumDecl>(NewTag)) {
2375         Scope *EnumScope = getNonFieldDeclScope(S);
2376         for (auto *D : NewTag->decls()) {
2377           auto *ED = cast<EnumConstantDecl>(D);
2378           assert(EnumScope->isDeclScope(ED));
2379           EnumScope->RemoveDecl(ED);
2380           IdResolver.RemoveDecl(ED);
2381           ED->getLexicalDeclContext()->removeDecl(ED);
2382         }
2383       }
2384     }
2385   }
2386 
2387   // If the typedef types are not identical, reject them in all languages and
2388   // with any extensions enabled.
2389   if (isIncompatibleTypedef(Old, New))
2390     return;
2391 
2392   // The types match.  Link up the redeclaration chain and merge attributes if
2393   // the old declaration was a typedef.
2394   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2395     New->setPreviousDecl(Typedef);
2396     mergeDeclAttributes(New, Old);
2397   }
2398 
2399   if (getLangOpts().MicrosoftExt)
2400     return;
2401 
2402   if (getLangOpts().CPlusPlus) {
2403     // C++ [dcl.typedef]p2:
2404     //   In a given non-class scope, a typedef specifier can be used to
2405     //   redefine the name of any type declared in that scope to refer
2406     //   to the type to which it already refers.
2407     if (!isa<CXXRecordDecl>(CurContext))
2408       return;
2409 
2410     // C++0x [dcl.typedef]p4:
2411     //   In a given class scope, a typedef specifier can be used to redefine
2412     //   any class-name declared in that scope that is not also a typedef-name
2413     //   to refer to the type to which it already refers.
2414     //
2415     // This wording came in via DR424, which was a correction to the
2416     // wording in DR56, which accidentally banned code like:
2417     //
2418     //   struct S {
2419     //     typedef struct A { } A;
2420     //   };
2421     //
2422     // in the C++03 standard. We implement the C++0x semantics, which
2423     // allow the above but disallow
2424     //
2425     //   struct S {
2426     //     typedef int I;
2427     //     typedef int I;
2428     //   };
2429     //
2430     // since that was the intent of DR56.
2431     if (!isa<TypedefNameDecl>(Old))
2432       return;
2433 
2434     Diag(New->getLocation(), diag::err_redefinition)
2435       << New->getDeclName();
2436     notePreviousDefinition(Old, New->getLocation());
2437     return New->setInvalidDecl();
2438   }
2439 
2440   // Modules always permit redefinition of typedefs, as does C11.
2441   if (getLangOpts().Modules || getLangOpts().C11)
2442     return;
2443 
2444   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2445   // is normally mapped to an error, but can be controlled with
2446   // -Wtypedef-redefinition.  If either the original or the redefinition is
2447   // in a system header, don't emit this for compatibility with GCC.
2448   if (getDiagnostics().getSuppressSystemWarnings() &&
2449       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2450       (Old->isImplicit() ||
2451        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2452        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2453     return;
2454 
2455   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2456     << New->getDeclName();
2457   notePreviousDefinition(Old, New->getLocation());
2458 }
2459 
2460 /// DeclhasAttr - returns true if decl Declaration already has the target
2461 /// attribute.
2462 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2463   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2464   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2465   for (const auto *i : D->attrs())
2466     if (i->getKind() == A->getKind()) {
2467       if (Ann) {
2468         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2469           return true;
2470         continue;
2471       }
2472       // FIXME: Don't hardcode this check
2473       if (OA && isa<OwnershipAttr>(i))
2474         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2475       return true;
2476     }
2477 
2478   return false;
2479 }
2480 
2481 static bool isAttributeTargetADefinition(Decl *D) {
2482   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2483     return VD->isThisDeclarationADefinition();
2484   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2485     return TD->isCompleteDefinition() || TD->isBeingDefined();
2486   return true;
2487 }
2488 
2489 /// Merge alignment attributes from \p Old to \p New, taking into account the
2490 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2491 ///
2492 /// \return \c true if any attributes were added to \p New.
2493 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2494   // Look for alignas attributes on Old, and pick out whichever attribute
2495   // specifies the strictest alignment requirement.
2496   AlignedAttr *OldAlignasAttr = nullptr;
2497   AlignedAttr *OldStrictestAlignAttr = nullptr;
2498   unsigned OldAlign = 0;
2499   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2500     // FIXME: We have no way of representing inherited dependent alignments
2501     // in a case like:
2502     //   template<int A, int B> struct alignas(A) X;
2503     //   template<int A, int B> struct alignas(B) X {};
2504     // For now, we just ignore any alignas attributes which are not on the
2505     // definition in such a case.
2506     if (I->isAlignmentDependent())
2507       return false;
2508 
2509     if (I->isAlignas())
2510       OldAlignasAttr = I;
2511 
2512     unsigned Align = I->getAlignment(S.Context);
2513     if (Align > OldAlign) {
2514       OldAlign = Align;
2515       OldStrictestAlignAttr = I;
2516     }
2517   }
2518 
2519   // Look for alignas attributes on New.
2520   AlignedAttr *NewAlignasAttr = nullptr;
2521   unsigned NewAlign = 0;
2522   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2523     if (I->isAlignmentDependent())
2524       return false;
2525 
2526     if (I->isAlignas())
2527       NewAlignasAttr = I;
2528 
2529     unsigned Align = I->getAlignment(S.Context);
2530     if (Align > NewAlign)
2531       NewAlign = Align;
2532   }
2533 
2534   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2535     // Both declarations have 'alignas' attributes. We require them to match.
2536     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2537     // fall short. (If two declarations both have alignas, they must both match
2538     // every definition, and so must match each other if there is a definition.)
2539 
2540     // If either declaration only contains 'alignas(0)' specifiers, then it
2541     // specifies the natural alignment for the type.
2542     if (OldAlign == 0 || NewAlign == 0) {
2543       QualType Ty;
2544       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2545         Ty = VD->getType();
2546       else
2547         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2548 
2549       if (OldAlign == 0)
2550         OldAlign = S.Context.getTypeAlign(Ty);
2551       if (NewAlign == 0)
2552         NewAlign = S.Context.getTypeAlign(Ty);
2553     }
2554 
2555     if (OldAlign != NewAlign) {
2556       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2557         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2558         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2559       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2560     }
2561   }
2562 
2563   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2564     // C++11 [dcl.align]p6:
2565     //   if any declaration of an entity has an alignment-specifier,
2566     //   every defining declaration of that entity shall specify an
2567     //   equivalent alignment.
2568     // C11 6.7.5/7:
2569     //   If the definition of an object does not have an alignment
2570     //   specifier, any other declaration of that object shall also
2571     //   have no alignment specifier.
2572     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2573       << OldAlignasAttr;
2574     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2575       << OldAlignasAttr;
2576   }
2577 
2578   bool AnyAdded = false;
2579 
2580   // Ensure we have an attribute representing the strictest alignment.
2581   if (OldAlign > NewAlign) {
2582     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2583     Clone->setInherited(true);
2584     New->addAttr(Clone);
2585     AnyAdded = true;
2586   }
2587 
2588   // Ensure we have an alignas attribute if the old declaration had one.
2589   if (OldAlignasAttr && !NewAlignasAttr &&
2590       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2591     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2592     Clone->setInherited(true);
2593     New->addAttr(Clone);
2594     AnyAdded = true;
2595   }
2596 
2597   return AnyAdded;
2598 }
2599 
2600 #define WANT_DECL_MERGE_LOGIC
2601 #include "clang/Sema/AttrParsedAttrImpl.inc"
2602 #undef WANT_DECL_MERGE_LOGIC
2603 
2604 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2605                                const InheritableAttr *Attr,
2606                                Sema::AvailabilityMergeKind AMK) {
2607   // Diagnose any mutual exclusions between the attribute that we want to add
2608   // and attributes that already exist on the declaration.
2609   if (!DiagnoseMutualExclusions(S, D, Attr))
2610     return false;
2611 
2612   // This function copies an attribute Attr from a previous declaration to the
2613   // new declaration D if the new declaration doesn't itself have that attribute
2614   // yet or if that attribute allows duplicates.
2615   // If you're adding a new attribute that requires logic different from
2616   // "use explicit attribute on decl if present, else use attribute from
2617   // previous decl", for example if the attribute needs to be consistent
2618   // between redeclarations, you need to call a custom merge function here.
2619   InheritableAttr *NewAttr = nullptr;
2620   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2621     NewAttr = S.mergeAvailabilityAttr(
2622         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2623         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2624         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2625         AA->getPriority());
2626   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2627     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2628   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2629     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2630   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2631     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2632   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2633     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2634   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2635     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2636   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2637     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2638                                 FA->getFirstArg());
2639   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2640     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2641   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2642     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2643   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2644     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2645                                        IA->getInheritanceModel());
2646   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2647     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2648                                       &S.Context.Idents.get(AA->getSpelling()));
2649   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2650            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2651             isa<CUDAGlobalAttr>(Attr))) {
2652     // CUDA target attributes are part of function signature for
2653     // overloading purposes and must not be merged.
2654     return false;
2655   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2656     NewAttr = S.mergeMinSizeAttr(D, *MA);
2657   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2658     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2659   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2660     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2661   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2662     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2663   else if (isa<AlignedAttr>(Attr))
2664     // AlignedAttrs are handled separately, because we need to handle all
2665     // such attributes on a declaration at the same time.
2666     NewAttr = nullptr;
2667   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2668            (AMK == Sema::AMK_Override ||
2669             AMK == Sema::AMK_ProtocolImplementation ||
2670             AMK == Sema::AMK_OptionalProtocolImplementation))
2671     NewAttr = nullptr;
2672   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2673     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2674   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2675     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2676   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2677     NewAttr = S.mergeImportNameAttr(D, *INA);
2678   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2679     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2680   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2681     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2682   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2683     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2684   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2685     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2686 
2687   if (NewAttr) {
2688     NewAttr->setInherited(true);
2689     D->addAttr(NewAttr);
2690     if (isa<MSInheritanceAttr>(NewAttr))
2691       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2692     return true;
2693   }
2694 
2695   return false;
2696 }
2697 
2698 static const NamedDecl *getDefinition(const Decl *D) {
2699   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2700     return TD->getDefinition();
2701   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2702     const VarDecl *Def = VD->getDefinition();
2703     if (Def)
2704       return Def;
2705     return VD->getActingDefinition();
2706   }
2707   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2708     const FunctionDecl *Def = nullptr;
2709     if (FD->isDefined(Def, true))
2710       return Def;
2711   }
2712   return nullptr;
2713 }
2714 
2715 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2716   for (const auto *Attribute : D->attrs())
2717     if (Attribute->getKind() == Kind)
2718       return true;
2719   return false;
2720 }
2721 
2722 /// checkNewAttributesAfterDef - If we already have a definition, check that
2723 /// there are no new attributes in this declaration.
2724 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2725   if (!New->hasAttrs())
2726     return;
2727 
2728   const NamedDecl *Def = getDefinition(Old);
2729   if (!Def || Def == New)
2730     return;
2731 
2732   AttrVec &NewAttributes = New->getAttrs();
2733   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2734     const Attr *NewAttribute = NewAttributes[I];
2735 
2736     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2737       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2738         Sema::SkipBodyInfo SkipBody;
2739         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2740 
2741         // If we're skipping this definition, drop the "alias" attribute.
2742         if (SkipBody.ShouldSkip) {
2743           NewAttributes.erase(NewAttributes.begin() + I);
2744           --E;
2745           continue;
2746         }
2747       } else {
2748         VarDecl *VD = cast<VarDecl>(New);
2749         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2750                                 VarDecl::TentativeDefinition
2751                             ? diag::err_alias_after_tentative
2752                             : diag::err_redefinition;
2753         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2754         if (Diag == diag::err_redefinition)
2755           S.notePreviousDefinition(Def, VD->getLocation());
2756         else
2757           S.Diag(Def->getLocation(), diag::note_previous_definition);
2758         VD->setInvalidDecl();
2759       }
2760       ++I;
2761       continue;
2762     }
2763 
2764     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2765       // Tentative definitions are only interesting for the alias check above.
2766       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2767         ++I;
2768         continue;
2769       }
2770     }
2771 
2772     if (hasAttribute(Def, NewAttribute->getKind())) {
2773       ++I;
2774       continue; // regular attr merging will take care of validating this.
2775     }
2776 
2777     if (isa<C11NoReturnAttr>(NewAttribute)) {
2778       // C's _Noreturn is allowed to be added to a function after it is defined.
2779       ++I;
2780       continue;
2781     } else if (isa<UuidAttr>(NewAttribute)) {
2782       // msvc will allow a subsequent definition to add an uuid to a class
2783       ++I;
2784       continue;
2785     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2786       if (AA->isAlignas()) {
2787         // C++11 [dcl.align]p6:
2788         //   if any declaration of an entity has an alignment-specifier,
2789         //   every defining declaration of that entity shall specify an
2790         //   equivalent alignment.
2791         // C11 6.7.5/7:
2792         //   If the definition of an object does not have an alignment
2793         //   specifier, any other declaration of that object shall also
2794         //   have no alignment specifier.
2795         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2796           << AA;
2797         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2798           << AA;
2799         NewAttributes.erase(NewAttributes.begin() + I);
2800         --E;
2801         continue;
2802       }
2803     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2804       // If there is a C definition followed by a redeclaration with this
2805       // attribute then there are two different definitions. In C++, prefer the
2806       // standard diagnostics.
2807       if (!S.getLangOpts().CPlusPlus) {
2808         S.Diag(NewAttribute->getLocation(),
2809                diag::err_loader_uninitialized_redeclaration);
2810         S.Diag(Def->getLocation(), diag::note_previous_definition);
2811         NewAttributes.erase(NewAttributes.begin() + I);
2812         --E;
2813         continue;
2814       }
2815     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2816                cast<VarDecl>(New)->isInline() &&
2817                !cast<VarDecl>(New)->isInlineSpecified()) {
2818       // Don't warn about applying selectany to implicitly inline variables.
2819       // Older compilers and language modes would require the use of selectany
2820       // to make such variables inline, and it would have no effect if we
2821       // honored it.
2822       ++I;
2823       continue;
2824     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2825       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2826       // declarations after defintions.
2827       ++I;
2828       continue;
2829     }
2830 
2831     S.Diag(NewAttribute->getLocation(),
2832            diag::warn_attribute_precede_definition);
2833     S.Diag(Def->getLocation(), diag::note_previous_definition);
2834     NewAttributes.erase(NewAttributes.begin() + I);
2835     --E;
2836   }
2837 }
2838 
2839 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2840                                      const ConstInitAttr *CIAttr,
2841                                      bool AttrBeforeInit) {
2842   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2843 
2844   // Figure out a good way to write this specifier on the old declaration.
2845   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2846   // enough of the attribute list spelling information to extract that without
2847   // heroics.
2848   std::string SuitableSpelling;
2849   if (S.getLangOpts().CPlusPlus20)
2850     SuitableSpelling = std::string(
2851         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2852   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2853     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2854         InsertLoc, {tok::l_square, tok::l_square,
2855                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2856                     S.PP.getIdentifierInfo("require_constant_initialization"),
2857                     tok::r_square, tok::r_square}));
2858   if (SuitableSpelling.empty())
2859     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2860         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2861                     S.PP.getIdentifierInfo("require_constant_initialization"),
2862                     tok::r_paren, tok::r_paren}));
2863   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2864     SuitableSpelling = "constinit";
2865   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2866     SuitableSpelling = "[[clang::require_constant_initialization]]";
2867   if (SuitableSpelling.empty())
2868     SuitableSpelling = "__attribute__((require_constant_initialization))";
2869   SuitableSpelling += " ";
2870 
2871   if (AttrBeforeInit) {
2872     // extern constinit int a;
2873     // int a = 0; // error (missing 'constinit'), accepted as extension
2874     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2875     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2876         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2877     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2878   } else {
2879     // int a = 0;
2880     // constinit extern int a; // error (missing 'constinit')
2881     S.Diag(CIAttr->getLocation(),
2882            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2883                                  : diag::warn_require_const_init_added_too_late)
2884         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2885     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2886         << CIAttr->isConstinit()
2887         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2888   }
2889 }
2890 
2891 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2892 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2893                                AvailabilityMergeKind AMK) {
2894   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2895     UsedAttr *NewAttr = OldAttr->clone(Context);
2896     NewAttr->setInherited(true);
2897     New->addAttr(NewAttr);
2898   }
2899   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2900     RetainAttr *NewAttr = OldAttr->clone(Context);
2901     NewAttr->setInherited(true);
2902     New->addAttr(NewAttr);
2903   }
2904 
2905   if (!Old->hasAttrs() && !New->hasAttrs())
2906     return;
2907 
2908   // [dcl.constinit]p1:
2909   //   If the [constinit] specifier is applied to any declaration of a
2910   //   variable, it shall be applied to the initializing declaration.
2911   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2912   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2913   if (bool(OldConstInit) != bool(NewConstInit)) {
2914     const auto *OldVD = cast<VarDecl>(Old);
2915     auto *NewVD = cast<VarDecl>(New);
2916 
2917     // Find the initializing declaration. Note that we might not have linked
2918     // the new declaration into the redeclaration chain yet.
2919     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2920     if (!InitDecl &&
2921         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2922       InitDecl = NewVD;
2923 
2924     if (InitDecl == NewVD) {
2925       // This is the initializing declaration. If it would inherit 'constinit',
2926       // that's ill-formed. (Note that we do not apply this to the attribute
2927       // form).
2928       if (OldConstInit && OldConstInit->isConstinit())
2929         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2930                                  /*AttrBeforeInit=*/true);
2931     } else if (NewConstInit) {
2932       // This is the first time we've been told that this declaration should
2933       // have a constant initializer. If we already saw the initializing
2934       // declaration, this is too late.
2935       if (InitDecl && InitDecl != NewVD) {
2936         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2937                                  /*AttrBeforeInit=*/false);
2938         NewVD->dropAttr<ConstInitAttr>();
2939       }
2940     }
2941   }
2942 
2943   // Attributes declared post-definition are currently ignored.
2944   checkNewAttributesAfterDef(*this, New, Old);
2945 
2946   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2947     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2948       if (!OldA->isEquivalent(NewA)) {
2949         // This redeclaration changes __asm__ label.
2950         Diag(New->getLocation(), diag::err_different_asm_label);
2951         Diag(OldA->getLocation(), diag::note_previous_declaration);
2952       }
2953     } else if (Old->isUsed()) {
2954       // This redeclaration adds an __asm__ label to a declaration that has
2955       // already been ODR-used.
2956       Diag(New->getLocation(), diag::err_late_asm_label_name)
2957         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2958     }
2959   }
2960 
2961   // Re-declaration cannot add abi_tag's.
2962   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2963     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2964       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2965         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
2966           Diag(NewAbiTagAttr->getLocation(),
2967                diag::err_new_abi_tag_on_redeclaration)
2968               << NewTag;
2969           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2970         }
2971       }
2972     } else {
2973       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2974       Diag(Old->getLocation(), diag::note_previous_declaration);
2975     }
2976   }
2977 
2978   // This redeclaration adds a section attribute.
2979   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2980     if (auto *VD = dyn_cast<VarDecl>(New)) {
2981       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2982         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2983         Diag(Old->getLocation(), diag::note_previous_declaration);
2984       }
2985     }
2986   }
2987 
2988   // Redeclaration adds code-seg attribute.
2989   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2990   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2991       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2992     Diag(New->getLocation(), diag::warn_mismatched_section)
2993          << 0 /*codeseg*/;
2994     Diag(Old->getLocation(), diag::note_previous_declaration);
2995   }
2996 
2997   if (!Old->hasAttrs())
2998     return;
2999 
3000   bool foundAny = New->hasAttrs();
3001 
3002   // Ensure that any moving of objects within the allocated map is done before
3003   // we process them.
3004   if (!foundAny) New->setAttrs(AttrVec());
3005 
3006   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3007     // Ignore deprecated/unavailable/availability attributes if requested.
3008     AvailabilityMergeKind LocalAMK = AMK_None;
3009     if (isa<DeprecatedAttr>(I) ||
3010         isa<UnavailableAttr>(I) ||
3011         isa<AvailabilityAttr>(I)) {
3012       switch (AMK) {
3013       case AMK_None:
3014         continue;
3015 
3016       case AMK_Redeclaration:
3017       case AMK_Override:
3018       case AMK_ProtocolImplementation:
3019       case AMK_OptionalProtocolImplementation:
3020         LocalAMK = AMK;
3021         break;
3022       }
3023     }
3024 
3025     // Already handled.
3026     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3027       continue;
3028 
3029     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3030       foundAny = true;
3031   }
3032 
3033   if (mergeAlignedAttrs(*this, New, Old))
3034     foundAny = true;
3035 
3036   if (!foundAny) New->dropAttrs();
3037 }
3038 
3039 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3040 /// to the new one.
3041 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3042                                      const ParmVarDecl *oldDecl,
3043                                      Sema &S) {
3044   // C++11 [dcl.attr.depend]p2:
3045   //   The first declaration of a function shall specify the
3046   //   carries_dependency attribute for its declarator-id if any declaration
3047   //   of the function specifies the carries_dependency attribute.
3048   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3049   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3050     S.Diag(CDA->getLocation(),
3051            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3052     // Find the first declaration of the parameter.
3053     // FIXME: Should we build redeclaration chains for function parameters?
3054     const FunctionDecl *FirstFD =
3055       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3056     const ParmVarDecl *FirstVD =
3057       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3058     S.Diag(FirstVD->getLocation(),
3059            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3060   }
3061 
3062   if (!oldDecl->hasAttrs())
3063     return;
3064 
3065   bool foundAny = newDecl->hasAttrs();
3066 
3067   // Ensure that any moving of objects within the allocated map is
3068   // done before we process them.
3069   if (!foundAny) newDecl->setAttrs(AttrVec());
3070 
3071   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3072     if (!DeclHasAttr(newDecl, I)) {
3073       InheritableAttr *newAttr =
3074         cast<InheritableParamAttr>(I->clone(S.Context));
3075       newAttr->setInherited(true);
3076       newDecl->addAttr(newAttr);
3077       foundAny = true;
3078     }
3079   }
3080 
3081   if (!foundAny) newDecl->dropAttrs();
3082 }
3083 
3084 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3085                                 const ParmVarDecl *OldParam,
3086                                 Sema &S) {
3087   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3088     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3089       if (*Oldnullability != *Newnullability) {
3090         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3091           << DiagNullabilityKind(
3092                *Newnullability,
3093                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3094                 != 0))
3095           << DiagNullabilityKind(
3096                *Oldnullability,
3097                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3098                 != 0));
3099         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3100       }
3101     } else {
3102       QualType NewT = NewParam->getType();
3103       NewT = S.Context.getAttributedType(
3104                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3105                          NewT, NewT);
3106       NewParam->setType(NewT);
3107     }
3108   }
3109 }
3110 
3111 namespace {
3112 
3113 /// Used in MergeFunctionDecl to keep track of function parameters in
3114 /// C.
3115 struct GNUCompatibleParamWarning {
3116   ParmVarDecl *OldParm;
3117   ParmVarDecl *NewParm;
3118   QualType PromotedType;
3119 };
3120 
3121 } // end anonymous namespace
3122 
3123 // Determine whether the previous declaration was a definition, implicit
3124 // declaration, or a declaration.
3125 template <typename T>
3126 static std::pair<diag::kind, SourceLocation>
3127 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3128   diag::kind PrevDiag;
3129   SourceLocation OldLocation = Old->getLocation();
3130   if (Old->isThisDeclarationADefinition())
3131     PrevDiag = diag::note_previous_definition;
3132   else if (Old->isImplicit()) {
3133     PrevDiag = diag::note_previous_implicit_declaration;
3134     if (OldLocation.isInvalid())
3135       OldLocation = New->getLocation();
3136   } else
3137     PrevDiag = diag::note_previous_declaration;
3138   return std::make_pair(PrevDiag, OldLocation);
3139 }
3140 
3141 /// canRedefineFunction - checks if a function can be redefined. Currently,
3142 /// only extern inline functions can be redefined, and even then only in
3143 /// GNU89 mode.
3144 static bool canRedefineFunction(const FunctionDecl *FD,
3145                                 const LangOptions& LangOpts) {
3146   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3147           !LangOpts.CPlusPlus &&
3148           FD->isInlineSpecified() &&
3149           FD->getStorageClass() == SC_Extern);
3150 }
3151 
3152 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3153   const AttributedType *AT = T->getAs<AttributedType>();
3154   while (AT && !AT->isCallingConv())
3155     AT = AT->getModifiedType()->getAs<AttributedType>();
3156   return AT;
3157 }
3158 
3159 template <typename T>
3160 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3161   const DeclContext *DC = Old->getDeclContext();
3162   if (DC->isRecord())
3163     return false;
3164 
3165   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3166   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3167     return true;
3168   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3169     return true;
3170   return false;
3171 }
3172 
3173 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3174 static bool isExternC(VarTemplateDecl *) { return false; }
3175 static bool isExternC(FunctionTemplateDecl *) { return false; }
3176 
3177 /// Check whether a redeclaration of an entity introduced by a
3178 /// using-declaration is valid, given that we know it's not an overload
3179 /// (nor a hidden tag declaration).
3180 template<typename ExpectedDecl>
3181 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3182                                    ExpectedDecl *New) {
3183   // C++11 [basic.scope.declarative]p4:
3184   //   Given a set of declarations in a single declarative region, each of
3185   //   which specifies the same unqualified name,
3186   //   -- they shall all refer to the same entity, or all refer to functions
3187   //      and function templates; or
3188   //   -- exactly one declaration shall declare a class name or enumeration
3189   //      name that is not a typedef name and the other declarations shall all
3190   //      refer to the same variable or enumerator, or all refer to functions
3191   //      and function templates; in this case the class name or enumeration
3192   //      name is hidden (3.3.10).
3193 
3194   // C++11 [namespace.udecl]p14:
3195   //   If a function declaration in namespace scope or block scope has the
3196   //   same name and the same parameter-type-list as a function introduced
3197   //   by a using-declaration, and the declarations do not declare the same
3198   //   function, the program is ill-formed.
3199 
3200   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3201   if (Old &&
3202       !Old->getDeclContext()->getRedeclContext()->Equals(
3203           New->getDeclContext()->getRedeclContext()) &&
3204       !(isExternC(Old) && isExternC(New)))
3205     Old = nullptr;
3206 
3207   if (!Old) {
3208     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3209     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3210     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3211     return true;
3212   }
3213   return false;
3214 }
3215 
3216 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3217                                             const FunctionDecl *B) {
3218   assert(A->getNumParams() == B->getNumParams());
3219 
3220   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3221     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3222     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3223     if (AttrA == AttrB)
3224       return true;
3225     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3226            AttrA->isDynamic() == AttrB->isDynamic();
3227   };
3228 
3229   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3230 }
3231 
3232 /// If necessary, adjust the semantic declaration context for a qualified
3233 /// declaration to name the correct inline namespace within the qualifier.
3234 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3235                                                DeclaratorDecl *OldD) {
3236   // The only case where we need to update the DeclContext is when
3237   // redeclaration lookup for a qualified name finds a declaration
3238   // in an inline namespace within the context named by the qualifier:
3239   //
3240   //   inline namespace N { int f(); }
3241   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3242   //
3243   // For unqualified declarations, the semantic context *can* change
3244   // along the redeclaration chain (for local extern declarations,
3245   // extern "C" declarations, and friend declarations in particular).
3246   if (!NewD->getQualifier())
3247     return;
3248 
3249   // NewD is probably already in the right context.
3250   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3251   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3252   if (NamedDC->Equals(SemaDC))
3253     return;
3254 
3255   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3256           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3257          "unexpected context for redeclaration");
3258 
3259   auto *LexDC = NewD->getLexicalDeclContext();
3260   auto FixSemaDC = [=](NamedDecl *D) {
3261     if (!D)
3262       return;
3263     D->setDeclContext(SemaDC);
3264     D->setLexicalDeclContext(LexDC);
3265   };
3266 
3267   FixSemaDC(NewD);
3268   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3269     FixSemaDC(FD->getDescribedFunctionTemplate());
3270   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3271     FixSemaDC(VD->getDescribedVarTemplate());
3272 }
3273 
3274 /// MergeFunctionDecl - We just parsed a function 'New' from
3275 /// declarator D which has the same name and scope as a previous
3276 /// declaration 'Old'.  Figure out how to resolve this situation,
3277 /// merging decls or emitting diagnostics as appropriate.
3278 ///
3279 /// In C++, New and Old must be declarations that are not
3280 /// overloaded. Use IsOverload to determine whether New and Old are
3281 /// overloaded, and to select the Old declaration that New should be
3282 /// merged with.
3283 ///
3284 /// Returns true if there was an error, false otherwise.
3285 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3286                              Scope *S, bool MergeTypeWithOld) {
3287   // Verify the old decl was also a function.
3288   FunctionDecl *Old = OldD->getAsFunction();
3289   if (!Old) {
3290     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3291       if (New->getFriendObjectKind()) {
3292         Diag(New->getLocation(), diag::err_using_decl_friend);
3293         Diag(Shadow->getTargetDecl()->getLocation(),
3294              diag::note_using_decl_target);
3295         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3296             << 0;
3297         return true;
3298       }
3299 
3300       // Check whether the two declarations might declare the same function or
3301       // function template.
3302       if (FunctionTemplateDecl *NewTemplate =
3303               New->getDescribedFunctionTemplate()) {
3304         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3305                                                          NewTemplate))
3306           return true;
3307         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3308                          ->getAsFunction();
3309       } else {
3310         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3311           return true;
3312         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3313       }
3314     } else {
3315       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3316         << New->getDeclName();
3317       notePreviousDefinition(OldD, New->getLocation());
3318       return true;
3319     }
3320   }
3321 
3322   // If the old declaration was found in an inline namespace and the new
3323   // declaration was qualified, update the DeclContext to match.
3324   adjustDeclContextForDeclaratorDecl(New, Old);
3325 
3326   // If the old declaration is invalid, just give up here.
3327   if (Old->isInvalidDecl())
3328     return true;
3329 
3330   // Disallow redeclaration of some builtins.
3331   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3332     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3333     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3334         << Old << Old->getType();
3335     return true;
3336   }
3337 
3338   diag::kind PrevDiag;
3339   SourceLocation OldLocation;
3340   std::tie(PrevDiag, OldLocation) =
3341       getNoteDiagForInvalidRedeclaration(Old, New);
3342 
3343   // Don't complain about this if we're in GNU89 mode and the old function
3344   // is an extern inline function.
3345   // Don't complain about specializations. They are not supposed to have
3346   // storage classes.
3347   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3348       New->getStorageClass() == SC_Static &&
3349       Old->hasExternalFormalLinkage() &&
3350       !New->getTemplateSpecializationInfo() &&
3351       !canRedefineFunction(Old, getLangOpts())) {
3352     if (getLangOpts().MicrosoftExt) {
3353       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3354       Diag(OldLocation, PrevDiag);
3355     } else {
3356       Diag(New->getLocation(), diag::err_static_non_static) << New;
3357       Diag(OldLocation, PrevDiag);
3358       return true;
3359     }
3360   }
3361 
3362   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3363     if (!Old->hasAttr<InternalLinkageAttr>()) {
3364       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3365           << ILA;
3366       Diag(Old->getLocation(), diag::note_previous_declaration);
3367       New->dropAttr<InternalLinkageAttr>();
3368     }
3369 
3370   if (auto *EA = New->getAttr<ErrorAttr>()) {
3371     if (!Old->hasAttr<ErrorAttr>()) {
3372       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3373       Diag(Old->getLocation(), diag::note_previous_declaration);
3374       New->dropAttr<ErrorAttr>();
3375     }
3376   }
3377 
3378   if (CheckRedeclarationModuleOwnership(New, Old))
3379     return true;
3380 
3381   if (!getLangOpts().CPlusPlus) {
3382     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3383     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3384       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3385         << New << OldOvl;
3386 
3387       // Try our best to find a decl that actually has the overloadable
3388       // attribute for the note. In most cases (e.g. programs with only one
3389       // broken declaration/definition), this won't matter.
3390       //
3391       // FIXME: We could do this if we juggled some extra state in
3392       // OverloadableAttr, rather than just removing it.
3393       const Decl *DiagOld = Old;
3394       if (OldOvl) {
3395         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3396           const auto *A = D->getAttr<OverloadableAttr>();
3397           return A && !A->isImplicit();
3398         });
3399         // If we've implicitly added *all* of the overloadable attrs to this
3400         // chain, emitting a "previous redecl" note is pointless.
3401         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3402       }
3403 
3404       if (DiagOld)
3405         Diag(DiagOld->getLocation(),
3406              diag::note_attribute_overloadable_prev_overload)
3407           << OldOvl;
3408 
3409       if (OldOvl)
3410         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3411       else
3412         New->dropAttr<OverloadableAttr>();
3413     }
3414   }
3415 
3416   // If a function is first declared with a calling convention, but is later
3417   // declared or defined without one, all following decls assume the calling
3418   // convention of the first.
3419   //
3420   // It's OK if a function is first declared without a calling convention,
3421   // but is later declared or defined with the default calling convention.
3422   //
3423   // To test if either decl has an explicit calling convention, we look for
3424   // AttributedType sugar nodes on the type as written.  If they are missing or
3425   // were canonicalized away, we assume the calling convention was implicit.
3426   //
3427   // Note also that we DO NOT return at this point, because we still have
3428   // other tests to run.
3429   QualType OldQType = Context.getCanonicalType(Old->getType());
3430   QualType NewQType = Context.getCanonicalType(New->getType());
3431   const FunctionType *OldType = cast<FunctionType>(OldQType);
3432   const FunctionType *NewType = cast<FunctionType>(NewQType);
3433   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3434   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3435   bool RequiresAdjustment = false;
3436 
3437   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3438     FunctionDecl *First = Old->getFirstDecl();
3439     const FunctionType *FT =
3440         First->getType().getCanonicalType()->castAs<FunctionType>();
3441     FunctionType::ExtInfo FI = FT->getExtInfo();
3442     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3443     if (!NewCCExplicit) {
3444       // Inherit the CC from the previous declaration if it was specified
3445       // there but not here.
3446       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3447       RequiresAdjustment = true;
3448     } else if (Old->getBuiltinID()) {
3449       // Builtin attribute isn't propagated to the new one yet at this point,
3450       // so we check if the old one is a builtin.
3451 
3452       // Calling Conventions on a Builtin aren't really useful and setting a
3453       // default calling convention and cdecl'ing some builtin redeclarations is
3454       // common, so warn and ignore the calling convention on the redeclaration.
3455       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3456           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3457           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3458       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3459       RequiresAdjustment = true;
3460     } else {
3461       // Calling conventions aren't compatible, so complain.
3462       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3463       Diag(New->getLocation(), diag::err_cconv_change)
3464         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3465         << !FirstCCExplicit
3466         << (!FirstCCExplicit ? "" :
3467             FunctionType::getNameForCallConv(FI.getCC()));
3468 
3469       // Put the note on the first decl, since it is the one that matters.
3470       Diag(First->getLocation(), diag::note_previous_declaration);
3471       return true;
3472     }
3473   }
3474 
3475   // FIXME: diagnose the other way around?
3476   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3477     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3478     RequiresAdjustment = true;
3479   }
3480 
3481   // Merge regparm attribute.
3482   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3483       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3484     if (NewTypeInfo.getHasRegParm()) {
3485       Diag(New->getLocation(), diag::err_regparm_mismatch)
3486         << NewType->getRegParmType()
3487         << OldType->getRegParmType();
3488       Diag(OldLocation, diag::note_previous_declaration);
3489       return true;
3490     }
3491 
3492     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3493     RequiresAdjustment = true;
3494   }
3495 
3496   // Merge ns_returns_retained attribute.
3497   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3498     if (NewTypeInfo.getProducesResult()) {
3499       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3500           << "'ns_returns_retained'";
3501       Diag(OldLocation, diag::note_previous_declaration);
3502       return true;
3503     }
3504 
3505     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3506     RequiresAdjustment = true;
3507   }
3508 
3509   if (OldTypeInfo.getNoCallerSavedRegs() !=
3510       NewTypeInfo.getNoCallerSavedRegs()) {
3511     if (NewTypeInfo.getNoCallerSavedRegs()) {
3512       AnyX86NoCallerSavedRegistersAttr *Attr =
3513         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3514       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3515       Diag(OldLocation, diag::note_previous_declaration);
3516       return true;
3517     }
3518 
3519     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3520     RequiresAdjustment = true;
3521   }
3522 
3523   if (RequiresAdjustment) {
3524     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3525     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3526     New->setType(QualType(AdjustedType, 0));
3527     NewQType = Context.getCanonicalType(New->getType());
3528   }
3529 
3530   // If this redeclaration makes the function inline, we may need to add it to
3531   // UndefinedButUsed.
3532   if (!Old->isInlined() && New->isInlined() &&
3533       !New->hasAttr<GNUInlineAttr>() &&
3534       !getLangOpts().GNUInline &&
3535       Old->isUsed(false) &&
3536       !Old->isDefined() && !New->isThisDeclarationADefinition())
3537     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3538                                            SourceLocation()));
3539 
3540   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3541   // about it.
3542   if (New->hasAttr<GNUInlineAttr>() &&
3543       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3544     UndefinedButUsed.erase(Old->getCanonicalDecl());
3545   }
3546 
3547   // If pass_object_size params don't match up perfectly, this isn't a valid
3548   // redeclaration.
3549   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3550       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3551     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3552         << New->getDeclName();
3553     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3554     return true;
3555   }
3556 
3557   if (getLangOpts().CPlusPlus) {
3558     // C++1z [over.load]p2
3559     //   Certain function declarations cannot be overloaded:
3560     //     -- Function declarations that differ only in the return type,
3561     //        the exception specification, or both cannot be overloaded.
3562 
3563     // Check the exception specifications match. This may recompute the type of
3564     // both Old and New if it resolved exception specifications, so grab the
3565     // types again after this. Because this updates the type, we do this before
3566     // any of the other checks below, which may update the "de facto" NewQType
3567     // but do not necessarily update the type of New.
3568     if (CheckEquivalentExceptionSpec(Old, New))
3569       return true;
3570     OldQType = Context.getCanonicalType(Old->getType());
3571     NewQType = Context.getCanonicalType(New->getType());
3572 
3573     // Go back to the type source info to compare the declared return types,
3574     // per C++1y [dcl.type.auto]p13:
3575     //   Redeclarations or specializations of a function or function template
3576     //   with a declared return type that uses a placeholder type shall also
3577     //   use that placeholder, not a deduced type.
3578     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3579     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3580     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3581         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3582                                        OldDeclaredReturnType)) {
3583       QualType ResQT;
3584       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3585           OldDeclaredReturnType->isObjCObjectPointerType())
3586         // FIXME: This does the wrong thing for a deduced return type.
3587         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3588       if (ResQT.isNull()) {
3589         if (New->isCXXClassMember() && New->isOutOfLine())
3590           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3591               << New << New->getReturnTypeSourceRange();
3592         else
3593           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3594               << New->getReturnTypeSourceRange();
3595         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3596                                     << Old->getReturnTypeSourceRange();
3597         return true;
3598       }
3599       else
3600         NewQType = ResQT;
3601     }
3602 
3603     QualType OldReturnType = OldType->getReturnType();
3604     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3605     if (OldReturnType != NewReturnType) {
3606       // If this function has a deduced return type and has already been
3607       // defined, copy the deduced value from the old declaration.
3608       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3609       if (OldAT && OldAT->isDeduced()) {
3610         New->setType(
3611             SubstAutoType(New->getType(),
3612                           OldAT->isDependentType() ? Context.DependentTy
3613                                                    : OldAT->getDeducedType()));
3614         NewQType = Context.getCanonicalType(
3615             SubstAutoType(NewQType,
3616                           OldAT->isDependentType() ? Context.DependentTy
3617                                                    : OldAT->getDeducedType()));
3618       }
3619     }
3620 
3621     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3622     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3623     if (OldMethod && NewMethod) {
3624       // Preserve triviality.
3625       NewMethod->setTrivial(OldMethod->isTrivial());
3626 
3627       // MSVC allows explicit template specialization at class scope:
3628       // 2 CXXMethodDecls referring to the same function will be injected.
3629       // We don't want a redeclaration error.
3630       bool IsClassScopeExplicitSpecialization =
3631                               OldMethod->isFunctionTemplateSpecialization() &&
3632                               NewMethod->isFunctionTemplateSpecialization();
3633       bool isFriend = NewMethod->getFriendObjectKind();
3634 
3635       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3636           !IsClassScopeExplicitSpecialization) {
3637         //    -- Member function declarations with the same name and the
3638         //       same parameter types cannot be overloaded if any of them
3639         //       is a static member function declaration.
3640         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3641           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3642           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3643           return true;
3644         }
3645 
3646         // C++ [class.mem]p1:
3647         //   [...] A member shall not be declared twice in the
3648         //   member-specification, except that a nested class or member
3649         //   class template can be declared and then later defined.
3650         if (!inTemplateInstantiation()) {
3651           unsigned NewDiag;
3652           if (isa<CXXConstructorDecl>(OldMethod))
3653             NewDiag = diag::err_constructor_redeclared;
3654           else if (isa<CXXDestructorDecl>(NewMethod))
3655             NewDiag = diag::err_destructor_redeclared;
3656           else if (isa<CXXConversionDecl>(NewMethod))
3657             NewDiag = diag::err_conv_function_redeclared;
3658           else
3659             NewDiag = diag::err_member_redeclared;
3660 
3661           Diag(New->getLocation(), NewDiag);
3662         } else {
3663           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3664             << New << New->getType();
3665         }
3666         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3667         return true;
3668 
3669       // Complain if this is an explicit declaration of a special
3670       // member that was initially declared implicitly.
3671       //
3672       // As an exception, it's okay to befriend such methods in order
3673       // to permit the implicit constructor/destructor/operator calls.
3674       } else if (OldMethod->isImplicit()) {
3675         if (isFriend) {
3676           NewMethod->setImplicit();
3677         } else {
3678           Diag(NewMethod->getLocation(),
3679                diag::err_definition_of_implicitly_declared_member)
3680             << New << getSpecialMember(OldMethod);
3681           return true;
3682         }
3683       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3684         Diag(NewMethod->getLocation(),
3685              diag::err_definition_of_explicitly_defaulted_member)
3686           << getSpecialMember(OldMethod);
3687         return true;
3688       }
3689     }
3690 
3691     // C++11 [dcl.attr.noreturn]p1:
3692     //   The first declaration of a function shall specify the noreturn
3693     //   attribute if any declaration of that function specifies the noreturn
3694     //   attribute.
3695     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3696       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3697         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3698             << NRA;
3699         Diag(Old->getLocation(), diag::note_previous_declaration);
3700       }
3701 
3702     // C++11 [dcl.attr.depend]p2:
3703     //   The first declaration of a function shall specify the
3704     //   carries_dependency attribute for its declarator-id if any declaration
3705     //   of the function specifies the carries_dependency attribute.
3706     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3707     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3708       Diag(CDA->getLocation(),
3709            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3710       Diag(Old->getFirstDecl()->getLocation(),
3711            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3712     }
3713 
3714     // (C++98 8.3.5p3):
3715     //   All declarations for a function shall agree exactly in both the
3716     //   return type and the parameter-type-list.
3717     // We also want to respect all the extended bits except noreturn.
3718 
3719     // noreturn should now match unless the old type info didn't have it.
3720     QualType OldQTypeForComparison = OldQType;
3721     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3722       auto *OldType = OldQType->castAs<FunctionProtoType>();
3723       const FunctionType *OldTypeForComparison
3724         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3725       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3726       assert(OldQTypeForComparison.isCanonical());
3727     }
3728 
3729     if (haveIncompatibleLanguageLinkages(Old, New)) {
3730       // As a special case, retain the language linkage from previous
3731       // declarations of a friend function as an extension.
3732       //
3733       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3734       // and is useful because there's otherwise no way to specify language
3735       // linkage within class scope.
3736       //
3737       // Check cautiously as the friend object kind isn't yet complete.
3738       if (New->getFriendObjectKind() != Decl::FOK_None) {
3739         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3740         Diag(OldLocation, PrevDiag);
3741       } else {
3742         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3743         Diag(OldLocation, PrevDiag);
3744         return true;
3745       }
3746     }
3747 
3748     // If the function types are compatible, merge the declarations. Ignore the
3749     // exception specifier because it was already checked above in
3750     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3751     // about incompatible types under -fms-compatibility.
3752     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3753                                                          NewQType))
3754       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3755 
3756     // If the types are imprecise (due to dependent constructs in friends or
3757     // local extern declarations), it's OK if they differ. We'll check again
3758     // during instantiation.
3759     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3760       return false;
3761 
3762     // Fall through for conflicting redeclarations and redefinitions.
3763   }
3764 
3765   // C: Function types need to be compatible, not identical. This handles
3766   // duplicate function decls like "void f(int); void f(enum X);" properly.
3767   if (!getLangOpts().CPlusPlus &&
3768       Context.typesAreCompatible(OldQType, NewQType)) {
3769     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3770     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3771     const FunctionProtoType *OldProto = nullptr;
3772     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3773         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3774       // The old declaration provided a function prototype, but the
3775       // new declaration does not. Merge in the prototype.
3776       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3777       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3778       NewQType =
3779           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3780                                   OldProto->getExtProtoInfo());
3781       New->setType(NewQType);
3782       New->setHasInheritedPrototype();
3783 
3784       // Synthesize parameters with the same types.
3785       SmallVector<ParmVarDecl*, 16> Params;
3786       for (const auto &ParamType : OldProto->param_types()) {
3787         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3788                                                  SourceLocation(), nullptr,
3789                                                  ParamType, /*TInfo=*/nullptr,
3790                                                  SC_None, nullptr);
3791         Param->setScopeInfo(0, Params.size());
3792         Param->setImplicit();
3793         Params.push_back(Param);
3794       }
3795 
3796       New->setParams(Params);
3797     }
3798 
3799     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3800   }
3801 
3802   // Check if the function types are compatible when pointer size address
3803   // spaces are ignored.
3804   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3805     return false;
3806 
3807   // GNU C permits a K&R definition to follow a prototype declaration
3808   // if the declared types of the parameters in the K&R definition
3809   // match the types in the prototype declaration, even when the
3810   // promoted types of the parameters from the K&R definition differ
3811   // from the types in the prototype. GCC then keeps the types from
3812   // the prototype.
3813   //
3814   // If a variadic prototype is followed by a non-variadic K&R definition,
3815   // the K&R definition becomes variadic.  This is sort of an edge case, but
3816   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3817   // C99 6.9.1p8.
3818   if (!getLangOpts().CPlusPlus &&
3819       Old->hasPrototype() && !New->hasPrototype() &&
3820       New->getType()->getAs<FunctionProtoType>() &&
3821       Old->getNumParams() == New->getNumParams()) {
3822     SmallVector<QualType, 16> ArgTypes;
3823     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3824     const FunctionProtoType *OldProto
3825       = Old->getType()->getAs<FunctionProtoType>();
3826     const FunctionProtoType *NewProto
3827       = New->getType()->getAs<FunctionProtoType>();
3828 
3829     // Determine whether this is the GNU C extension.
3830     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3831                                                NewProto->getReturnType());
3832     bool LooseCompatible = !MergedReturn.isNull();
3833     for (unsigned Idx = 0, End = Old->getNumParams();
3834          LooseCompatible && Idx != End; ++Idx) {
3835       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3836       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3837       if (Context.typesAreCompatible(OldParm->getType(),
3838                                      NewProto->getParamType(Idx))) {
3839         ArgTypes.push_back(NewParm->getType());
3840       } else if (Context.typesAreCompatible(OldParm->getType(),
3841                                             NewParm->getType(),
3842                                             /*CompareUnqualified=*/true)) {
3843         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3844                                            NewProto->getParamType(Idx) };
3845         Warnings.push_back(Warn);
3846         ArgTypes.push_back(NewParm->getType());
3847       } else
3848         LooseCompatible = false;
3849     }
3850 
3851     if (LooseCompatible) {
3852       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3853         Diag(Warnings[Warn].NewParm->getLocation(),
3854              diag::ext_param_promoted_not_compatible_with_prototype)
3855           << Warnings[Warn].PromotedType
3856           << Warnings[Warn].OldParm->getType();
3857         if (Warnings[Warn].OldParm->getLocation().isValid())
3858           Diag(Warnings[Warn].OldParm->getLocation(),
3859                diag::note_previous_declaration);
3860       }
3861 
3862       if (MergeTypeWithOld)
3863         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3864                                              OldProto->getExtProtoInfo()));
3865       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3866     }
3867 
3868     // Fall through to diagnose conflicting types.
3869   }
3870 
3871   // A function that has already been declared has been redeclared or
3872   // defined with a different type; show an appropriate diagnostic.
3873 
3874   // If the previous declaration was an implicitly-generated builtin
3875   // declaration, then at the very least we should use a specialized note.
3876   unsigned BuiltinID;
3877   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3878     // If it's actually a library-defined builtin function like 'malloc'
3879     // or 'printf', just warn about the incompatible redeclaration.
3880     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3881       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3882       Diag(OldLocation, diag::note_previous_builtin_declaration)
3883         << Old << Old->getType();
3884       return false;
3885     }
3886 
3887     PrevDiag = diag::note_previous_builtin_declaration;
3888   }
3889 
3890   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3891   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3892   return true;
3893 }
3894 
3895 /// Completes the merge of two function declarations that are
3896 /// known to be compatible.
3897 ///
3898 /// This routine handles the merging of attributes and other
3899 /// properties of function declarations from the old declaration to
3900 /// the new declaration, once we know that New is in fact a
3901 /// redeclaration of Old.
3902 ///
3903 /// \returns false
3904 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3905                                         Scope *S, bool MergeTypeWithOld) {
3906   // Merge the attributes
3907   mergeDeclAttributes(New, Old);
3908 
3909   // Merge "pure" flag.
3910   if (Old->isPure())
3911     New->setPure();
3912 
3913   // Merge "used" flag.
3914   if (Old->getMostRecentDecl()->isUsed(false))
3915     New->setIsUsed();
3916 
3917   // Merge attributes from the parameters.  These can mismatch with K&R
3918   // declarations.
3919   if (New->getNumParams() == Old->getNumParams())
3920       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3921         ParmVarDecl *NewParam = New->getParamDecl(i);
3922         ParmVarDecl *OldParam = Old->getParamDecl(i);
3923         mergeParamDeclAttributes(NewParam, OldParam, *this);
3924         mergeParamDeclTypes(NewParam, OldParam, *this);
3925       }
3926 
3927   if (getLangOpts().CPlusPlus)
3928     return MergeCXXFunctionDecl(New, Old, S);
3929 
3930   // Merge the function types so the we get the composite types for the return
3931   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3932   // was visible.
3933   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3934   if (!Merged.isNull() && MergeTypeWithOld)
3935     New->setType(Merged);
3936 
3937   return false;
3938 }
3939 
3940 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3941                                 ObjCMethodDecl *oldMethod) {
3942   // Merge the attributes, including deprecated/unavailable
3943   AvailabilityMergeKind MergeKind =
3944       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3945           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3946                                      : AMK_ProtocolImplementation)
3947           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3948                                                            : AMK_Override;
3949 
3950   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3951 
3952   // Merge attributes from the parameters.
3953   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3954                                        oe = oldMethod->param_end();
3955   for (ObjCMethodDecl::param_iterator
3956          ni = newMethod->param_begin(), ne = newMethod->param_end();
3957        ni != ne && oi != oe; ++ni, ++oi)
3958     mergeParamDeclAttributes(*ni, *oi, *this);
3959 
3960   CheckObjCMethodOverride(newMethod, oldMethod);
3961 }
3962 
3963 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3964   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3965 
3966   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3967          ? diag::err_redefinition_different_type
3968          : diag::err_redeclaration_different_type)
3969     << New->getDeclName() << New->getType() << Old->getType();
3970 
3971   diag::kind PrevDiag;
3972   SourceLocation OldLocation;
3973   std::tie(PrevDiag, OldLocation)
3974     = getNoteDiagForInvalidRedeclaration(Old, New);
3975   S.Diag(OldLocation, PrevDiag);
3976   New->setInvalidDecl();
3977 }
3978 
3979 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3980 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3981 /// emitting diagnostics as appropriate.
3982 ///
3983 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3984 /// to here in AddInitializerToDecl. We can't check them before the initializer
3985 /// is attached.
3986 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3987                              bool MergeTypeWithOld) {
3988   if (New->isInvalidDecl() || Old->isInvalidDecl())
3989     return;
3990 
3991   QualType MergedT;
3992   if (getLangOpts().CPlusPlus) {
3993     if (New->getType()->isUndeducedType()) {
3994       // We don't know what the new type is until the initializer is attached.
3995       return;
3996     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3997       // These could still be something that needs exception specs checked.
3998       return MergeVarDeclExceptionSpecs(New, Old);
3999     }
4000     // C++ [basic.link]p10:
4001     //   [...] the types specified by all declarations referring to a given
4002     //   object or function shall be identical, except that declarations for an
4003     //   array object can specify array types that differ by the presence or
4004     //   absence of a major array bound (8.3.4).
4005     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4006       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4007       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4008 
4009       // We are merging a variable declaration New into Old. If it has an array
4010       // bound, and that bound differs from Old's bound, we should diagnose the
4011       // mismatch.
4012       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4013         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4014              PrevVD = PrevVD->getPreviousDecl()) {
4015           QualType PrevVDTy = PrevVD->getType();
4016           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4017             continue;
4018 
4019           if (!Context.hasSameType(New->getType(), PrevVDTy))
4020             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4021         }
4022       }
4023 
4024       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4025         if (Context.hasSameType(OldArray->getElementType(),
4026                                 NewArray->getElementType()))
4027           MergedT = New->getType();
4028       }
4029       // FIXME: Check visibility. New is hidden but has a complete type. If New
4030       // has no array bound, it should not inherit one from Old, if Old is not
4031       // visible.
4032       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4033         if (Context.hasSameType(OldArray->getElementType(),
4034                                 NewArray->getElementType()))
4035           MergedT = Old->getType();
4036       }
4037     }
4038     else if (New->getType()->isObjCObjectPointerType() &&
4039                Old->getType()->isObjCObjectPointerType()) {
4040       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4041                                               Old->getType());
4042     }
4043   } else {
4044     // C 6.2.7p2:
4045     //   All declarations that refer to the same object or function shall have
4046     //   compatible type.
4047     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4048   }
4049   if (MergedT.isNull()) {
4050     // It's OK if we couldn't merge types if either type is dependent, for a
4051     // block-scope variable. In other cases (static data members of class
4052     // templates, variable templates, ...), we require the types to be
4053     // equivalent.
4054     // FIXME: The C++ standard doesn't say anything about this.
4055     if ((New->getType()->isDependentType() ||
4056          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4057       // If the old type was dependent, we can't merge with it, so the new type
4058       // becomes dependent for now. We'll reproduce the original type when we
4059       // instantiate the TypeSourceInfo for the variable.
4060       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4061         New->setType(Context.DependentTy);
4062       return;
4063     }
4064     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4065   }
4066 
4067   // Don't actually update the type on the new declaration if the old
4068   // declaration was an extern declaration in a different scope.
4069   if (MergeTypeWithOld)
4070     New->setType(MergedT);
4071 }
4072 
4073 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4074                                   LookupResult &Previous) {
4075   // C11 6.2.7p4:
4076   //   For an identifier with internal or external linkage declared
4077   //   in a scope in which a prior declaration of that identifier is
4078   //   visible, if the prior declaration specifies internal or
4079   //   external linkage, the type of the identifier at the later
4080   //   declaration becomes the composite type.
4081   //
4082   // If the variable isn't visible, we do not merge with its type.
4083   if (Previous.isShadowed())
4084     return false;
4085 
4086   if (S.getLangOpts().CPlusPlus) {
4087     // C++11 [dcl.array]p3:
4088     //   If there is a preceding declaration of the entity in the same
4089     //   scope in which the bound was specified, an omitted array bound
4090     //   is taken to be the same as in that earlier declaration.
4091     return NewVD->isPreviousDeclInSameBlockScope() ||
4092            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4093             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4094   } else {
4095     // If the old declaration was function-local, don't merge with its
4096     // type unless we're in the same function.
4097     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4098            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4099   }
4100 }
4101 
4102 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4103 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4104 /// situation, merging decls or emitting diagnostics as appropriate.
4105 ///
4106 /// Tentative definition rules (C99 6.9.2p2) are checked by
4107 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4108 /// definitions here, since the initializer hasn't been attached.
4109 ///
4110 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4111   // If the new decl is already invalid, don't do any other checking.
4112   if (New->isInvalidDecl())
4113     return;
4114 
4115   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4116     return;
4117 
4118   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4119 
4120   // Verify the old decl was also a variable or variable template.
4121   VarDecl *Old = nullptr;
4122   VarTemplateDecl *OldTemplate = nullptr;
4123   if (Previous.isSingleResult()) {
4124     if (NewTemplate) {
4125       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4126       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4127 
4128       if (auto *Shadow =
4129               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4130         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4131           return New->setInvalidDecl();
4132     } else {
4133       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4134 
4135       if (auto *Shadow =
4136               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4137         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4138           return New->setInvalidDecl();
4139     }
4140   }
4141   if (!Old) {
4142     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4143         << New->getDeclName();
4144     notePreviousDefinition(Previous.getRepresentativeDecl(),
4145                            New->getLocation());
4146     return New->setInvalidDecl();
4147   }
4148 
4149   // If the old declaration was found in an inline namespace and the new
4150   // declaration was qualified, update the DeclContext to match.
4151   adjustDeclContextForDeclaratorDecl(New, Old);
4152 
4153   // Ensure the template parameters are compatible.
4154   if (NewTemplate &&
4155       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4156                                       OldTemplate->getTemplateParameters(),
4157                                       /*Complain=*/true, TPL_TemplateMatch))
4158     return New->setInvalidDecl();
4159 
4160   // C++ [class.mem]p1:
4161   //   A member shall not be declared twice in the member-specification [...]
4162   //
4163   // Here, we need only consider static data members.
4164   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4165     Diag(New->getLocation(), diag::err_duplicate_member)
4166       << New->getIdentifier();
4167     Diag(Old->getLocation(), diag::note_previous_declaration);
4168     New->setInvalidDecl();
4169   }
4170 
4171   mergeDeclAttributes(New, Old);
4172   // Warn if an already-declared variable is made a weak_import in a subsequent
4173   // declaration
4174   if (New->hasAttr<WeakImportAttr>() &&
4175       Old->getStorageClass() == SC_None &&
4176       !Old->hasAttr<WeakImportAttr>()) {
4177     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4178     Diag(Old->getLocation(), diag::note_previous_declaration);
4179     // Remove weak_import attribute on new declaration.
4180     New->dropAttr<WeakImportAttr>();
4181   }
4182 
4183   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4184     if (!Old->hasAttr<InternalLinkageAttr>()) {
4185       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4186           << ILA;
4187       Diag(Old->getLocation(), diag::note_previous_declaration);
4188       New->dropAttr<InternalLinkageAttr>();
4189     }
4190 
4191   // Merge the types.
4192   VarDecl *MostRecent = Old->getMostRecentDecl();
4193   if (MostRecent != Old) {
4194     MergeVarDeclTypes(New, MostRecent,
4195                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4196     if (New->isInvalidDecl())
4197       return;
4198   }
4199 
4200   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4201   if (New->isInvalidDecl())
4202     return;
4203 
4204   diag::kind PrevDiag;
4205   SourceLocation OldLocation;
4206   std::tie(PrevDiag, OldLocation) =
4207       getNoteDiagForInvalidRedeclaration(Old, New);
4208 
4209   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4210   if (New->getStorageClass() == SC_Static &&
4211       !New->isStaticDataMember() &&
4212       Old->hasExternalFormalLinkage()) {
4213     if (getLangOpts().MicrosoftExt) {
4214       Diag(New->getLocation(), diag::ext_static_non_static)
4215           << New->getDeclName();
4216       Diag(OldLocation, PrevDiag);
4217     } else {
4218       Diag(New->getLocation(), diag::err_static_non_static)
4219           << New->getDeclName();
4220       Diag(OldLocation, PrevDiag);
4221       return New->setInvalidDecl();
4222     }
4223   }
4224   // C99 6.2.2p4:
4225   //   For an identifier declared with the storage-class specifier
4226   //   extern in a scope in which a prior declaration of that
4227   //   identifier is visible,23) if the prior declaration specifies
4228   //   internal or external linkage, the linkage of the identifier at
4229   //   the later declaration is the same as the linkage specified at
4230   //   the prior declaration. If no prior declaration is visible, or
4231   //   if the prior declaration specifies no linkage, then the
4232   //   identifier has external linkage.
4233   if (New->hasExternalStorage() && Old->hasLinkage())
4234     /* Okay */;
4235   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4236            !New->isStaticDataMember() &&
4237            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4238     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4239     Diag(OldLocation, PrevDiag);
4240     return New->setInvalidDecl();
4241   }
4242 
4243   // Check if extern is followed by non-extern and vice-versa.
4244   if (New->hasExternalStorage() &&
4245       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4246     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4247     Diag(OldLocation, PrevDiag);
4248     return New->setInvalidDecl();
4249   }
4250   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4251       !New->hasExternalStorage()) {
4252     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4253     Diag(OldLocation, PrevDiag);
4254     return New->setInvalidDecl();
4255   }
4256 
4257   if (CheckRedeclarationModuleOwnership(New, Old))
4258     return;
4259 
4260   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4261 
4262   // FIXME: The test for external storage here seems wrong? We still
4263   // need to check for mismatches.
4264   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4265       // Don't complain about out-of-line definitions of static members.
4266       !(Old->getLexicalDeclContext()->isRecord() &&
4267         !New->getLexicalDeclContext()->isRecord())) {
4268     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4269     Diag(OldLocation, PrevDiag);
4270     return New->setInvalidDecl();
4271   }
4272 
4273   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4274     if (VarDecl *Def = Old->getDefinition()) {
4275       // C++1z [dcl.fcn.spec]p4:
4276       //   If the definition of a variable appears in a translation unit before
4277       //   its first declaration as inline, the program is ill-formed.
4278       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4279       Diag(Def->getLocation(), diag::note_previous_definition);
4280     }
4281   }
4282 
4283   // If this redeclaration makes the variable inline, we may need to add it to
4284   // UndefinedButUsed.
4285   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4286       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4287     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4288                                            SourceLocation()));
4289 
4290   if (New->getTLSKind() != Old->getTLSKind()) {
4291     if (!Old->getTLSKind()) {
4292       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4293       Diag(OldLocation, PrevDiag);
4294     } else if (!New->getTLSKind()) {
4295       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4296       Diag(OldLocation, PrevDiag);
4297     } else {
4298       // Do not allow redeclaration to change the variable between requiring
4299       // static and dynamic initialization.
4300       // FIXME: GCC allows this, but uses the TLS keyword on the first
4301       // declaration to determine the kind. Do we need to be compatible here?
4302       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4303         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4304       Diag(OldLocation, PrevDiag);
4305     }
4306   }
4307 
4308   // C++ doesn't have tentative definitions, so go right ahead and check here.
4309   if (getLangOpts().CPlusPlus &&
4310       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4311     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4312         Old->getCanonicalDecl()->isConstexpr()) {
4313       // This definition won't be a definition any more once it's been merged.
4314       Diag(New->getLocation(),
4315            diag::warn_deprecated_redundant_constexpr_static_def);
4316     } else if (VarDecl *Def = Old->getDefinition()) {
4317       if (checkVarDeclRedefinition(Def, New))
4318         return;
4319     }
4320   }
4321 
4322   if (haveIncompatibleLanguageLinkages(Old, New)) {
4323     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4324     Diag(OldLocation, PrevDiag);
4325     New->setInvalidDecl();
4326     return;
4327   }
4328 
4329   // Merge "used" flag.
4330   if (Old->getMostRecentDecl()->isUsed(false))
4331     New->setIsUsed();
4332 
4333   // Keep a chain of previous declarations.
4334   New->setPreviousDecl(Old);
4335   if (NewTemplate)
4336     NewTemplate->setPreviousDecl(OldTemplate);
4337 
4338   // Inherit access appropriately.
4339   New->setAccess(Old->getAccess());
4340   if (NewTemplate)
4341     NewTemplate->setAccess(New->getAccess());
4342 
4343   if (Old->isInline())
4344     New->setImplicitlyInline();
4345 }
4346 
4347 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4348   SourceManager &SrcMgr = getSourceManager();
4349   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4350   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4351   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4352   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4353   auto &HSI = PP.getHeaderSearchInfo();
4354   StringRef HdrFilename =
4355       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4356 
4357   auto noteFromModuleOrInclude = [&](Module *Mod,
4358                                      SourceLocation IncLoc) -> bool {
4359     // Redefinition errors with modules are common with non modular mapped
4360     // headers, example: a non-modular header H in module A that also gets
4361     // included directly in a TU. Pointing twice to the same header/definition
4362     // is confusing, try to get better diagnostics when modules is on.
4363     if (IncLoc.isValid()) {
4364       if (Mod) {
4365         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4366             << HdrFilename.str() << Mod->getFullModuleName();
4367         if (!Mod->DefinitionLoc.isInvalid())
4368           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4369               << Mod->getFullModuleName();
4370       } else {
4371         Diag(IncLoc, diag::note_redefinition_include_same_file)
4372             << HdrFilename.str();
4373       }
4374       return true;
4375     }
4376 
4377     return false;
4378   };
4379 
4380   // Is it the same file and same offset? Provide more information on why
4381   // this leads to a redefinition error.
4382   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4383     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4384     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4385     bool EmittedDiag =
4386         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4387     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4388 
4389     // If the header has no guards, emit a note suggesting one.
4390     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4391       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4392 
4393     if (EmittedDiag)
4394       return;
4395   }
4396 
4397   // Redefinition coming from different files or couldn't do better above.
4398   if (Old->getLocation().isValid())
4399     Diag(Old->getLocation(), diag::note_previous_definition);
4400 }
4401 
4402 /// We've just determined that \p Old and \p New both appear to be definitions
4403 /// of the same variable. Either diagnose or fix the problem.
4404 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4405   if (!hasVisibleDefinition(Old) &&
4406       (New->getFormalLinkage() == InternalLinkage ||
4407        New->isInline() ||
4408        New->getDescribedVarTemplate() ||
4409        New->getNumTemplateParameterLists() ||
4410        New->getDeclContext()->isDependentContext())) {
4411     // The previous definition is hidden, and multiple definitions are
4412     // permitted (in separate TUs). Demote this to a declaration.
4413     New->demoteThisDefinitionToDeclaration();
4414 
4415     // Make the canonical definition visible.
4416     if (auto *OldTD = Old->getDescribedVarTemplate())
4417       makeMergedDefinitionVisible(OldTD);
4418     makeMergedDefinitionVisible(Old);
4419     return false;
4420   } else {
4421     Diag(New->getLocation(), diag::err_redefinition) << New;
4422     notePreviousDefinition(Old, New->getLocation());
4423     New->setInvalidDecl();
4424     return true;
4425   }
4426 }
4427 
4428 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4429 /// no declarator (e.g. "struct foo;") is parsed.
4430 Decl *
4431 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4432                                  RecordDecl *&AnonRecord) {
4433   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4434                                     AnonRecord);
4435 }
4436 
4437 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4438 // disambiguate entities defined in different scopes.
4439 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4440 // compatibility.
4441 // We will pick our mangling number depending on which version of MSVC is being
4442 // targeted.
4443 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4444   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4445              ? S->getMSCurManglingNumber()
4446              : S->getMSLastManglingNumber();
4447 }
4448 
4449 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4450   if (!Context.getLangOpts().CPlusPlus)
4451     return;
4452 
4453   if (isa<CXXRecordDecl>(Tag->getParent())) {
4454     // If this tag is the direct child of a class, number it if
4455     // it is anonymous.
4456     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4457       return;
4458     MangleNumberingContext &MCtx =
4459         Context.getManglingNumberContext(Tag->getParent());
4460     Context.setManglingNumber(
4461         Tag, MCtx.getManglingNumber(
4462                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4463     return;
4464   }
4465 
4466   // If this tag isn't a direct child of a class, number it if it is local.
4467   MangleNumberingContext *MCtx;
4468   Decl *ManglingContextDecl;
4469   std::tie(MCtx, ManglingContextDecl) =
4470       getCurrentMangleNumberContext(Tag->getDeclContext());
4471   if (MCtx) {
4472     Context.setManglingNumber(
4473         Tag, MCtx->getManglingNumber(
4474                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4475   }
4476 }
4477 
4478 namespace {
4479 struct NonCLikeKind {
4480   enum {
4481     None,
4482     BaseClass,
4483     DefaultMemberInit,
4484     Lambda,
4485     Friend,
4486     OtherMember,
4487     Invalid,
4488   } Kind = None;
4489   SourceRange Range;
4490 
4491   explicit operator bool() { return Kind != None; }
4492 };
4493 }
4494 
4495 /// Determine whether a class is C-like, according to the rules of C++
4496 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4497 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4498   if (RD->isInvalidDecl())
4499     return {NonCLikeKind::Invalid, {}};
4500 
4501   // C++ [dcl.typedef]p9: [P1766R1]
4502   //   An unnamed class with a typedef name for linkage purposes shall not
4503   //
4504   //    -- have any base classes
4505   if (RD->getNumBases())
4506     return {NonCLikeKind::BaseClass,
4507             SourceRange(RD->bases_begin()->getBeginLoc(),
4508                         RD->bases_end()[-1].getEndLoc())};
4509   bool Invalid = false;
4510   for (Decl *D : RD->decls()) {
4511     // Don't complain about things we already diagnosed.
4512     if (D->isInvalidDecl()) {
4513       Invalid = true;
4514       continue;
4515     }
4516 
4517     //  -- have any [...] default member initializers
4518     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4519       if (FD->hasInClassInitializer()) {
4520         auto *Init = FD->getInClassInitializer();
4521         return {NonCLikeKind::DefaultMemberInit,
4522                 Init ? Init->getSourceRange() : D->getSourceRange()};
4523       }
4524       continue;
4525     }
4526 
4527     // FIXME: We don't allow friend declarations. This violates the wording of
4528     // P1766, but not the intent.
4529     if (isa<FriendDecl>(D))
4530       return {NonCLikeKind::Friend, D->getSourceRange()};
4531 
4532     //  -- declare any members other than non-static data members, member
4533     //     enumerations, or member classes,
4534     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4535         isa<EnumDecl>(D))
4536       continue;
4537     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4538     if (!MemberRD) {
4539       if (D->isImplicit())
4540         continue;
4541       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4542     }
4543 
4544     //  -- contain a lambda-expression,
4545     if (MemberRD->isLambda())
4546       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4547 
4548     //  and all member classes shall also satisfy these requirements
4549     //  (recursively).
4550     if (MemberRD->isThisDeclarationADefinition()) {
4551       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4552         return Kind;
4553     }
4554   }
4555 
4556   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4557 }
4558 
4559 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4560                                         TypedefNameDecl *NewTD) {
4561   if (TagFromDeclSpec->isInvalidDecl())
4562     return;
4563 
4564   // Do nothing if the tag already has a name for linkage purposes.
4565   if (TagFromDeclSpec->hasNameForLinkage())
4566     return;
4567 
4568   // A well-formed anonymous tag must always be a TUK_Definition.
4569   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4570 
4571   // The type must match the tag exactly;  no qualifiers allowed.
4572   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4573                            Context.getTagDeclType(TagFromDeclSpec))) {
4574     if (getLangOpts().CPlusPlus)
4575       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4576     return;
4577   }
4578 
4579   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4580   //   An unnamed class with a typedef name for linkage purposes shall [be
4581   //   C-like].
4582   //
4583   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4584   // shouldn't happen, but there are constructs that the language rule doesn't
4585   // disallow for which we can't reasonably avoid computing linkage early.
4586   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4587   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4588                              : NonCLikeKind();
4589   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4590   if (NonCLike || ChangesLinkage) {
4591     if (NonCLike.Kind == NonCLikeKind::Invalid)
4592       return;
4593 
4594     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4595     if (ChangesLinkage) {
4596       // If the linkage changes, we can't accept this as an extension.
4597       if (NonCLike.Kind == NonCLikeKind::None)
4598         DiagID = diag::err_typedef_changes_linkage;
4599       else
4600         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4601     }
4602 
4603     SourceLocation FixitLoc =
4604         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4605     llvm::SmallString<40> TextToInsert;
4606     TextToInsert += ' ';
4607     TextToInsert += NewTD->getIdentifier()->getName();
4608 
4609     Diag(FixitLoc, DiagID)
4610       << isa<TypeAliasDecl>(NewTD)
4611       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4612     if (NonCLike.Kind != NonCLikeKind::None) {
4613       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4614         << NonCLike.Kind - 1 << NonCLike.Range;
4615     }
4616     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4617       << NewTD << isa<TypeAliasDecl>(NewTD);
4618 
4619     if (ChangesLinkage)
4620       return;
4621   }
4622 
4623   // Otherwise, set this as the anon-decl typedef for the tag.
4624   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4625 }
4626 
4627 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4628   switch (T) {
4629   case DeclSpec::TST_class:
4630     return 0;
4631   case DeclSpec::TST_struct:
4632     return 1;
4633   case DeclSpec::TST_interface:
4634     return 2;
4635   case DeclSpec::TST_union:
4636     return 3;
4637   case DeclSpec::TST_enum:
4638     return 4;
4639   default:
4640     llvm_unreachable("unexpected type specifier");
4641   }
4642 }
4643 
4644 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4645 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4646 /// parameters to cope with template friend declarations.
4647 Decl *
4648 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4649                                  MultiTemplateParamsArg TemplateParams,
4650                                  bool IsExplicitInstantiation,
4651                                  RecordDecl *&AnonRecord) {
4652   Decl *TagD = nullptr;
4653   TagDecl *Tag = nullptr;
4654   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4655       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4656       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4657       DS.getTypeSpecType() == DeclSpec::TST_union ||
4658       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4659     TagD = DS.getRepAsDecl();
4660 
4661     if (!TagD) // We probably had an error
4662       return nullptr;
4663 
4664     // Note that the above type specs guarantee that the
4665     // type rep is a Decl, whereas in many of the others
4666     // it's a Type.
4667     if (isa<TagDecl>(TagD))
4668       Tag = cast<TagDecl>(TagD);
4669     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4670       Tag = CTD->getTemplatedDecl();
4671   }
4672 
4673   if (Tag) {
4674     handleTagNumbering(Tag, S);
4675     Tag->setFreeStanding();
4676     if (Tag->isInvalidDecl())
4677       return Tag;
4678   }
4679 
4680   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4681     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4682     // or incomplete types shall not be restrict-qualified."
4683     if (TypeQuals & DeclSpec::TQ_restrict)
4684       Diag(DS.getRestrictSpecLoc(),
4685            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4686            << DS.getSourceRange();
4687   }
4688 
4689   if (DS.isInlineSpecified())
4690     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4691         << getLangOpts().CPlusPlus17;
4692 
4693   if (DS.hasConstexprSpecifier()) {
4694     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4695     // and definitions of functions and variables.
4696     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4697     // the declaration of a function or function template
4698     if (Tag)
4699       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4700           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4701           << static_cast<int>(DS.getConstexprSpecifier());
4702     else
4703       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4704           << static_cast<int>(DS.getConstexprSpecifier());
4705     // Don't emit warnings after this error.
4706     return TagD;
4707   }
4708 
4709   DiagnoseFunctionSpecifiers(DS);
4710 
4711   if (DS.isFriendSpecified()) {
4712     // If we're dealing with a decl but not a TagDecl, assume that
4713     // whatever routines created it handled the friendship aspect.
4714     if (TagD && !Tag)
4715       return nullptr;
4716     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4717   }
4718 
4719   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4720   bool IsExplicitSpecialization =
4721     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4722   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4723       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4724       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4725     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4726     // nested-name-specifier unless it is an explicit instantiation
4727     // or an explicit specialization.
4728     //
4729     // FIXME: We allow class template partial specializations here too, per the
4730     // obvious intent of DR1819.
4731     //
4732     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4733     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4734         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4735     return nullptr;
4736   }
4737 
4738   // Track whether this decl-specifier declares anything.
4739   bool DeclaresAnything = true;
4740 
4741   // Handle anonymous struct definitions.
4742   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4743     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4744         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4745       if (getLangOpts().CPlusPlus ||
4746           Record->getDeclContext()->isRecord()) {
4747         // If CurContext is a DeclContext that can contain statements,
4748         // RecursiveASTVisitor won't visit the decls that
4749         // BuildAnonymousStructOrUnion() will put into CurContext.
4750         // Also store them here so that they can be part of the
4751         // DeclStmt that gets created in this case.
4752         // FIXME: Also return the IndirectFieldDecls created by
4753         // BuildAnonymousStructOr union, for the same reason?
4754         if (CurContext->isFunctionOrMethod())
4755           AnonRecord = Record;
4756         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4757                                            Context.getPrintingPolicy());
4758       }
4759 
4760       DeclaresAnything = false;
4761     }
4762   }
4763 
4764   // C11 6.7.2.1p2:
4765   //   A struct-declaration that does not declare an anonymous structure or
4766   //   anonymous union shall contain a struct-declarator-list.
4767   //
4768   // This rule also existed in C89 and C99; the grammar for struct-declaration
4769   // did not permit a struct-declaration without a struct-declarator-list.
4770   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4771       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4772     // Check for Microsoft C extension: anonymous struct/union member.
4773     // Handle 2 kinds of anonymous struct/union:
4774     //   struct STRUCT;
4775     //   union UNION;
4776     // and
4777     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4778     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4779     if ((Tag && Tag->getDeclName()) ||
4780         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4781       RecordDecl *Record = nullptr;
4782       if (Tag)
4783         Record = dyn_cast<RecordDecl>(Tag);
4784       else if (const RecordType *RT =
4785                    DS.getRepAsType().get()->getAsStructureType())
4786         Record = RT->getDecl();
4787       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4788         Record = UT->getDecl();
4789 
4790       if (Record && getLangOpts().MicrosoftExt) {
4791         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4792             << Record->isUnion() << DS.getSourceRange();
4793         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4794       }
4795 
4796       DeclaresAnything = false;
4797     }
4798   }
4799 
4800   // Skip all the checks below if we have a type error.
4801   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4802       (TagD && TagD->isInvalidDecl()))
4803     return TagD;
4804 
4805   if (getLangOpts().CPlusPlus &&
4806       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4807     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4808       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4809           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4810         DeclaresAnything = false;
4811 
4812   if (!DS.isMissingDeclaratorOk()) {
4813     // Customize diagnostic for a typedef missing a name.
4814     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4815       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4816           << DS.getSourceRange();
4817     else
4818       DeclaresAnything = false;
4819   }
4820 
4821   if (DS.isModulePrivateSpecified() &&
4822       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4823     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4824       << Tag->getTagKind()
4825       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4826 
4827   ActOnDocumentableDecl(TagD);
4828 
4829   // C 6.7/2:
4830   //   A declaration [...] shall declare at least a declarator [...], a tag,
4831   //   or the members of an enumeration.
4832   // C++ [dcl.dcl]p3:
4833   //   [If there are no declarators], and except for the declaration of an
4834   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4835   //   names into the program, or shall redeclare a name introduced by a
4836   //   previous declaration.
4837   if (!DeclaresAnything) {
4838     // In C, we allow this as a (popular) extension / bug. Don't bother
4839     // producing further diagnostics for redundant qualifiers after this.
4840     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4841                                ? diag::err_no_declarators
4842                                : diag::ext_no_declarators)
4843         << DS.getSourceRange();
4844     return TagD;
4845   }
4846 
4847   // C++ [dcl.stc]p1:
4848   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4849   //   init-declarator-list of the declaration shall not be empty.
4850   // C++ [dcl.fct.spec]p1:
4851   //   If a cv-qualifier appears in a decl-specifier-seq, the
4852   //   init-declarator-list of the declaration shall not be empty.
4853   //
4854   // Spurious qualifiers here appear to be valid in C.
4855   unsigned DiagID = diag::warn_standalone_specifier;
4856   if (getLangOpts().CPlusPlus)
4857     DiagID = diag::ext_standalone_specifier;
4858 
4859   // Note that a linkage-specification sets a storage class, but
4860   // 'extern "C" struct foo;' is actually valid and not theoretically
4861   // useless.
4862   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4863     if (SCS == DeclSpec::SCS_mutable)
4864       // Since mutable is not a viable storage class specifier in C, there is
4865       // no reason to treat it as an extension. Instead, diagnose as an error.
4866       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4867     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4868       Diag(DS.getStorageClassSpecLoc(), DiagID)
4869         << DeclSpec::getSpecifierName(SCS);
4870   }
4871 
4872   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4873     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4874       << DeclSpec::getSpecifierName(TSCS);
4875   if (DS.getTypeQualifiers()) {
4876     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4877       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4878     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4879       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4880     // Restrict is covered above.
4881     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4882       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4883     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4884       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4885   }
4886 
4887   // Warn about ignored type attributes, for example:
4888   // __attribute__((aligned)) struct A;
4889   // Attributes should be placed after tag to apply to type declaration.
4890   if (!DS.getAttributes().empty()) {
4891     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4892     if (TypeSpecType == DeclSpec::TST_class ||
4893         TypeSpecType == DeclSpec::TST_struct ||
4894         TypeSpecType == DeclSpec::TST_interface ||
4895         TypeSpecType == DeclSpec::TST_union ||
4896         TypeSpecType == DeclSpec::TST_enum) {
4897       for (const ParsedAttr &AL : DS.getAttributes())
4898         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4899             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4900     }
4901   }
4902 
4903   return TagD;
4904 }
4905 
4906 /// We are trying to inject an anonymous member into the given scope;
4907 /// check if there's an existing declaration that can't be overloaded.
4908 ///
4909 /// \return true if this is a forbidden redeclaration
4910 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4911                                          Scope *S,
4912                                          DeclContext *Owner,
4913                                          DeclarationName Name,
4914                                          SourceLocation NameLoc,
4915                                          bool IsUnion) {
4916   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4917                  Sema::ForVisibleRedeclaration);
4918   if (!SemaRef.LookupName(R, S)) return false;
4919 
4920   // Pick a representative declaration.
4921   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4922   assert(PrevDecl && "Expected a non-null Decl");
4923 
4924   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4925     return false;
4926 
4927   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4928     << IsUnion << Name;
4929   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4930 
4931   return true;
4932 }
4933 
4934 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4935 /// anonymous struct or union AnonRecord into the owning context Owner
4936 /// and scope S. This routine will be invoked just after we realize
4937 /// that an unnamed union or struct is actually an anonymous union or
4938 /// struct, e.g.,
4939 ///
4940 /// @code
4941 /// union {
4942 ///   int i;
4943 ///   float f;
4944 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4945 ///    // f into the surrounding scope.x
4946 /// @endcode
4947 ///
4948 /// This routine is recursive, injecting the names of nested anonymous
4949 /// structs/unions into the owning context and scope as well.
4950 static bool
4951 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4952                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4953                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4954   bool Invalid = false;
4955 
4956   // Look every FieldDecl and IndirectFieldDecl with a name.
4957   for (auto *D : AnonRecord->decls()) {
4958     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4959         cast<NamedDecl>(D)->getDeclName()) {
4960       ValueDecl *VD = cast<ValueDecl>(D);
4961       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4962                                        VD->getLocation(),
4963                                        AnonRecord->isUnion())) {
4964         // C++ [class.union]p2:
4965         //   The names of the members of an anonymous union shall be
4966         //   distinct from the names of any other entity in the
4967         //   scope in which the anonymous union is declared.
4968         Invalid = true;
4969       } else {
4970         // C++ [class.union]p2:
4971         //   For the purpose of name lookup, after the anonymous union
4972         //   definition, the members of the anonymous union are
4973         //   considered to have been defined in the scope in which the
4974         //   anonymous union is declared.
4975         unsigned OldChainingSize = Chaining.size();
4976         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4977           Chaining.append(IF->chain_begin(), IF->chain_end());
4978         else
4979           Chaining.push_back(VD);
4980 
4981         assert(Chaining.size() >= 2);
4982         NamedDecl **NamedChain =
4983           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4984         for (unsigned i = 0; i < Chaining.size(); i++)
4985           NamedChain[i] = Chaining[i];
4986 
4987         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4988             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4989             VD->getType(), {NamedChain, Chaining.size()});
4990 
4991         for (const auto *Attr : VD->attrs())
4992           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4993 
4994         IndirectField->setAccess(AS);
4995         IndirectField->setImplicit();
4996         SemaRef.PushOnScopeChains(IndirectField, S);
4997 
4998         // That includes picking up the appropriate access specifier.
4999         if (AS != AS_none) IndirectField->setAccess(AS);
5000 
5001         Chaining.resize(OldChainingSize);
5002       }
5003     }
5004   }
5005 
5006   return Invalid;
5007 }
5008 
5009 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5010 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5011 /// illegal input values are mapped to SC_None.
5012 static StorageClass
5013 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5014   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5015   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5016          "Parser allowed 'typedef' as storage class VarDecl.");
5017   switch (StorageClassSpec) {
5018   case DeclSpec::SCS_unspecified:    return SC_None;
5019   case DeclSpec::SCS_extern:
5020     if (DS.isExternInLinkageSpec())
5021       return SC_None;
5022     return SC_Extern;
5023   case DeclSpec::SCS_static:         return SC_Static;
5024   case DeclSpec::SCS_auto:           return SC_Auto;
5025   case DeclSpec::SCS_register:       return SC_Register;
5026   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5027     // Illegal SCSs map to None: error reporting is up to the caller.
5028   case DeclSpec::SCS_mutable:        // Fall through.
5029   case DeclSpec::SCS_typedef:        return SC_None;
5030   }
5031   llvm_unreachable("unknown storage class specifier");
5032 }
5033 
5034 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5035   assert(Record->hasInClassInitializer());
5036 
5037   for (const auto *I : Record->decls()) {
5038     const auto *FD = dyn_cast<FieldDecl>(I);
5039     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5040       FD = IFD->getAnonField();
5041     if (FD && FD->hasInClassInitializer())
5042       return FD->getLocation();
5043   }
5044 
5045   llvm_unreachable("couldn't find in-class initializer");
5046 }
5047 
5048 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5049                                       SourceLocation DefaultInitLoc) {
5050   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5051     return;
5052 
5053   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5054   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5055 }
5056 
5057 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5058                                       CXXRecordDecl *AnonUnion) {
5059   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5060     return;
5061 
5062   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5063 }
5064 
5065 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5066 /// anonymous structure or union. Anonymous unions are a C++ feature
5067 /// (C++ [class.union]) and a C11 feature; anonymous structures
5068 /// are a C11 feature and GNU C++ extension.
5069 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5070                                         AccessSpecifier AS,
5071                                         RecordDecl *Record,
5072                                         const PrintingPolicy &Policy) {
5073   DeclContext *Owner = Record->getDeclContext();
5074 
5075   // Diagnose whether this anonymous struct/union is an extension.
5076   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5077     Diag(Record->getLocation(), diag::ext_anonymous_union);
5078   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5079     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5080   else if (!Record->isUnion() && !getLangOpts().C11)
5081     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5082 
5083   // C and C++ require different kinds of checks for anonymous
5084   // structs/unions.
5085   bool Invalid = false;
5086   if (getLangOpts().CPlusPlus) {
5087     const char *PrevSpec = nullptr;
5088     if (Record->isUnion()) {
5089       // C++ [class.union]p6:
5090       // C++17 [class.union.anon]p2:
5091       //   Anonymous unions declared in a named namespace or in the
5092       //   global namespace shall be declared static.
5093       unsigned DiagID;
5094       DeclContext *OwnerScope = Owner->getRedeclContext();
5095       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5096           (OwnerScope->isTranslationUnit() ||
5097            (OwnerScope->isNamespace() &&
5098             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5099         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5100           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5101 
5102         // Recover by adding 'static'.
5103         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5104                                PrevSpec, DiagID, Policy);
5105       }
5106       // C++ [class.union]p6:
5107       //   A storage class is not allowed in a declaration of an
5108       //   anonymous union in a class scope.
5109       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5110                isa<RecordDecl>(Owner)) {
5111         Diag(DS.getStorageClassSpecLoc(),
5112              diag::err_anonymous_union_with_storage_spec)
5113           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5114 
5115         // Recover by removing the storage specifier.
5116         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5117                                SourceLocation(),
5118                                PrevSpec, DiagID, Context.getPrintingPolicy());
5119       }
5120     }
5121 
5122     // Ignore const/volatile/restrict qualifiers.
5123     if (DS.getTypeQualifiers()) {
5124       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5125         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5126           << Record->isUnion() << "const"
5127           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5128       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5129         Diag(DS.getVolatileSpecLoc(),
5130              diag::ext_anonymous_struct_union_qualified)
5131           << Record->isUnion() << "volatile"
5132           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5133       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5134         Diag(DS.getRestrictSpecLoc(),
5135              diag::ext_anonymous_struct_union_qualified)
5136           << Record->isUnion() << "restrict"
5137           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5138       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5139         Diag(DS.getAtomicSpecLoc(),
5140              diag::ext_anonymous_struct_union_qualified)
5141           << Record->isUnion() << "_Atomic"
5142           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5143       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5144         Diag(DS.getUnalignedSpecLoc(),
5145              diag::ext_anonymous_struct_union_qualified)
5146           << Record->isUnion() << "__unaligned"
5147           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5148 
5149       DS.ClearTypeQualifiers();
5150     }
5151 
5152     // C++ [class.union]p2:
5153     //   The member-specification of an anonymous union shall only
5154     //   define non-static data members. [Note: nested types and
5155     //   functions cannot be declared within an anonymous union. ]
5156     for (auto *Mem : Record->decls()) {
5157       // Ignore invalid declarations; we already diagnosed them.
5158       if (Mem->isInvalidDecl())
5159         continue;
5160 
5161       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5162         // C++ [class.union]p3:
5163         //   An anonymous union shall not have private or protected
5164         //   members (clause 11).
5165         assert(FD->getAccess() != AS_none);
5166         if (FD->getAccess() != AS_public) {
5167           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5168             << Record->isUnion() << (FD->getAccess() == AS_protected);
5169           Invalid = true;
5170         }
5171 
5172         // C++ [class.union]p1
5173         //   An object of a class with a non-trivial constructor, a non-trivial
5174         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5175         //   assignment operator cannot be a member of a union, nor can an
5176         //   array of such objects.
5177         if (CheckNontrivialField(FD))
5178           Invalid = true;
5179       } else if (Mem->isImplicit()) {
5180         // Any implicit members are fine.
5181       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5182         // This is a type that showed up in an
5183         // elaborated-type-specifier inside the anonymous struct or
5184         // union, but which actually declares a type outside of the
5185         // anonymous struct or union. It's okay.
5186       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5187         if (!MemRecord->isAnonymousStructOrUnion() &&
5188             MemRecord->getDeclName()) {
5189           // Visual C++ allows type definition in anonymous struct or union.
5190           if (getLangOpts().MicrosoftExt)
5191             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5192               << Record->isUnion();
5193           else {
5194             // This is a nested type declaration.
5195             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5196               << Record->isUnion();
5197             Invalid = true;
5198           }
5199         } else {
5200           // This is an anonymous type definition within another anonymous type.
5201           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5202           // not part of standard C++.
5203           Diag(MemRecord->getLocation(),
5204                diag::ext_anonymous_record_with_anonymous_type)
5205             << Record->isUnion();
5206         }
5207       } else if (isa<AccessSpecDecl>(Mem)) {
5208         // Any access specifier is fine.
5209       } else if (isa<StaticAssertDecl>(Mem)) {
5210         // In C++1z, static_assert declarations are also fine.
5211       } else {
5212         // We have something that isn't a non-static data
5213         // member. Complain about it.
5214         unsigned DK = diag::err_anonymous_record_bad_member;
5215         if (isa<TypeDecl>(Mem))
5216           DK = diag::err_anonymous_record_with_type;
5217         else if (isa<FunctionDecl>(Mem))
5218           DK = diag::err_anonymous_record_with_function;
5219         else if (isa<VarDecl>(Mem))
5220           DK = diag::err_anonymous_record_with_static;
5221 
5222         // Visual C++ allows type definition in anonymous struct or union.
5223         if (getLangOpts().MicrosoftExt &&
5224             DK == diag::err_anonymous_record_with_type)
5225           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5226             << Record->isUnion();
5227         else {
5228           Diag(Mem->getLocation(), DK) << Record->isUnion();
5229           Invalid = true;
5230         }
5231       }
5232     }
5233 
5234     // C++11 [class.union]p8 (DR1460):
5235     //   At most one variant member of a union may have a
5236     //   brace-or-equal-initializer.
5237     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5238         Owner->isRecord())
5239       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5240                                 cast<CXXRecordDecl>(Record));
5241   }
5242 
5243   if (!Record->isUnion() && !Owner->isRecord()) {
5244     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5245       << getLangOpts().CPlusPlus;
5246     Invalid = true;
5247   }
5248 
5249   // C++ [dcl.dcl]p3:
5250   //   [If there are no declarators], and except for the declaration of an
5251   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5252   //   names into the program
5253   // C++ [class.mem]p2:
5254   //   each such member-declaration shall either declare at least one member
5255   //   name of the class or declare at least one unnamed bit-field
5256   //
5257   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5258   if (getLangOpts().CPlusPlus && Record->field_empty())
5259     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5260 
5261   // Mock up a declarator.
5262   Declarator Dc(DS, DeclaratorContext::Member);
5263   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5264   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5265 
5266   // Create a declaration for this anonymous struct/union.
5267   NamedDecl *Anon = nullptr;
5268   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5269     Anon = FieldDecl::Create(
5270         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5271         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5272         /*BitWidth=*/nullptr, /*Mutable=*/false,
5273         /*InitStyle=*/ICIS_NoInit);
5274     Anon->setAccess(AS);
5275     ProcessDeclAttributes(S, Anon, Dc);
5276 
5277     if (getLangOpts().CPlusPlus)
5278       FieldCollector->Add(cast<FieldDecl>(Anon));
5279   } else {
5280     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5281     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5282     if (SCSpec == DeclSpec::SCS_mutable) {
5283       // mutable can only appear on non-static class members, so it's always
5284       // an error here
5285       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5286       Invalid = true;
5287       SC = SC_None;
5288     }
5289 
5290     assert(DS.getAttributes().empty() && "No attribute expected");
5291     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5292                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5293                            Context.getTypeDeclType(Record), TInfo, SC);
5294 
5295     // Default-initialize the implicit variable. This initialization will be
5296     // trivial in almost all cases, except if a union member has an in-class
5297     // initializer:
5298     //   union { int n = 0; };
5299     if (!Invalid)
5300       ActOnUninitializedDecl(Anon);
5301   }
5302   Anon->setImplicit();
5303 
5304   // Mark this as an anonymous struct/union type.
5305   Record->setAnonymousStructOrUnion(true);
5306 
5307   // Add the anonymous struct/union object to the current
5308   // context. We'll be referencing this object when we refer to one of
5309   // its members.
5310   Owner->addDecl(Anon);
5311 
5312   // Inject the members of the anonymous struct/union into the owning
5313   // context and into the identifier resolver chain for name lookup
5314   // purposes.
5315   SmallVector<NamedDecl*, 2> Chain;
5316   Chain.push_back(Anon);
5317 
5318   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5319     Invalid = true;
5320 
5321   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5322     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5323       MangleNumberingContext *MCtx;
5324       Decl *ManglingContextDecl;
5325       std::tie(MCtx, ManglingContextDecl) =
5326           getCurrentMangleNumberContext(NewVD->getDeclContext());
5327       if (MCtx) {
5328         Context.setManglingNumber(
5329             NewVD, MCtx->getManglingNumber(
5330                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5331         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5332       }
5333     }
5334   }
5335 
5336   if (Invalid)
5337     Anon->setInvalidDecl();
5338 
5339   return Anon;
5340 }
5341 
5342 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5343 /// Microsoft C anonymous structure.
5344 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5345 /// Example:
5346 ///
5347 /// struct A { int a; };
5348 /// struct B { struct A; int b; };
5349 ///
5350 /// void foo() {
5351 ///   B var;
5352 ///   var.a = 3;
5353 /// }
5354 ///
5355 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5356                                            RecordDecl *Record) {
5357   assert(Record && "expected a record!");
5358 
5359   // Mock up a declarator.
5360   Declarator Dc(DS, DeclaratorContext::TypeName);
5361   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5362   assert(TInfo && "couldn't build declarator info for anonymous struct");
5363 
5364   auto *ParentDecl = cast<RecordDecl>(CurContext);
5365   QualType RecTy = Context.getTypeDeclType(Record);
5366 
5367   // Create a declaration for this anonymous struct.
5368   NamedDecl *Anon =
5369       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5370                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5371                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5372                         /*InitStyle=*/ICIS_NoInit);
5373   Anon->setImplicit();
5374 
5375   // Add the anonymous struct object to the current context.
5376   CurContext->addDecl(Anon);
5377 
5378   // Inject the members of the anonymous struct into the current
5379   // context and into the identifier resolver chain for name lookup
5380   // purposes.
5381   SmallVector<NamedDecl*, 2> Chain;
5382   Chain.push_back(Anon);
5383 
5384   RecordDecl *RecordDef = Record->getDefinition();
5385   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5386                                diag::err_field_incomplete_or_sizeless) ||
5387       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5388                                           AS_none, Chain)) {
5389     Anon->setInvalidDecl();
5390     ParentDecl->setInvalidDecl();
5391   }
5392 
5393   return Anon;
5394 }
5395 
5396 /// GetNameForDeclarator - Determine the full declaration name for the
5397 /// given Declarator.
5398 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5399   return GetNameFromUnqualifiedId(D.getName());
5400 }
5401 
5402 /// Retrieves the declaration name from a parsed unqualified-id.
5403 DeclarationNameInfo
5404 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5405   DeclarationNameInfo NameInfo;
5406   NameInfo.setLoc(Name.StartLocation);
5407 
5408   switch (Name.getKind()) {
5409 
5410   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5411   case UnqualifiedIdKind::IK_Identifier:
5412     NameInfo.setName(Name.Identifier);
5413     return NameInfo;
5414 
5415   case UnqualifiedIdKind::IK_DeductionGuideName: {
5416     // C++ [temp.deduct.guide]p3:
5417     //   The simple-template-id shall name a class template specialization.
5418     //   The template-name shall be the same identifier as the template-name
5419     //   of the simple-template-id.
5420     // These together intend to imply that the template-name shall name a
5421     // class template.
5422     // FIXME: template<typename T> struct X {};
5423     //        template<typename T> using Y = X<T>;
5424     //        Y(int) -> Y<int>;
5425     //   satisfies these rules but does not name a class template.
5426     TemplateName TN = Name.TemplateName.get().get();
5427     auto *Template = TN.getAsTemplateDecl();
5428     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5429       Diag(Name.StartLocation,
5430            diag::err_deduction_guide_name_not_class_template)
5431         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5432       if (Template)
5433         Diag(Template->getLocation(), diag::note_template_decl_here);
5434       return DeclarationNameInfo();
5435     }
5436 
5437     NameInfo.setName(
5438         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5439     return NameInfo;
5440   }
5441 
5442   case UnqualifiedIdKind::IK_OperatorFunctionId:
5443     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5444                                            Name.OperatorFunctionId.Operator));
5445     NameInfo.setCXXOperatorNameRange(SourceRange(
5446         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5447     return NameInfo;
5448 
5449   case UnqualifiedIdKind::IK_LiteralOperatorId:
5450     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5451                                                            Name.Identifier));
5452     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5453     return NameInfo;
5454 
5455   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5456     TypeSourceInfo *TInfo;
5457     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5458     if (Ty.isNull())
5459       return DeclarationNameInfo();
5460     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5461                                                Context.getCanonicalType(Ty)));
5462     NameInfo.setNamedTypeInfo(TInfo);
5463     return NameInfo;
5464   }
5465 
5466   case UnqualifiedIdKind::IK_ConstructorName: {
5467     TypeSourceInfo *TInfo;
5468     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5469     if (Ty.isNull())
5470       return DeclarationNameInfo();
5471     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5472                                               Context.getCanonicalType(Ty)));
5473     NameInfo.setNamedTypeInfo(TInfo);
5474     return NameInfo;
5475   }
5476 
5477   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5478     // In well-formed code, we can only have a constructor
5479     // template-id that refers to the current context, so go there
5480     // to find the actual type being constructed.
5481     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5482     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5483       return DeclarationNameInfo();
5484 
5485     // Determine the type of the class being constructed.
5486     QualType CurClassType = Context.getTypeDeclType(CurClass);
5487 
5488     // FIXME: Check two things: that the template-id names the same type as
5489     // CurClassType, and that the template-id does not occur when the name
5490     // was qualified.
5491 
5492     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5493                                     Context.getCanonicalType(CurClassType)));
5494     // FIXME: should we retrieve TypeSourceInfo?
5495     NameInfo.setNamedTypeInfo(nullptr);
5496     return NameInfo;
5497   }
5498 
5499   case UnqualifiedIdKind::IK_DestructorName: {
5500     TypeSourceInfo *TInfo;
5501     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5502     if (Ty.isNull())
5503       return DeclarationNameInfo();
5504     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5505                                               Context.getCanonicalType(Ty)));
5506     NameInfo.setNamedTypeInfo(TInfo);
5507     return NameInfo;
5508   }
5509 
5510   case UnqualifiedIdKind::IK_TemplateId: {
5511     TemplateName TName = Name.TemplateId->Template.get();
5512     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5513     return Context.getNameForTemplate(TName, TNameLoc);
5514   }
5515 
5516   } // switch (Name.getKind())
5517 
5518   llvm_unreachable("Unknown name kind");
5519 }
5520 
5521 static QualType getCoreType(QualType Ty) {
5522   do {
5523     if (Ty->isPointerType() || Ty->isReferenceType())
5524       Ty = Ty->getPointeeType();
5525     else if (Ty->isArrayType())
5526       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5527     else
5528       return Ty.withoutLocalFastQualifiers();
5529   } while (true);
5530 }
5531 
5532 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5533 /// and Definition have "nearly" matching parameters. This heuristic is
5534 /// used to improve diagnostics in the case where an out-of-line function
5535 /// definition doesn't match any declaration within the class or namespace.
5536 /// Also sets Params to the list of indices to the parameters that differ
5537 /// between the declaration and the definition. If hasSimilarParameters
5538 /// returns true and Params is empty, then all of the parameters match.
5539 static bool hasSimilarParameters(ASTContext &Context,
5540                                      FunctionDecl *Declaration,
5541                                      FunctionDecl *Definition,
5542                                      SmallVectorImpl<unsigned> &Params) {
5543   Params.clear();
5544   if (Declaration->param_size() != Definition->param_size())
5545     return false;
5546   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5547     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5548     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5549 
5550     // The parameter types are identical
5551     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5552       continue;
5553 
5554     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5555     QualType DefParamBaseTy = getCoreType(DefParamTy);
5556     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5557     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5558 
5559     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5560         (DeclTyName && DeclTyName == DefTyName))
5561       Params.push_back(Idx);
5562     else  // The two parameters aren't even close
5563       return false;
5564   }
5565 
5566   return true;
5567 }
5568 
5569 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5570 /// declarator needs to be rebuilt in the current instantiation.
5571 /// Any bits of declarator which appear before the name are valid for
5572 /// consideration here.  That's specifically the type in the decl spec
5573 /// and the base type in any member-pointer chunks.
5574 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5575                                                     DeclarationName Name) {
5576   // The types we specifically need to rebuild are:
5577   //   - typenames, typeofs, and decltypes
5578   //   - types which will become injected class names
5579   // Of course, we also need to rebuild any type referencing such a
5580   // type.  It's safest to just say "dependent", but we call out a
5581   // few cases here.
5582 
5583   DeclSpec &DS = D.getMutableDeclSpec();
5584   switch (DS.getTypeSpecType()) {
5585   case DeclSpec::TST_typename:
5586   case DeclSpec::TST_typeofType:
5587   case DeclSpec::TST_underlyingType:
5588   case DeclSpec::TST_atomic: {
5589     // Grab the type from the parser.
5590     TypeSourceInfo *TSI = nullptr;
5591     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5592     if (T.isNull() || !T->isInstantiationDependentType()) break;
5593 
5594     // Make sure there's a type source info.  This isn't really much
5595     // of a waste; most dependent types should have type source info
5596     // attached already.
5597     if (!TSI)
5598       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5599 
5600     // Rebuild the type in the current instantiation.
5601     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5602     if (!TSI) return true;
5603 
5604     // Store the new type back in the decl spec.
5605     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5606     DS.UpdateTypeRep(LocType);
5607     break;
5608   }
5609 
5610   case DeclSpec::TST_decltype:
5611   case DeclSpec::TST_typeofExpr: {
5612     Expr *E = DS.getRepAsExpr();
5613     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5614     if (Result.isInvalid()) return true;
5615     DS.UpdateExprRep(Result.get());
5616     break;
5617   }
5618 
5619   default:
5620     // Nothing to do for these decl specs.
5621     break;
5622   }
5623 
5624   // It doesn't matter what order we do this in.
5625   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5626     DeclaratorChunk &Chunk = D.getTypeObject(I);
5627 
5628     // The only type information in the declarator which can come
5629     // before the declaration name is the base type of a member
5630     // pointer.
5631     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5632       continue;
5633 
5634     // Rebuild the scope specifier in-place.
5635     CXXScopeSpec &SS = Chunk.Mem.Scope();
5636     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5637       return true;
5638   }
5639 
5640   return false;
5641 }
5642 
5643 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5644   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5645   // of system decl.
5646   if (D->getPreviousDecl() || D->isImplicit())
5647     return;
5648   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5649   if (Status != ReservedIdentifierStatus::NotReserved &&
5650       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5651     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5652         << D << static_cast<int>(Status);
5653 }
5654 
5655 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5656   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5657   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5658 
5659   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5660       Dcl && Dcl->getDeclContext()->isFileContext())
5661     Dcl->setTopLevelDeclInObjCContainer();
5662 
5663   return Dcl;
5664 }
5665 
5666 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5667 ///   If T is the name of a class, then each of the following shall have a
5668 ///   name different from T:
5669 ///     - every static data member of class T;
5670 ///     - every member function of class T
5671 ///     - every member of class T that is itself a type;
5672 /// \returns true if the declaration name violates these rules.
5673 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5674                                    DeclarationNameInfo NameInfo) {
5675   DeclarationName Name = NameInfo.getName();
5676 
5677   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5678   while (Record && Record->isAnonymousStructOrUnion())
5679     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5680   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5681     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5682     return true;
5683   }
5684 
5685   return false;
5686 }
5687 
5688 /// Diagnose a declaration whose declarator-id has the given
5689 /// nested-name-specifier.
5690 ///
5691 /// \param SS The nested-name-specifier of the declarator-id.
5692 ///
5693 /// \param DC The declaration context to which the nested-name-specifier
5694 /// resolves.
5695 ///
5696 /// \param Name The name of the entity being declared.
5697 ///
5698 /// \param Loc The location of the name of the entity being declared.
5699 ///
5700 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5701 /// we're declaring an explicit / partial specialization / instantiation.
5702 ///
5703 /// \returns true if we cannot safely recover from this error, false otherwise.
5704 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5705                                         DeclarationName Name,
5706                                         SourceLocation Loc, bool IsTemplateId) {
5707   DeclContext *Cur = CurContext;
5708   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5709     Cur = Cur->getParent();
5710 
5711   // If the user provided a superfluous scope specifier that refers back to the
5712   // class in which the entity is already declared, diagnose and ignore it.
5713   //
5714   // class X {
5715   //   void X::f();
5716   // };
5717   //
5718   // Note, it was once ill-formed to give redundant qualification in all
5719   // contexts, but that rule was removed by DR482.
5720   if (Cur->Equals(DC)) {
5721     if (Cur->isRecord()) {
5722       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5723                                       : diag::err_member_extra_qualification)
5724         << Name << FixItHint::CreateRemoval(SS.getRange());
5725       SS.clear();
5726     } else {
5727       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5728     }
5729     return false;
5730   }
5731 
5732   // Check whether the qualifying scope encloses the scope of the original
5733   // declaration. For a template-id, we perform the checks in
5734   // CheckTemplateSpecializationScope.
5735   if (!Cur->Encloses(DC) && !IsTemplateId) {
5736     if (Cur->isRecord())
5737       Diag(Loc, diag::err_member_qualification)
5738         << Name << SS.getRange();
5739     else if (isa<TranslationUnitDecl>(DC))
5740       Diag(Loc, diag::err_invalid_declarator_global_scope)
5741         << Name << SS.getRange();
5742     else if (isa<FunctionDecl>(Cur))
5743       Diag(Loc, diag::err_invalid_declarator_in_function)
5744         << Name << SS.getRange();
5745     else if (isa<BlockDecl>(Cur))
5746       Diag(Loc, diag::err_invalid_declarator_in_block)
5747         << Name << SS.getRange();
5748     else
5749       Diag(Loc, diag::err_invalid_declarator_scope)
5750       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5751 
5752     return true;
5753   }
5754 
5755   if (Cur->isRecord()) {
5756     // Cannot qualify members within a class.
5757     Diag(Loc, diag::err_member_qualification)
5758       << Name << SS.getRange();
5759     SS.clear();
5760 
5761     // C++ constructors and destructors with incorrect scopes can break
5762     // our AST invariants by having the wrong underlying types. If
5763     // that's the case, then drop this declaration entirely.
5764     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5765          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5766         !Context.hasSameType(Name.getCXXNameType(),
5767                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5768       return true;
5769 
5770     return false;
5771   }
5772 
5773   // C++11 [dcl.meaning]p1:
5774   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5775   //   not begin with a decltype-specifer"
5776   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5777   while (SpecLoc.getPrefix())
5778     SpecLoc = SpecLoc.getPrefix();
5779   if (dyn_cast_or_null<DecltypeType>(
5780         SpecLoc.getNestedNameSpecifier()->getAsType()))
5781     Diag(Loc, diag::err_decltype_in_declarator)
5782       << SpecLoc.getTypeLoc().getSourceRange();
5783 
5784   return false;
5785 }
5786 
5787 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5788                                   MultiTemplateParamsArg TemplateParamLists) {
5789   // TODO: consider using NameInfo for diagnostic.
5790   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5791   DeclarationName Name = NameInfo.getName();
5792 
5793   // All of these full declarators require an identifier.  If it doesn't have
5794   // one, the ParsedFreeStandingDeclSpec action should be used.
5795   if (D.isDecompositionDeclarator()) {
5796     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5797   } else if (!Name) {
5798     if (!D.isInvalidType())  // Reject this if we think it is valid.
5799       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5800           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5801     return nullptr;
5802   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5803     return nullptr;
5804 
5805   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5806   // we find one that is.
5807   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5808          (S->getFlags() & Scope::TemplateParamScope) != 0)
5809     S = S->getParent();
5810 
5811   DeclContext *DC = CurContext;
5812   if (D.getCXXScopeSpec().isInvalid())
5813     D.setInvalidType();
5814   else if (D.getCXXScopeSpec().isSet()) {
5815     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5816                                         UPPC_DeclarationQualifier))
5817       return nullptr;
5818 
5819     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5820     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5821     if (!DC || isa<EnumDecl>(DC)) {
5822       // If we could not compute the declaration context, it's because the
5823       // declaration context is dependent but does not refer to a class,
5824       // class template, or class template partial specialization. Complain
5825       // and return early, to avoid the coming semantic disaster.
5826       Diag(D.getIdentifierLoc(),
5827            diag::err_template_qualified_declarator_no_match)
5828         << D.getCXXScopeSpec().getScopeRep()
5829         << D.getCXXScopeSpec().getRange();
5830       return nullptr;
5831     }
5832     bool IsDependentContext = DC->isDependentContext();
5833 
5834     if (!IsDependentContext &&
5835         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5836       return nullptr;
5837 
5838     // If a class is incomplete, do not parse entities inside it.
5839     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5840       Diag(D.getIdentifierLoc(),
5841            diag::err_member_def_undefined_record)
5842         << Name << DC << D.getCXXScopeSpec().getRange();
5843       return nullptr;
5844     }
5845     if (!D.getDeclSpec().isFriendSpecified()) {
5846       if (diagnoseQualifiedDeclaration(
5847               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5848               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5849         if (DC->isRecord())
5850           return nullptr;
5851 
5852         D.setInvalidType();
5853       }
5854     }
5855 
5856     // Check whether we need to rebuild the type of the given
5857     // declaration in the current instantiation.
5858     if (EnteringContext && IsDependentContext &&
5859         TemplateParamLists.size() != 0) {
5860       ContextRAII SavedContext(*this, DC);
5861       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5862         D.setInvalidType();
5863     }
5864   }
5865 
5866   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5867   QualType R = TInfo->getType();
5868 
5869   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5870                                       UPPC_DeclarationType))
5871     D.setInvalidType();
5872 
5873   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5874                         forRedeclarationInCurContext());
5875 
5876   // See if this is a redefinition of a variable in the same scope.
5877   if (!D.getCXXScopeSpec().isSet()) {
5878     bool IsLinkageLookup = false;
5879     bool CreateBuiltins = false;
5880 
5881     // If the declaration we're planning to build will be a function
5882     // or object with linkage, then look for another declaration with
5883     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5884     //
5885     // If the declaration we're planning to build will be declared with
5886     // external linkage in the translation unit, create any builtin with
5887     // the same name.
5888     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5889       /* Do nothing*/;
5890     else if (CurContext->isFunctionOrMethod() &&
5891              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5892               R->isFunctionType())) {
5893       IsLinkageLookup = true;
5894       CreateBuiltins =
5895           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5896     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5897                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5898       CreateBuiltins = true;
5899 
5900     if (IsLinkageLookup) {
5901       Previous.clear(LookupRedeclarationWithLinkage);
5902       Previous.setRedeclarationKind(ForExternalRedeclaration);
5903     }
5904 
5905     LookupName(Previous, S, CreateBuiltins);
5906   } else { // Something like "int foo::x;"
5907     LookupQualifiedName(Previous, DC);
5908 
5909     // C++ [dcl.meaning]p1:
5910     //   When the declarator-id is qualified, the declaration shall refer to a
5911     //  previously declared member of the class or namespace to which the
5912     //  qualifier refers (or, in the case of a namespace, of an element of the
5913     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5914     //  thereof; [...]
5915     //
5916     // Note that we already checked the context above, and that we do not have
5917     // enough information to make sure that Previous contains the declaration
5918     // we want to match. For example, given:
5919     //
5920     //   class X {
5921     //     void f();
5922     //     void f(float);
5923     //   };
5924     //
5925     //   void X::f(int) { } // ill-formed
5926     //
5927     // In this case, Previous will point to the overload set
5928     // containing the two f's declared in X, but neither of them
5929     // matches.
5930 
5931     // C++ [dcl.meaning]p1:
5932     //   [...] the member shall not merely have been introduced by a
5933     //   using-declaration in the scope of the class or namespace nominated by
5934     //   the nested-name-specifier of the declarator-id.
5935     RemoveUsingDecls(Previous);
5936   }
5937 
5938   if (Previous.isSingleResult() &&
5939       Previous.getFoundDecl()->isTemplateParameter()) {
5940     // Maybe we will complain about the shadowed template parameter.
5941     if (!D.isInvalidType())
5942       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5943                                       Previous.getFoundDecl());
5944 
5945     // Just pretend that we didn't see the previous declaration.
5946     Previous.clear();
5947   }
5948 
5949   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5950     // Forget that the previous declaration is the injected-class-name.
5951     Previous.clear();
5952 
5953   // In C++, the previous declaration we find might be a tag type
5954   // (class or enum). In this case, the new declaration will hide the
5955   // tag type. Note that this applies to functions, function templates, and
5956   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5957   if (Previous.isSingleTagDecl() &&
5958       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5959       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5960     Previous.clear();
5961 
5962   // Check that there are no default arguments other than in the parameters
5963   // of a function declaration (C++ only).
5964   if (getLangOpts().CPlusPlus)
5965     CheckExtraCXXDefaultArguments(D);
5966 
5967   NamedDecl *New;
5968 
5969   bool AddToScope = true;
5970   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5971     if (TemplateParamLists.size()) {
5972       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5973       return nullptr;
5974     }
5975 
5976     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5977   } else if (R->isFunctionType()) {
5978     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5979                                   TemplateParamLists,
5980                                   AddToScope);
5981   } else {
5982     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5983                                   AddToScope);
5984   }
5985 
5986   if (!New)
5987     return nullptr;
5988 
5989   // If this has an identifier and is not a function template specialization,
5990   // add it to the scope stack.
5991   if (New->getDeclName() && AddToScope)
5992     PushOnScopeChains(New, S);
5993 
5994   if (isInOpenMPDeclareTargetContext())
5995     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5996 
5997   return New;
5998 }
5999 
6000 /// Helper method to turn variable array types into constant array
6001 /// types in certain situations which would otherwise be errors (for
6002 /// GCC compatibility).
6003 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6004                                                     ASTContext &Context,
6005                                                     bool &SizeIsNegative,
6006                                                     llvm::APSInt &Oversized) {
6007   // This method tries to turn a variable array into a constant
6008   // array even when the size isn't an ICE.  This is necessary
6009   // for compatibility with code that depends on gcc's buggy
6010   // constant expression folding, like struct {char x[(int)(char*)2];}
6011   SizeIsNegative = false;
6012   Oversized = 0;
6013 
6014   if (T->isDependentType())
6015     return QualType();
6016 
6017   QualifierCollector Qs;
6018   const Type *Ty = Qs.strip(T);
6019 
6020   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6021     QualType Pointee = PTy->getPointeeType();
6022     QualType FixedType =
6023         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6024                                             Oversized);
6025     if (FixedType.isNull()) return FixedType;
6026     FixedType = Context.getPointerType(FixedType);
6027     return Qs.apply(Context, FixedType);
6028   }
6029   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6030     QualType Inner = PTy->getInnerType();
6031     QualType FixedType =
6032         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6033                                             Oversized);
6034     if (FixedType.isNull()) return FixedType;
6035     FixedType = Context.getParenType(FixedType);
6036     return Qs.apply(Context, FixedType);
6037   }
6038 
6039   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6040   if (!VLATy)
6041     return QualType();
6042 
6043   QualType ElemTy = VLATy->getElementType();
6044   if (ElemTy->isVariablyModifiedType()) {
6045     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6046                                                  SizeIsNegative, Oversized);
6047     if (ElemTy.isNull())
6048       return QualType();
6049   }
6050 
6051   Expr::EvalResult Result;
6052   if (!VLATy->getSizeExpr() ||
6053       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6054     return QualType();
6055 
6056   llvm::APSInt Res = Result.Val.getInt();
6057 
6058   // Check whether the array size is negative.
6059   if (Res.isSigned() && Res.isNegative()) {
6060     SizeIsNegative = true;
6061     return QualType();
6062   }
6063 
6064   // Check whether the array is too large to be addressed.
6065   unsigned ActiveSizeBits =
6066       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6067        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6068           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6069           : Res.getActiveBits();
6070   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6071     Oversized = Res;
6072     return QualType();
6073   }
6074 
6075   QualType FoldedArrayType = Context.getConstantArrayType(
6076       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6077   return Qs.apply(Context, FoldedArrayType);
6078 }
6079 
6080 static void
6081 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6082   SrcTL = SrcTL.getUnqualifiedLoc();
6083   DstTL = DstTL.getUnqualifiedLoc();
6084   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6085     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6086     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6087                                       DstPTL.getPointeeLoc());
6088     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6089     return;
6090   }
6091   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6092     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6093     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6094                                       DstPTL.getInnerLoc());
6095     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6096     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6097     return;
6098   }
6099   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6100   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6101   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6102   TypeLoc DstElemTL = DstATL.getElementLoc();
6103   if (VariableArrayTypeLoc SrcElemATL =
6104           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6105     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6106     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6107   } else {
6108     DstElemTL.initializeFullCopy(SrcElemTL);
6109   }
6110   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6111   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6112   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6113 }
6114 
6115 /// Helper method to turn variable array types into constant array
6116 /// types in certain situations which would otherwise be errors (for
6117 /// GCC compatibility).
6118 static TypeSourceInfo*
6119 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6120                                               ASTContext &Context,
6121                                               bool &SizeIsNegative,
6122                                               llvm::APSInt &Oversized) {
6123   QualType FixedTy
6124     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6125                                           SizeIsNegative, Oversized);
6126   if (FixedTy.isNull())
6127     return nullptr;
6128   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6129   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6130                                     FixedTInfo->getTypeLoc());
6131   return FixedTInfo;
6132 }
6133 
6134 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6135 /// true if we were successful.
6136 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6137                                            QualType &T, SourceLocation Loc,
6138                                            unsigned FailedFoldDiagID) {
6139   bool SizeIsNegative;
6140   llvm::APSInt Oversized;
6141   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6142       TInfo, Context, SizeIsNegative, Oversized);
6143   if (FixedTInfo) {
6144     Diag(Loc, diag::ext_vla_folded_to_constant);
6145     TInfo = FixedTInfo;
6146     T = FixedTInfo->getType();
6147     return true;
6148   }
6149 
6150   if (SizeIsNegative)
6151     Diag(Loc, diag::err_typecheck_negative_array_size);
6152   else if (Oversized.getBoolValue())
6153     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6154   else if (FailedFoldDiagID)
6155     Diag(Loc, FailedFoldDiagID);
6156   return false;
6157 }
6158 
6159 /// Register the given locally-scoped extern "C" declaration so
6160 /// that it can be found later for redeclarations. We include any extern "C"
6161 /// declaration that is not visible in the translation unit here, not just
6162 /// function-scope declarations.
6163 void
6164 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6165   if (!getLangOpts().CPlusPlus &&
6166       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6167     // Don't need to track declarations in the TU in C.
6168     return;
6169 
6170   // Note that we have a locally-scoped external with this name.
6171   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6172 }
6173 
6174 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6175   // FIXME: We can have multiple results via __attribute__((overloadable)).
6176   auto Result = Context.getExternCContextDecl()->lookup(Name);
6177   return Result.empty() ? nullptr : *Result.begin();
6178 }
6179 
6180 /// Diagnose function specifiers on a declaration of an identifier that
6181 /// does not identify a function.
6182 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6183   // FIXME: We should probably indicate the identifier in question to avoid
6184   // confusion for constructs like "virtual int a(), b;"
6185   if (DS.isVirtualSpecified())
6186     Diag(DS.getVirtualSpecLoc(),
6187          diag::err_virtual_non_function);
6188 
6189   if (DS.hasExplicitSpecifier())
6190     Diag(DS.getExplicitSpecLoc(),
6191          diag::err_explicit_non_function);
6192 
6193   if (DS.isNoreturnSpecified())
6194     Diag(DS.getNoreturnSpecLoc(),
6195          diag::err_noreturn_non_function);
6196 }
6197 
6198 NamedDecl*
6199 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6200                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6201   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6202   if (D.getCXXScopeSpec().isSet()) {
6203     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6204       << D.getCXXScopeSpec().getRange();
6205     D.setInvalidType();
6206     // Pretend we didn't see the scope specifier.
6207     DC = CurContext;
6208     Previous.clear();
6209   }
6210 
6211   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6212 
6213   if (D.getDeclSpec().isInlineSpecified())
6214     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6215         << getLangOpts().CPlusPlus17;
6216   if (D.getDeclSpec().hasConstexprSpecifier())
6217     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6218         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6219 
6220   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6221     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6222       Diag(D.getName().StartLocation,
6223            diag::err_deduction_guide_invalid_specifier)
6224           << "typedef";
6225     else
6226       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6227           << D.getName().getSourceRange();
6228     return nullptr;
6229   }
6230 
6231   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6232   if (!NewTD) return nullptr;
6233 
6234   // Handle attributes prior to checking for duplicates in MergeVarDecl
6235   ProcessDeclAttributes(S, NewTD, D);
6236 
6237   CheckTypedefForVariablyModifiedType(S, NewTD);
6238 
6239   bool Redeclaration = D.isRedeclaration();
6240   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6241   D.setRedeclaration(Redeclaration);
6242   return ND;
6243 }
6244 
6245 void
6246 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6247   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6248   // then it shall have block scope.
6249   // Note that variably modified types must be fixed before merging the decl so
6250   // that redeclarations will match.
6251   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6252   QualType T = TInfo->getType();
6253   if (T->isVariablyModifiedType()) {
6254     setFunctionHasBranchProtectedScope();
6255 
6256     if (S->getFnParent() == nullptr) {
6257       bool SizeIsNegative;
6258       llvm::APSInt Oversized;
6259       TypeSourceInfo *FixedTInfo =
6260         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6261                                                       SizeIsNegative,
6262                                                       Oversized);
6263       if (FixedTInfo) {
6264         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6265         NewTD->setTypeSourceInfo(FixedTInfo);
6266       } else {
6267         if (SizeIsNegative)
6268           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6269         else if (T->isVariableArrayType())
6270           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6271         else if (Oversized.getBoolValue())
6272           Diag(NewTD->getLocation(), diag::err_array_too_large)
6273             << toString(Oversized, 10);
6274         else
6275           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6276         NewTD->setInvalidDecl();
6277       }
6278     }
6279   }
6280 }
6281 
6282 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6283 /// declares a typedef-name, either using the 'typedef' type specifier or via
6284 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6285 NamedDecl*
6286 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6287                            LookupResult &Previous, bool &Redeclaration) {
6288 
6289   // Find the shadowed declaration before filtering for scope.
6290   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6291 
6292   // Merge the decl with the existing one if appropriate. If the decl is
6293   // in an outer scope, it isn't the same thing.
6294   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6295                        /*AllowInlineNamespace*/false);
6296   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6297   if (!Previous.empty()) {
6298     Redeclaration = true;
6299     MergeTypedefNameDecl(S, NewTD, Previous);
6300   } else {
6301     inferGslPointerAttribute(NewTD);
6302   }
6303 
6304   if (ShadowedDecl && !Redeclaration)
6305     CheckShadow(NewTD, ShadowedDecl, Previous);
6306 
6307   // If this is the C FILE type, notify the AST context.
6308   if (IdentifierInfo *II = NewTD->getIdentifier())
6309     if (!NewTD->isInvalidDecl() &&
6310         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6311       if (II->isStr("FILE"))
6312         Context.setFILEDecl(NewTD);
6313       else if (II->isStr("jmp_buf"))
6314         Context.setjmp_bufDecl(NewTD);
6315       else if (II->isStr("sigjmp_buf"))
6316         Context.setsigjmp_bufDecl(NewTD);
6317       else if (II->isStr("ucontext_t"))
6318         Context.setucontext_tDecl(NewTD);
6319     }
6320 
6321   return NewTD;
6322 }
6323 
6324 /// Determines whether the given declaration is an out-of-scope
6325 /// previous declaration.
6326 ///
6327 /// This routine should be invoked when name lookup has found a
6328 /// previous declaration (PrevDecl) that is not in the scope where a
6329 /// new declaration by the same name is being introduced. If the new
6330 /// declaration occurs in a local scope, previous declarations with
6331 /// linkage may still be considered previous declarations (C99
6332 /// 6.2.2p4-5, C++ [basic.link]p6).
6333 ///
6334 /// \param PrevDecl the previous declaration found by name
6335 /// lookup
6336 ///
6337 /// \param DC the context in which the new declaration is being
6338 /// declared.
6339 ///
6340 /// \returns true if PrevDecl is an out-of-scope previous declaration
6341 /// for a new delcaration with the same name.
6342 static bool
6343 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6344                                 ASTContext &Context) {
6345   if (!PrevDecl)
6346     return false;
6347 
6348   if (!PrevDecl->hasLinkage())
6349     return false;
6350 
6351   if (Context.getLangOpts().CPlusPlus) {
6352     // C++ [basic.link]p6:
6353     //   If there is a visible declaration of an entity with linkage
6354     //   having the same name and type, ignoring entities declared
6355     //   outside the innermost enclosing namespace scope, the block
6356     //   scope declaration declares that same entity and receives the
6357     //   linkage of the previous declaration.
6358     DeclContext *OuterContext = DC->getRedeclContext();
6359     if (!OuterContext->isFunctionOrMethod())
6360       // This rule only applies to block-scope declarations.
6361       return false;
6362 
6363     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6364     if (PrevOuterContext->isRecord())
6365       // We found a member function: ignore it.
6366       return false;
6367 
6368     // Find the innermost enclosing namespace for the new and
6369     // previous declarations.
6370     OuterContext = OuterContext->getEnclosingNamespaceContext();
6371     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6372 
6373     // The previous declaration is in a different namespace, so it
6374     // isn't the same function.
6375     if (!OuterContext->Equals(PrevOuterContext))
6376       return false;
6377   }
6378 
6379   return true;
6380 }
6381 
6382 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6383   CXXScopeSpec &SS = D.getCXXScopeSpec();
6384   if (!SS.isSet()) return;
6385   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6386 }
6387 
6388 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6389   QualType type = decl->getType();
6390   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6391   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6392     // Various kinds of declaration aren't allowed to be __autoreleasing.
6393     unsigned kind = -1U;
6394     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6395       if (var->hasAttr<BlocksAttr>())
6396         kind = 0; // __block
6397       else if (!var->hasLocalStorage())
6398         kind = 1; // global
6399     } else if (isa<ObjCIvarDecl>(decl)) {
6400       kind = 3; // ivar
6401     } else if (isa<FieldDecl>(decl)) {
6402       kind = 2; // field
6403     }
6404 
6405     if (kind != -1U) {
6406       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6407         << kind;
6408     }
6409   } else if (lifetime == Qualifiers::OCL_None) {
6410     // Try to infer lifetime.
6411     if (!type->isObjCLifetimeType())
6412       return false;
6413 
6414     lifetime = type->getObjCARCImplicitLifetime();
6415     type = Context.getLifetimeQualifiedType(type, lifetime);
6416     decl->setType(type);
6417   }
6418 
6419   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6420     // Thread-local variables cannot have lifetime.
6421     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6422         var->getTLSKind()) {
6423       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6424         << var->getType();
6425       return true;
6426     }
6427   }
6428 
6429   return false;
6430 }
6431 
6432 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6433   if (Decl->getType().hasAddressSpace())
6434     return;
6435   if (Decl->getType()->isDependentType())
6436     return;
6437   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6438     QualType Type = Var->getType();
6439     if (Type->isSamplerT() || Type->isVoidType())
6440       return;
6441     LangAS ImplAS = LangAS::opencl_private;
6442     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6443     // __opencl_c_program_scope_global_variables feature, the address space
6444     // for a variable at program scope or a static or extern variable inside
6445     // a function are inferred to be __global.
6446     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6447         Var->hasGlobalStorage())
6448       ImplAS = LangAS::opencl_global;
6449     // If the original type from a decayed type is an array type and that array
6450     // type has no address space yet, deduce it now.
6451     if (auto DT = dyn_cast<DecayedType>(Type)) {
6452       auto OrigTy = DT->getOriginalType();
6453       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6454         // Add the address space to the original array type and then propagate
6455         // that to the element type through `getAsArrayType`.
6456         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6457         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6458         // Re-generate the decayed type.
6459         Type = Context.getDecayedType(OrigTy);
6460       }
6461     }
6462     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6463     // Apply any qualifiers (including address space) from the array type to
6464     // the element type. This implements C99 6.7.3p8: "If the specification of
6465     // an array type includes any type qualifiers, the element type is so
6466     // qualified, not the array type."
6467     if (Type->isArrayType())
6468       Type = QualType(Context.getAsArrayType(Type), 0);
6469     Decl->setType(Type);
6470   }
6471 }
6472 
6473 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6474   // Ensure that an auto decl is deduced otherwise the checks below might cache
6475   // the wrong linkage.
6476   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6477 
6478   // 'weak' only applies to declarations with external linkage.
6479   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6480     if (!ND.isExternallyVisible()) {
6481       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6482       ND.dropAttr<WeakAttr>();
6483     }
6484   }
6485   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6486     if (ND.isExternallyVisible()) {
6487       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6488       ND.dropAttr<WeakRefAttr>();
6489       ND.dropAttr<AliasAttr>();
6490     }
6491   }
6492 
6493   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6494     if (VD->hasInit()) {
6495       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6496         assert(VD->isThisDeclarationADefinition() &&
6497                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6498         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6499         VD->dropAttr<AliasAttr>();
6500       }
6501     }
6502   }
6503 
6504   // 'selectany' only applies to externally visible variable declarations.
6505   // It does not apply to functions.
6506   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6507     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6508       S.Diag(Attr->getLocation(),
6509              diag::err_attribute_selectany_non_extern_data);
6510       ND.dropAttr<SelectAnyAttr>();
6511     }
6512   }
6513 
6514   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6515     auto *VD = dyn_cast<VarDecl>(&ND);
6516     bool IsAnonymousNS = false;
6517     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6518     if (VD) {
6519       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6520       while (NS && !IsAnonymousNS) {
6521         IsAnonymousNS = NS->isAnonymousNamespace();
6522         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6523       }
6524     }
6525     // dll attributes require external linkage. Static locals may have external
6526     // linkage but still cannot be explicitly imported or exported.
6527     // In Microsoft mode, a variable defined in anonymous namespace must have
6528     // external linkage in order to be exported.
6529     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6530     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6531         (!AnonNSInMicrosoftMode &&
6532          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6533       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6534         << &ND << Attr;
6535       ND.setInvalidDecl();
6536     }
6537   }
6538 
6539   // Check the attributes on the function type, if any.
6540   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6541     // Don't declare this variable in the second operand of the for-statement;
6542     // GCC miscompiles that by ending its lifetime before evaluating the
6543     // third operand. See gcc.gnu.org/PR86769.
6544     AttributedTypeLoc ATL;
6545     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6546          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6547          TL = ATL.getModifiedLoc()) {
6548       // The [[lifetimebound]] attribute can be applied to the implicit object
6549       // parameter of a non-static member function (other than a ctor or dtor)
6550       // by applying it to the function type.
6551       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6552         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6553         if (!MD || MD->isStatic()) {
6554           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6555               << !MD << A->getRange();
6556         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6557           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6558               << isa<CXXDestructorDecl>(MD) << A->getRange();
6559         }
6560       }
6561     }
6562   }
6563 }
6564 
6565 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6566                                            NamedDecl *NewDecl,
6567                                            bool IsSpecialization,
6568                                            bool IsDefinition) {
6569   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6570     return;
6571 
6572   bool IsTemplate = false;
6573   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6574     OldDecl = OldTD->getTemplatedDecl();
6575     IsTemplate = true;
6576     if (!IsSpecialization)
6577       IsDefinition = false;
6578   }
6579   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6580     NewDecl = NewTD->getTemplatedDecl();
6581     IsTemplate = true;
6582   }
6583 
6584   if (!OldDecl || !NewDecl)
6585     return;
6586 
6587   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6588   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6589   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6590   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6591 
6592   // dllimport and dllexport are inheritable attributes so we have to exclude
6593   // inherited attribute instances.
6594   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6595                     (NewExportAttr && !NewExportAttr->isInherited());
6596 
6597   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6598   // the only exception being explicit specializations.
6599   // Implicitly generated declarations are also excluded for now because there
6600   // is no other way to switch these to use dllimport or dllexport.
6601   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6602 
6603   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6604     // Allow with a warning for free functions and global variables.
6605     bool JustWarn = false;
6606     if (!OldDecl->isCXXClassMember()) {
6607       auto *VD = dyn_cast<VarDecl>(OldDecl);
6608       if (VD && !VD->getDescribedVarTemplate())
6609         JustWarn = true;
6610       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6611       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6612         JustWarn = true;
6613     }
6614 
6615     // We cannot change a declaration that's been used because IR has already
6616     // been emitted. Dllimported functions will still work though (modulo
6617     // address equality) as they can use the thunk.
6618     if (OldDecl->isUsed())
6619       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6620         JustWarn = false;
6621 
6622     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6623                                : diag::err_attribute_dll_redeclaration;
6624     S.Diag(NewDecl->getLocation(), DiagID)
6625         << NewDecl
6626         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6627     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6628     if (!JustWarn) {
6629       NewDecl->setInvalidDecl();
6630       return;
6631     }
6632   }
6633 
6634   // A redeclaration is not allowed to drop a dllimport attribute, the only
6635   // exceptions being inline function definitions (except for function
6636   // templates), local extern declarations, qualified friend declarations or
6637   // special MSVC extension: in the last case, the declaration is treated as if
6638   // it were marked dllexport.
6639   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6640   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6641   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6642     // Ignore static data because out-of-line definitions are diagnosed
6643     // separately.
6644     IsStaticDataMember = VD->isStaticDataMember();
6645     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6646                    VarDecl::DeclarationOnly;
6647   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6648     IsInline = FD->isInlined();
6649     IsQualifiedFriend = FD->getQualifier() &&
6650                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6651   }
6652 
6653   if (OldImportAttr && !HasNewAttr &&
6654       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6655       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6656     if (IsMicrosoftABI && IsDefinition) {
6657       S.Diag(NewDecl->getLocation(),
6658              diag::warn_redeclaration_without_import_attribute)
6659           << NewDecl;
6660       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6661       NewDecl->dropAttr<DLLImportAttr>();
6662       NewDecl->addAttr(
6663           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6664     } else {
6665       S.Diag(NewDecl->getLocation(),
6666              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6667           << NewDecl << OldImportAttr;
6668       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6669       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6670       OldDecl->dropAttr<DLLImportAttr>();
6671       NewDecl->dropAttr<DLLImportAttr>();
6672     }
6673   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6674     // In MinGW, seeing a function declared inline drops the dllimport
6675     // attribute.
6676     OldDecl->dropAttr<DLLImportAttr>();
6677     NewDecl->dropAttr<DLLImportAttr>();
6678     S.Diag(NewDecl->getLocation(),
6679            diag::warn_dllimport_dropped_from_inline_function)
6680         << NewDecl << OldImportAttr;
6681   }
6682 
6683   // A specialization of a class template member function is processed here
6684   // since it's a redeclaration. If the parent class is dllexport, the
6685   // specialization inherits that attribute. This doesn't happen automatically
6686   // since the parent class isn't instantiated until later.
6687   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6688     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6689         !NewImportAttr && !NewExportAttr) {
6690       if (const DLLExportAttr *ParentExportAttr =
6691               MD->getParent()->getAttr<DLLExportAttr>()) {
6692         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6693         NewAttr->setInherited(true);
6694         NewDecl->addAttr(NewAttr);
6695       }
6696     }
6697   }
6698 }
6699 
6700 /// Given that we are within the definition of the given function,
6701 /// will that definition behave like C99's 'inline', where the
6702 /// definition is discarded except for optimization purposes?
6703 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6704   // Try to avoid calling GetGVALinkageForFunction.
6705 
6706   // All cases of this require the 'inline' keyword.
6707   if (!FD->isInlined()) return false;
6708 
6709   // This is only possible in C++ with the gnu_inline attribute.
6710   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6711     return false;
6712 
6713   // Okay, go ahead and call the relatively-more-expensive function.
6714   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6715 }
6716 
6717 /// Determine whether a variable is extern "C" prior to attaching
6718 /// an initializer. We can't just call isExternC() here, because that
6719 /// will also compute and cache whether the declaration is externally
6720 /// visible, which might change when we attach the initializer.
6721 ///
6722 /// This can only be used if the declaration is known to not be a
6723 /// redeclaration of an internal linkage declaration.
6724 ///
6725 /// For instance:
6726 ///
6727 ///   auto x = []{};
6728 ///
6729 /// Attaching the initializer here makes this declaration not externally
6730 /// visible, because its type has internal linkage.
6731 ///
6732 /// FIXME: This is a hack.
6733 template<typename T>
6734 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6735   if (S.getLangOpts().CPlusPlus) {
6736     // In C++, the overloadable attribute negates the effects of extern "C".
6737     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6738       return false;
6739 
6740     // So do CUDA's host/device attributes.
6741     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6742                                  D->template hasAttr<CUDAHostAttr>()))
6743       return false;
6744   }
6745   return D->isExternC();
6746 }
6747 
6748 static bool shouldConsiderLinkage(const VarDecl *VD) {
6749   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6750   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6751       isa<OMPDeclareMapperDecl>(DC))
6752     return VD->hasExternalStorage();
6753   if (DC->isFileContext())
6754     return true;
6755   if (DC->isRecord())
6756     return false;
6757   if (isa<RequiresExprBodyDecl>(DC))
6758     return false;
6759   llvm_unreachable("Unexpected context");
6760 }
6761 
6762 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6763   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6764   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6765       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6766     return true;
6767   if (DC->isRecord())
6768     return false;
6769   llvm_unreachable("Unexpected context");
6770 }
6771 
6772 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6773                           ParsedAttr::Kind Kind) {
6774   // Check decl attributes on the DeclSpec.
6775   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6776     return true;
6777 
6778   // Walk the declarator structure, checking decl attributes that were in a type
6779   // position to the decl itself.
6780   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6781     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6782       return true;
6783   }
6784 
6785   // Finally, check attributes on the decl itself.
6786   return PD.getAttributes().hasAttribute(Kind);
6787 }
6788 
6789 /// Adjust the \c DeclContext for a function or variable that might be a
6790 /// function-local external declaration.
6791 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6792   if (!DC->isFunctionOrMethod())
6793     return false;
6794 
6795   // If this is a local extern function or variable declared within a function
6796   // template, don't add it into the enclosing namespace scope until it is
6797   // instantiated; it might have a dependent type right now.
6798   if (DC->isDependentContext())
6799     return true;
6800 
6801   // C++11 [basic.link]p7:
6802   //   When a block scope declaration of an entity with linkage is not found to
6803   //   refer to some other declaration, then that entity is a member of the
6804   //   innermost enclosing namespace.
6805   //
6806   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6807   // semantically-enclosing namespace, not a lexically-enclosing one.
6808   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6809     DC = DC->getParent();
6810   return true;
6811 }
6812 
6813 /// Returns true if given declaration has external C language linkage.
6814 static bool isDeclExternC(const Decl *D) {
6815   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6816     return FD->isExternC();
6817   if (const auto *VD = dyn_cast<VarDecl>(D))
6818     return VD->isExternC();
6819 
6820   llvm_unreachable("Unknown type of decl!");
6821 }
6822 
6823 /// Returns true if there hasn't been any invalid type diagnosed.
6824 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6825   DeclContext *DC = NewVD->getDeclContext();
6826   QualType R = NewVD->getType();
6827 
6828   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6829   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6830   // argument.
6831   if (R->isImageType() || R->isPipeType()) {
6832     Se.Diag(NewVD->getLocation(),
6833             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6834         << R;
6835     NewVD->setInvalidDecl();
6836     return false;
6837   }
6838 
6839   // OpenCL v1.2 s6.9.r:
6840   // The event type cannot be used to declare a program scope variable.
6841   // OpenCL v2.0 s6.9.q:
6842   // The clk_event_t and reserve_id_t types cannot be declared in program
6843   // scope.
6844   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6845     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6846       Se.Diag(NewVD->getLocation(),
6847               diag::err_invalid_type_for_program_scope_var)
6848           << R;
6849       NewVD->setInvalidDecl();
6850       return false;
6851     }
6852   }
6853 
6854   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6855   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6856                                                Se.getLangOpts())) {
6857     QualType NR = R.getCanonicalType();
6858     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6859            NR->isReferenceType()) {
6860       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6861           NR->isFunctionReferenceType()) {
6862         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6863             << NR->isReferenceType();
6864         NewVD->setInvalidDecl();
6865         return false;
6866       }
6867       NR = NR->getPointeeType();
6868     }
6869   }
6870 
6871   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6872                                                Se.getLangOpts())) {
6873     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6874     // half array type (unless the cl_khr_fp16 extension is enabled).
6875     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6876       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6877       NewVD->setInvalidDecl();
6878       return false;
6879     }
6880   }
6881 
6882   // OpenCL v1.2 s6.9.r:
6883   // The event type cannot be used with the __local, __constant and __global
6884   // address space qualifiers.
6885   if (R->isEventT()) {
6886     if (R.getAddressSpace() != LangAS::opencl_private) {
6887       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6888       NewVD->setInvalidDecl();
6889       return false;
6890     }
6891   }
6892 
6893   if (R->isSamplerT()) {
6894     // OpenCL v1.2 s6.9.b p4:
6895     // The sampler type cannot be used with the __local and __global address
6896     // space qualifiers.
6897     if (R.getAddressSpace() == LangAS::opencl_local ||
6898         R.getAddressSpace() == LangAS::opencl_global) {
6899       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6900       NewVD->setInvalidDecl();
6901     }
6902 
6903     // OpenCL v1.2 s6.12.14.1:
6904     // A global sampler must be declared with either the constant address
6905     // space qualifier or with the const qualifier.
6906     if (DC->isTranslationUnit() &&
6907         !(R.getAddressSpace() == LangAS::opencl_constant ||
6908           R.isConstQualified())) {
6909       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6910       NewVD->setInvalidDecl();
6911     }
6912     if (NewVD->isInvalidDecl())
6913       return false;
6914   }
6915 
6916   return true;
6917 }
6918 
6919 template <typename AttrTy>
6920 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6921   const TypedefNameDecl *TND = TT->getDecl();
6922   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6923     AttrTy *Clone = Attribute->clone(S.Context);
6924     Clone->setInherited(true);
6925     D->addAttr(Clone);
6926   }
6927 }
6928 
6929 NamedDecl *Sema::ActOnVariableDeclarator(
6930     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6931     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6932     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6933   QualType R = TInfo->getType();
6934   DeclarationName Name = GetNameForDeclarator(D).getName();
6935 
6936   IdentifierInfo *II = Name.getAsIdentifierInfo();
6937 
6938   if (D.isDecompositionDeclarator()) {
6939     // Take the name of the first declarator as our name for diagnostic
6940     // purposes.
6941     auto &Decomp = D.getDecompositionDeclarator();
6942     if (!Decomp.bindings().empty()) {
6943       II = Decomp.bindings()[0].Name;
6944       Name = II;
6945     }
6946   } else if (!II) {
6947     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6948     return nullptr;
6949   }
6950 
6951 
6952   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6953   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6954 
6955   // dllimport globals without explicit storage class are treated as extern. We
6956   // have to change the storage class this early to get the right DeclContext.
6957   if (SC == SC_None && !DC->isRecord() &&
6958       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6959       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6960     SC = SC_Extern;
6961 
6962   DeclContext *OriginalDC = DC;
6963   bool IsLocalExternDecl = SC == SC_Extern &&
6964                            adjustContextForLocalExternDecl(DC);
6965 
6966   if (SCSpec == DeclSpec::SCS_mutable) {
6967     // mutable can only appear on non-static class members, so it's always
6968     // an error here
6969     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6970     D.setInvalidType();
6971     SC = SC_None;
6972   }
6973 
6974   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6975       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6976                               D.getDeclSpec().getStorageClassSpecLoc())) {
6977     // In C++11, the 'register' storage class specifier is deprecated.
6978     // Suppress the warning in system macros, it's used in macros in some
6979     // popular C system headers, such as in glibc's htonl() macro.
6980     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6981          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6982                                    : diag::warn_deprecated_register)
6983       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6984   }
6985 
6986   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6987 
6988   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6989     // C99 6.9p2: The storage-class specifiers auto and register shall not
6990     // appear in the declaration specifiers in an external declaration.
6991     // Global Register+Asm is a GNU extension we support.
6992     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6993       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6994       D.setInvalidType();
6995     }
6996   }
6997 
6998   // If this variable has a VLA type and an initializer, try to
6999   // fold to a constant-sized type. This is otherwise invalid.
7000   if (D.hasInitializer() && R->isVariableArrayType())
7001     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7002                                     /*DiagID=*/0);
7003 
7004   bool IsMemberSpecialization = false;
7005   bool IsVariableTemplateSpecialization = false;
7006   bool IsPartialSpecialization = false;
7007   bool IsVariableTemplate = false;
7008   VarDecl *NewVD = nullptr;
7009   VarTemplateDecl *NewTemplate = nullptr;
7010   TemplateParameterList *TemplateParams = nullptr;
7011   if (!getLangOpts().CPlusPlus) {
7012     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7013                             II, R, TInfo, SC);
7014 
7015     if (R->getContainedDeducedType())
7016       ParsingInitForAutoVars.insert(NewVD);
7017 
7018     if (D.isInvalidType())
7019       NewVD->setInvalidDecl();
7020 
7021     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7022         NewVD->hasLocalStorage())
7023       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7024                             NTCUC_AutoVar, NTCUK_Destruct);
7025   } else {
7026     bool Invalid = false;
7027 
7028     if (DC->isRecord() && !CurContext->isRecord()) {
7029       // This is an out-of-line definition of a static data member.
7030       switch (SC) {
7031       case SC_None:
7032         break;
7033       case SC_Static:
7034         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7035              diag::err_static_out_of_line)
7036           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7037         break;
7038       case SC_Auto:
7039       case SC_Register:
7040       case SC_Extern:
7041         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7042         // to names of variables declared in a block or to function parameters.
7043         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7044         // of class members
7045 
7046         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7047              diag::err_storage_class_for_static_member)
7048           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7049         break;
7050       case SC_PrivateExtern:
7051         llvm_unreachable("C storage class in c++!");
7052       }
7053     }
7054 
7055     if (SC == SC_Static && CurContext->isRecord()) {
7056       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7057         // Walk up the enclosing DeclContexts to check for any that are
7058         // incompatible with static data members.
7059         const DeclContext *FunctionOrMethod = nullptr;
7060         const CXXRecordDecl *AnonStruct = nullptr;
7061         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7062           if (Ctxt->isFunctionOrMethod()) {
7063             FunctionOrMethod = Ctxt;
7064             break;
7065           }
7066           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7067           if (ParentDecl && !ParentDecl->getDeclName()) {
7068             AnonStruct = ParentDecl;
7069             break;
7070           }
7071         }
7072         if (FunctionOrMethod) {
7073           // C++ [class.static.data]p5: A local class shall not have static data
7074           // members.
7075           Diag(D.getIdentifierLoc(),
7076                diag::err_static_data_member_not_allowed_in_local_class)
7077             << Name << RD->getDeclName() << RD->getTagKind();
7078         } else if (AnonStruct) {
7079           // C++ [class.static.data]p4: Unnamed classes and classes contained
7080           // directly or indirectly within unnamed classes shall not contain
7081           // static data members.
7082           Diag(D.getIdentifierLoc(),
7083                diag::err_static_data_member_not_allowed_in_anon_struct)
7084             << Name << AnonStruct->getTagKind();
7085           Invalid = true;
7086         } else if (RD->isUnion()) {
7087           // C++98 [class.union]p1: If a union contains a static data member,
7088           // the program is ill-formed. C++11 drops this restriction.
7089           Diag(D.getIdentifierLoc(),
7090                getLangOpts().CPlusPlus11
7091                  ? diag::warn_cxx98_compat_static_data_member_in_union
7092                  : diag::ext_static_data_member_in_union) << Name;
7093         }
7094       }
7095     }
7096 
7097     // Match up the template parameter lists with the scope specifier, then
7098     // determine whether we have a template or a template specialization.
7099     bool InvalidScope = false;
7100     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7101         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7102         D.getCXXScopeSpec(),
7103         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7104             ? D.getName().TemplateId
7105             : nullptr,
7106         TemplateParamLists,
7107         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7108     Invalid |= InvalidScope;
7109 
7110     if (TemplateParams) {
7111       if (!TemplateParams->size() &&
7112           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7113         // There is an extraneous 'template<>' for this variable. Complain
7114         // about it, but allow the declaration of the variable.
7115         Diag(TemplateParams->getTemplateLoc(),
7116              diag::err_template_variable_noparams)
7117           << II
7118           << SourceRange(TemplateParams->getTemplateLoc(),
7119                          TemplateParams->getRAngleLoc());
7120         TemplateParams = nullptr;
7121       } else {
7122         // Check that we can declare a template here.
7123         if (CheckTemplateDeclScope(S, TemplateParams))
7124           return nullptr;
7125 
7126         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7127           // This is an explicit specialization or a partial specialization.
7128           IsVariableTemplateSpecialization = true;
7129           IsPartialSpecialization = TemplateParams->size() > 0;
7130         } else { // if (TemplateParams->size() > 0)
7131           // This is a template declaration.
7132           IsVariableTemplate = true;
7133 
7134           // Only C++1y supports variable templates (N3651).
7135           Diag(D.getIdentifierLoc(),
7136                getLangOpts().CPlusPlus14
7137                    ? diag::warn_cxx11_compat_variable_template
7138                    : diag::ext_variable_template);
7139         }
7140       }
7141     } else {
7142       // Check that we can declare a member specialization here.
7143       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7144           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7145         return nullptr;
7146       assert((Invalid ||
7147               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7148              "should have a 'template<>' for this decl");
7149     }
7150 
7151     if (IsVariableTemplateSpecialization) {
7152       SourceLocation TemplateKWLoc =
7153           TemplateParamLists.size() > 0
7154               ? TemplateParamLists[0]->getTemplateLoc()
7155               : SourceLocation();
7156       DeclResult Res = ActOnVarTemplateSpecialization(
7157           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7158           IsPartialSpecialization);
7159       if (Res.isInvalid())
7160         return nullptr;
7161       NewVD = cast<VarDecl>(Res.get());
7162       AddToScope = false;
7163     } else if (D.isDecompositionDeclarator()) {
7164       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7165                                         D.getIdentifierLoc(), R, TInfo, SC,
7166                                         Bindings);
7167     } else
7168       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7169                               D.getIdentifierLoc(), II, R, TInfo, SC);
7170 
7171     // If this is supposed to be a variable template, create it as such.
7172     if (IsVariableTemplate) {
7173       NewTemplate =
7174           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7175                                   TemplateParams, NewVD);
7176       NewVD->setDescribedVarTemplate(NewTemplate);
7177     }
7178 
7179     // If this decl has an auto type in need of deduction, make a note of the
7180     // Decl so we can diagnose uses of it in its own initializer.
7181     if (R->getContainedDeducedType())
7182       ParsingInitForAutoVars.insert(NewVD);
7183 
7184     if (D.isInvalidType() || Invalid) {
7185       NewVD->setInvalidDecl();
7186       if (NewTemplate)
7187         NewTemplate->setInvalidDecl();
7188     }
7189 
7190     SetNestedNameSpecifier(*this, NewVD, D);
7191 
7192     // If we have any template parameter lists that don't directly belong to
7193     // the variable (matching the scope specifier), store them.
7194     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7195     if (TemplateParamLists.size() > VDTemplateParamLists)
7196       NewVD->setTemplateParameterListsInfo(
7197           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7198   }
7199 
7200   if (D.getDeclSpec().isInlineSpecified()) {
7201     if (!getLangOpts().CPlusPlus) {
7202       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7203           << 0;
7204     } else if (CurContext->isFunctionOrMethod()) {
7205       // 'inline' is not allowed on block scope variable declaration.
7206       Diag(D.getDeclSpec().getInlineSpecLoc(),
7207            diag::err_inline_declaration_block_scope) << Name
7208         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7209     } else {
7210       Diag(D.getDeclSpec().getInlineSpecLoc(),
7211            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7212                                      : diag::ext_inline_variable);
7213       NewVD->setInlineSpecified();
7214     }
7215   }
7216 
7217   // Set the lexical context. If the declarator has a C++ scope specifier, the
7218   // lexical context will be different from the semantic context.
7219   NewVD->setLexicalDeclContext(CurContext);
7220   if (NewTemplate)
7221     NewTemplate->setLexicalDeclContext(CurContext);
7222 
7223   if (IsLocalExternDecl) {
7224     if (D.isDecompositionDeclarator())
7225       for (auto *B : Bindings)
7226         B->setLocalExternDecl();
7227     else
7228       NewVD->setLocalExternDecl();
7229   }
7230 
7231   bool EmitTLSUnsupportedError = false;
7232   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7233     // C++11 [dcl.stc]p4:
7234     //   When thread_local is applied to a variable of block scope the
7235     //   storage-class-specifier static is implied if it does not appear
7236     //   explicitly.
7237     // Core issue: 'static' is not implied if the variable is declared
7238     //   'extern'.
7239     if (NewVD->hasLocalStorage() &&
7240         (SCSpec != DeclSpec::SCS_unspecified ||
7241          TSCS != DeclSpec::TSCS_thread_local ||
7242          !DC->isFunctionOrMethod()))
7243       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7244            diag::err_thread_non_global)
7245         << DeclSpec::getSpecifierName(TSCS);
7246     else if (!Context.getTargetInfo().isTLSSupported()) {
7247       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7248           getLangOpts().SYCLIsDevice) {
7249         // Postpone error emission until we've collected attributes required to
7250         // figure out whether it's a host or device variable and whether the
7251         // error should be ignored.
7252         EmitTLSUnsupportedError = true;
7253         // We still need to mark the variable as TLS so it shows up in AST with
7254         // proper storage class for other tools to use even if we're not going
7255         // to emit any code for it.
7256         NewVD->setTSCSpec(TSCS);
7257       } else
7258         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7259              diag::err_thread_unsupported);
7260     } else
7261       NewVD->setTSCSpec(TSCS);
7262   }
7263 
7264   switch (D.getDeclSpec().getConstexprSpecifier()) {
7265   case ConstexprSpecKind::Unspecified:
7266     break;
7267 
7268   case ConstexprSpecKind::Consteval:
7269     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7270          diag::err_constexpr_wrong_decl_kind)
7271         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7272     LLVM_FALLTHROUGH;
7273 
7274   case ConstexprSpecKind::Constexpr:
7275     NewVD->setConstexpr(true);
7276     // C++1z [dcl.spec.constexpr]p1:
7277     //   A static data member declared with the constexpr specifier is
7278     //   implicitly an inline variable.
7279     if (NewVD->isStaticDataMember() &&
7280         (getLangOpts().CPlusPlus17 ||
7281          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7282       NewVD->setImplicitlyInline();
7283     break;
7284 
7285   case ConstexprSpecKind::Constinit:
7286     if (!NewVD->hasGlobalStorage())
7287       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7288            diag::err_constinit_local_variable);
7289     else
7290       NewVD->addAttr(ConstInitAttr::Create(
7291           Context, D.getDeclSpec().getConstexprSpecLoc(),
7292           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7293     break;
7294   }
7295 
7296   // C99 6.7.4p3
7297   //   An inline definition of a function with external linkage shall
7298   //   not contain a definition of a modifiable object with static or
7299   //   thread storage duration...
7300   // We only apply this when the function is required to be defined
7301   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7302   // that a local variable with thread storage duration still has to
7303   // be marked 'static'.  Also note that it's possible to get these
7304   // semantics in C++ using __attribute__((gnu_inline)).
7305   if (SC == SC_Static && S->getFnParent() != nullptr &&
7306       !NewVD->getType().isConstQualified()) {
7307     FunctionDecl *CurFD = getCurFunctionDecl();
7308     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7309       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7310            diag::warn_static_local_in_extern_inline);
7311       MaybeSuggestAddingStaticToDecl(CurFD);
7312     }
7313   }
7314 
7315   if (D.getDeclSpec().isModulePrivateSpecified()) {
7316     if (IsVariableTemplateSpecialization)
7317       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7318           << (IsPartialSpecialization ? 1 : 0)
7319           << FixItHint::CreateRemoval(
7320                  D.getDeclSpec().getModulePrivateSpecLoc());
7321     else if (IsMemberSpecialization)
7322       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7323         << 2
7324         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7325     else if (NewVD->hasLocalStorage())
7326       Diag(NewVD->getLocation(), diag::err_module_private_local)
7327           << 0 << NewVD
7328           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7329           << FixItHint::CreateRemoval(
7330                  D.getDeclSpec().getModulePrivateSpecLoc());
7331     else {
7332       NewVD->setModulePrivate();
7333       if (NewTemplate)
7334         NewTemplate->setModulePrivate();
7335       for (auto *B : Bindings)
7336         B->setModulePrivate();
7337     }
7338   }
7339 
7340   if (getLangOpts().OpenCL) {
7341     deduceOpenCLAddressSpace(NewVD);
7342 
7343     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7344     if (TSC != TSCS_unspecified) {
7345       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7346            diag::err_opencl_unknown_type_specifier)
7347           << getLangOpts().getOpenCLVersionString()
7348           << DeclSpec::getSpecifierName(TSC) << 1;
7349       NewVD->setInvalidDecl();
7350     }
7351   }
7352 
7353   // Handle attributes prior to checking for duplicates in MergeVarDecl
7354   ProcessDeclAttributes(S, NewVD, D);
7355 
7356   // FIXME: This is probably the wrong location to be doing this and we should
7357   // probably be doing this for more attributes (especially for function
7358   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7359   // the code to copy attributes would be generated by TableGen.
7360   if (R->isFunctionPointerType())
7361     if (const auto *TT = R->getAs<TypedefType>())
7362       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7363 
7364   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7365       getLangOpts().SYCLIsDevice) {
7366     if (EmitTLSUnsupportedError &&
7367         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7368          (getLangOpts().OpenMPIsDevice &&
7369           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7370       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7371            diag::err_thread_unsupported);
7372 
7373     if (EmitTLSUnsupportedError &&
7374         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7375       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7376     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7377     // storage [duration]."
7378     if (SC == SC_None && S->getFnParent() != nullptr &&
7379         (NewVD->hasAttr<CUDASharedAttr>() ||
7380          NewVD->hasAttr<CUDAConstantAttr>())) {
7381       NewVD->setStorageClass(SC_Static);
7382     }
7383   }
7384 
7385   // Ensure that dllimport globals without explicit storage class are treated as
7386   // extern. The storage class is set above using parsed attributes. Now we can
7387   // check the VarDecl itself.
7388   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7389          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7390          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7391 
7392   // In auto-retain/release, infer strong retension for variables of
7393   // retainable type.
7394   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7395     NewVD->setInvalidDecl();
7396 
7397   // Handle GNU asm-label extension (encoded as an attribute).
7398   if (Expr *E = (Expr*)D.getAsmLabel()) {
7399     // The parser guarantees this is a string.
7400     StringLiteral *SE = cast<StringLiteral>(E);
7401     StringRef Label = SE->getString();
7402     if (S->getFnParent() != nullptr) {
7403       switch (SC) {
7404       case SC_None:
7405       case SC_Auto:
7406         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7407         break;
7408       case SC_Register:
7409         // Local Named register
7410         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7411             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7412           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7413         break;
7414       case SC_Static:
7415       case SC_Extern:
7416       case SC_PrivateExtern:
7417         break;
7418       }
7419     } else if (SC == SC_Register) {
7420       // Global Named register
7421       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7422         const auto &TI = Context.getTargetInfo();
7423         bool HasSizeMismatch;
7424 
7425         if (!TI.isValidGCCRegisterName(Label))
7426           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7427         else if (!TI.validateGlobalRegisterVariable(Label,
7428                                                     Context.getTypeSize(R),
7429                                                     HasSizeMismatch))
7430           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7431         else if (HasSizeMismatch)
7432           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7433       }
7434 
7435       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7436         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7437         NewVD->setInvalidDecl(true);
7438       }
7439     }
7440 
7441     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7442                                         /*IsLiteralLabel=*/true,
7443                                         SE->getStrTokenLoc(0)));
7444   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7445     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7446       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7447     if (I != ExtnameUndeclaredIdentifiers.end()) {
7448       if (isDeclExternC(NewVD)) {
7449         NewVD->addAttr(I->second);
7450         ExtnameUndeclaredIdentifiers.erase(I);
7451       } else
7452         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7453             << /*Variable*/1 << NewVD;
7454     }
7455   }
7456 
7457   // Find the shadowed declaration before filtering for scope.
7458   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7459                                 ? getShadowedDeclaration(NewVD, Previous)
7460                                 : nullptr;
7461 
7462   // Don't consider existing declarations that are in a different
7463   // scope and are out-of-semantic-context declarations (if the new
7464   // declaration has linkage).
7465   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7466                        D.getCXXScopeSpec().isNotEmpty() ||
7467                        IsMemberSpecialization ||
7468                        IsVariableTemplateSpecialization);
7469 
7470   // Check whether the previous declaration is in the same block scope. This
7471   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7472   if (getLangOpts().CPlusPlus &&
7473       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7474     NewVD->setPreviousDeclInSameBlockScope(
7475         Previous.isSingleResult() && !Previous.isShadowed() &&
7476         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7477 
7478   if (!getLangOpts().CPlusPlus) {
7479     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7480   } else {
7481     // If this is an explicit specialization of a static data member, check it.
7482     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7483         CheckMemberSpecialization(NewVD, Previous))
7484       NewVD->setInvalidDecl();
7485 
7486     // Merge the decl with the existing one if appropriate.
7487     if (!Previous.empty()) {
7488       if (Previous.isSingleResult() &&
7489           isa<FieldDecl>(Previous.getFoundDecl()) &&
7490           D.getCXXScopeSpec().isSet()) {
7491         // The user tried to define a non-static data member
7492         // out-of-line (C++ [dcl.meaning]p1).
7493         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7494           << D.getCXXScopeSpec().getRange();
7495         Previous.clear();
7496         NewVD->setInvalidDecl();
7497       }
7498     } else if (D.getCXXScopeSpec().isSet()) {
7499       // No previous declaration in the qualifying scope.
7500       Diag(D.getIdentifierLoc(), diag::err_no_member)
7501         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7502         << D.getCXXScopeSpec().getRange();
7503       NewVD->setInvalidDecl();
7504     }
7505 
7506     if (!IsVariableTemplateSpecialization)
7507       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7508 
7509     if (NewTemplate) {
7510       VarTemplateDecl *PrevVarTemplate =
7511           NewVD->getPreviousDecl()
7512               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7513               : nullptr;
7514 
7515       // Check the template parameter list of this declaration, possibly
7516       // merging in the template parameter list from the previous variable
7517       // template declaration.
7518       if (CheckTemplateParameterList(
7519               TemplateParams,
7520               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7521                               : nullptr,
7522               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7523                DC->isDependentContext())
7524                   ? TPC_ClassTemplateMember
7525                   : TPC_VarTemplate))
7526         NewVD->setInvalidDecl();
7527 
7528       // If we are providing an explicit specialization of a static variable
7529       // template, make a note of that.
7530       if (PrevVarTemplate &&
7531           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7532         PrevVarTemplate->setMemberSpecialization();
7533     }
7534   }
7535 
7536   // Diagnose shadowed variables iff this isn't a redeclaration.
7537   if (ShadowedDecl && !D.isRedeclaration())
7538     CheckShadow(NewVD, ShadowedDecl, Previous);
7539 
7540   ProcessPragmaWeak(S, NewVD);
7541 
7542   // If this is the first declaration of an extern C variable, update
7543   // the map of such variables.
7544   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7545       isIncompleteDeclExternC(*this, NewVD))
7546     RegisterLocallyScopedExternCDecl(NewVD, S);
7547 
7548   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7549     MangleNumberingContext *MCtx;
7550     Decl *ManglingContextDecl;
7551     std::tie(MCtx, ManglingContextDecl) =
7552         getCurrentMangleNumberContext(NewVD->getDeclContext());
7553     if (MCtx) {
7554       Context.setManglingNumber(
7555           NewVD, MCtx->getManglingNumber(
7556                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7557       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7558     }
7559   }
7560 
7561   // Special handling of variable named 'main'.
7562   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7563       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7564       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7565 
7566     // C++ [basic.start.main]p3
7567     // A program that declares a variable main at global scope is ill-formed.
7568     if (getLangOpts().CPlusPlus)
7569       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7570 
7571     // In C, and external-linkage variable named main results in undefined
7572     // behavior.
7573     else if (NewVD->hasExternalFormalLinkage())
7574       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7575   }
7576 
7577   if (D.isRedeclaration() && !Previous.empty()) {
7578     NamedDecl *Prev = Previous.getRepresentativeDecl();
7579     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7580                                    D.isFunctionDefinition());
7581   }
7582 
7583   if (NewTemplate) {
7584     if (NewVD->isInvalidDecl())
7585       NewTemplate->setInvalidDecl();
7586     ActOnDocumentableDecl(NewTemplate);
7587     return NewTemplate;
7588   }
7589 
7590   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7591     CompleteMemberSpecialization(NewVD, Previous);
7592 
7593   return NewVD;
7594 }
7595 
7596 /// Enum describing the %select options in diag::warn_decl_shadow.
7597 enum ShadowedDeclKind {
7598   SDK_Local,
7599   SDK_Global,
7600   SDK_StaticMember,
7601   SDK_Field,
7602   SDK_Typedef,
7603   SDK_Using,
7604   SDK_StructuredBinding
7605 };
7606 
7607 /// Determine what kind of declaration we're shadowing.
7608 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7609                                                 const DeclContext *OldDC) {
7610   if (isa<TypeAliasDecl>(ShadowedDecl))
7611     return SDK_Using;
7612   else if (isa<TypedefDecl>(ShadowedDecl))
7613     return SDK_Typedef;
7614   else if (isa<BindingDecl>(ShadowedDecl))
7615     return SDK_StructuredBinding;
7616   else if (isa<RecordDecl>(OldDC))
7617     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7618 
7619   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7620 }
7621 
7622 /// Return the location of the capture if the given lambda captures the given
7623 /// variable \p VD, or an invalid source location otherwise.
7624 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7625                                          const VarDecl *VD) {
7626   for (const Capture &Capture : LSI->Captures) {
7627     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7628       return Capture.getLocation();
7629   }
7630   return SourceLocation();
7631 }
7632 
7633 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7634                                      const LookupResult &R) {
7635   // Only diagnose if we're shadowing an unambiguous field or variable.
7636   if (R.getResultKind() != LookupResult::Found)
7637     return false;
7638 
7639   // Return false if warning is ignored.
7640   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7641 }
7642 
7643 /// Return the declaration shadowed by the given variable \p D, or null
7644 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7645 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7646                                         const LookupResult &R) {
7647   if (!shouldWarnIfShadowedDecl(Diags, R))
7648     return nullptr;
7649 
7650   // Don't diagnose declarations at file scope.
7651   if (D->hasGlobalStorage())
7652     return nullptr;
7653 
7654   NamedDecl *ShadowedDecl = R.getFoundDecl();
7655   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7656                                                             : nullptr;
7657 }
7658 
7659 /// Return the declaration shadowed by the given typedef \p D, or null
7660 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7661 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7662                                         const LookupResult &R) {
7663   // Don't warn if typedef declaration is part of a class
7664   if (D->getDeclContext()->isRecord())
7665     return nullptr;
7666 
7667   if (!shouldWarnIfShadowedDecl(Diags, R))
7668     return nullptr;
7669 
7670   NamedDecl *ShadowedDecl = R.getFoundDecl();
7671   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7672 }
7673 
7674 /// Return the declaration shadowed by the given variable \p D, or null
7675 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7676 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7677                                         const LookupResult &R) {
7678   if (!shouldWarnIfShadowedDecl(Diags, R))
7679     return nullptr;
7680 
7681   NamedDecl *ShadowedDecl = R.getFoundDecl();
7682   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7683                                                             : nullptr;
7684 }
7685 
7686 /// Diagnose variable or built-in function shadowing.  Implements
7687 /// -Wshadow.
7688 ///
7689 /// This method is called whenever a VarDecl is added to a "useful"
7690 /// scope.
7691 ///
7692 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7693 /// \param R the lookup of the name
7694 ///
7695 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7696                        const LookupResult &R) {
7697   DeclContext *NewDC = D->getDeclContext();
7698 
7699   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7700     // Fields are not shadowed by variables in C++ static methods.
7701     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7702       if (MD->isStatic())
7703         return;
7704 
7705     // Fields shadowed by constructor parameters are a special case. Usually
7706     // the constructor initializes the field with the parameter.
7707     if (isa<CXXConstructorDecl>(NewDC))
7708       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7709         // Remember that this was shadowed so we can either warn about its
7710         // modification or its existence depending on warning settings.
7711         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7712         return;
7713       }
7714   }
7715 
7716   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7717     if (shadowedVar->isExternC()) {
7718       // For shadowing external vars, make sure that we point to the global
7719       // declaration, not a locally scoped extern declaration.
7720       for (auto I : shadowedVar->redecls())
7721         if (I->isFileVarDecl()) {
7722           ShadowedDecl = I;
7723           break;
7724         }
7725     }
7726 
7727   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7728 
7729   unsigned WarningDiag = diag::warn_decl_shadow;
7730   SourceLocation CaptureLoc;
7731   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7732       isa<CXXMethodDecl>(NewDC)) {
7733     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7734       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7735         if (RD->getLambdaCaptureDefault() == LCD_None) {
7736           // Try to avoid warnings for lambdas with an explicit capture list.
7737           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7738           // Warn only when the lambda captures the shadowed decl explicitly.
7739           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7740           if (CaptureLoc.isInvalid())
7741             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7742         } else {
7743           // Remember that this was shadowed so we can avoid the warning if the
7744           // shadowed decl isn't captured and the warning settings allow it.
7745           cast<LambdaScopeInfo>(getCurFunction())
7746               ->ShadowingDecls.push_back(
7747                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7748           return;
7749         }
7750       }
7751 
7752       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7753         // A variable can't shadow a local variable in an enclosing scope, if
7754         // they are separated by a non-capturing declaration context.
7755         for (DeclContext *ParentDC = NewDC;
7756              ParentDC && !ParentDC->Equals(OldDC);
7757              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7758           // Only block literals, captured statements, and lambda expressions
7759           // can capture; other scopes don't.
7760           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7761               !isLambdaCallOperator(ParentDC)) {
7762             return;
7763           }
7764         }
7765       }
7766     }
7767   }
7768 
7769   // Only warn about certain kinds of shadowing for class members.
7770   if (NewDC && NewDC->isRecord()) {
7771     // In particular, don't warn about shadowing non-class members.
7772     if (!OldDC->isRecord())
7773       return;
7774 
7775     // TODO: should we warn about static data members shadowing
7776     // static data members from base classes?
7777 
7778     // TODO: don't diagnose for inaccessible shadowed members.
7779     // This is hard to do perfectly because we might friend the
7780     // shadowing context, but that's just a false negative.
7781   }
7782 
7783 
7784   DeclarationName Name = R.getLookupName();
7785 
7786   // Emit warning and note.
7787   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7788     return;
7789   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7790   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7791   if (!CaptureLoc.isInvalid())
7792     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7793         << Name << /*explicitly*/ 1;
7794   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7795 }
7796 
7797 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7798 /// when these variables are captured by the lambda.
7799 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7800   for (const auto &Shadow : LSI->ShadowingDecls) {
7801     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7802     // Try to avoid the warning when the shadowed decl isn't captured.
7803     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7804     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7805     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7806                                        ? diag::warn_decl_shadow_uncaptured_local
7807                                        : diag::warn_decl_shadow)
7808         << Shadow.VD->getDeclName()
7809         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7810     if (!CaptureLoc.isInvalid())
7811       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7812           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7813     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7814   }
7815 }
7816 
7817 /// Check -Wshadow without the advantage of a previous lookup.
7818 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7819   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7820     return;
7821 
7822   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7823                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7824   LookupName(R, S);
7825   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7826     CheckShadow(D, ShadowedDecl, R);
7827 }
7828 
7829 /// Check if 'E', which is an expression that is about to be modified, refers
7830 /// to a constructor parameter that shadows a field.
7831 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7832   // Quickly ignore expressions that can't be shadowing ctor parameters.
7833   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7834     return;
7835   E = E->IgnoreParenImpCasts();
7836   auto *DRE = dyn_cast<DeclRefExpr>(E);
7837   if (!DRE)
7838     return;
7839   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7840   auto I = ShadowingDecls.find(D);
7841   if (I == ShadowingDecls.end())
7842     return;
7843   const NamedDecl *ShadowedDecl = I->second;
7844   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7845   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7846   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7847   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7848 
7849   // Avoid issuing multiple warnings about the same decl.
7850   ShadowingDecls.erase(I);
7851 }
7852 
7853 /// Check for conflict between this global or extern "C" declaration and
7854 /// previous global or extern "C" declarations. This is only used in C++.
7855 template<typename T>
7856 static bool checkGlobalOrExternCConflict(
7857     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7858   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7859   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7860 
7861   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7862     // The common case: this global doesn't conflict with any extern "C"
7863     // declaration.
7864     return false;
7865   }
7866 
7867   if (Prev) {
7868     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7869       // Both the old and new declarations have C language linkage. This is a
7870       // redeclaration.
7871       Previous.clear();
7872       Previous.addDecl(Prev);
7873       return true;
7874     }
7875 
7876     // This is a global, non-extern "C" declaration, and there is a previous
7877     // non-global extern "C" declaration. Diagnose if this is a variable
7878     // declaration.
7879     if (!isa<VarDecl>(ND))
7880       return false;
7881   } else {
7882     // The declaration is extern "C". Check for any declaration in the
7883     // translation unit which might conflict.
7884     if (IsGlobal) {
7885       // We have already performed the lookup into the translation unit.
7886       IsGlobal = false;
7887       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7888            I != E; ++I) {
7889         if (isa<VarDecl>(*I)) {
7890           Prev = *I;
7891           break;
7892         }
7893       }
7894     } else {
7895       DeclContext::lookup_result R =
7896           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7897       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7898            I != E; ++I) {
7899         if (isa<VarDecl>(*I)) {
7900           Prev = *I;
7901           break;
7902         }
7903         // FIXME: If we have any other entity with this name in global scope,
7904         // the declaration is ill-formed, but that is a defect: it breaks the
7905         // 'stat' hack, for instance. Only variables can have mangled name
7906         // clashes with extern "C" declarations, so only they deserve a
7907         // diagnostic.
7908       }
7909     }
7910 
7911     if (!Prev)
7912       return false;
7913   }
7914 
7915   // Use the first declaration's location to ensure we point at something which
7916   // is lexically inside an extern "C" linkage-spec.
7917   assert(Prev && "should have found a previous declaration to diagnose");
7918   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7919     Prev = FD->getFirstDecl();
7920   else
7921     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7922 
7923   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7924     << IsGlobal << ND;
7925   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7926     << IsGlobal;
7927   return false;
7928 }
7929 
7930 /// Apply special rules for handling extern "C" declarations. Returns \c true
7931 /// if we have found that this is a redeclaration of some prior entity.
7932 ///
7933 /// Per C++ [dcl.link]p6:
7934 ///   Two declarations [for a function or variable] with C language linkage
7935 ///   with the same name that appear in different scopes refer to the same
7936 ///   [entity]. An entity with C language linkage shall not be declared with
7937 ///   the same name as an entity in global scope.
7938 template<typename T>
7939 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7940                                                   LookupResult &Previous) {
7941   if (!S.getLangOpts().CPlusPlus) {
7942     // In C, when declaring a global variable, look for a corresponding 'extern'
7943     // variable declared in function scope. We don't need this in C++, because
7944     // we find local extern decls in the surrounding file-scope DeclContext.
7945     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7946       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7947         Previous.clear();
7948         Previous.addDecl(Prev);
7949         return true;
7950       }
7951     }
7952     return false;
7953   }
7954 
7955   // A declaration in the translation unit can conflict with an extern "C"
7956   // declaration.
7957   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7958     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7959 
7960   // An extern "C" declaration can conflict with a declaration in the
7961   // translation unit or can be a redeclaration of an extern "C" declaration
7962   // in another scope.
7963   if (isIncompleteDeclExternC(S,ND))
7964     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7965 
7966   // Neither global nor extern "C": nothing to do.
7967   return false;
7968 }
7969 
7970 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7971   // If the decl is already known invalid, don't check it.
7972   if (NewVD->isInvalidDecl())
7973     return;
7974 
7975   QualType T = NewVD->getType();
7976 
7977   // Defer checking an 'auto' type until its initializer is attached.
7978   if (T->isUndeducedType())
7979     return;
7980 
7981   if (NewVD->hasAttrs())
7982     CheckAlignasUnderalignment(NewVD);
7983 
7984   if (T->isObjCObjectType()) {
7985     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7986       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7987     T = Context.getObjCObjectPointerType(T);
7988     NewVD->setType(T);
7989   }
7990 
7991   // Emit an error if an address space was applied to decl with local storage.
7992   // This includes arrays of objects with address space qualifiers, but not
7993   // automatic variables that point to other address spaces.
7994   // ISO/IEC TR 18037 S5.1.2
7995   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7996       T.getAddressSpace() != LangAS::Default) {
7997     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7998     NewVD->setInvalidDecl();
7999     return;
8000   }
8001 
8002   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8003   // scope.
8004   if (getLangOpts().OpenCLVersion == 120 &&
8005       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8006                                             getLangOpts()) &&
8007       NewVD->isStaticLocal()) {
8008     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8009     NewVD->setInvalidDecl();
8010     return;
8011   }
8012 
8013   if (getLangOpts().OpenCL) {
8014     if (!diagnoseOpenCLTypes(*this, NewVD))
8015       return;
8016 
8017     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8018     if (NewVD->hasAttr<BlocksAttr>()) {
8019       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8020       return;
8021     }
8022 
8023     if (T->isBlockPointerType()) {
8024       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8025       // can't use 'extern' storage class.
8026       if (!T.isConstQualified()) {
8027         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8028             << 0 /*const*/;
8029         NewVD->setInvalidDecl();
8030         return;
8031       }
8032       if (NewVD->hasExternalStorage()) {
8033         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8034         NewVD->setInvalidDecl();
8035         return;
8036       }
8037     }
8038 
8039     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8040     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8041         NewVD->hasExternalStorage()) {
8042       if (!T->isSamplerT() && !T->isDependentType() &&
8043           !(T.getAddressSpace() == LangAS::opencl_constant ||
8044             (T.getAddressSpace() == LangAS::opencl_global &&
8045              getOpenCLOptions().areProgramScopeVariablesSupported(
8046                  getLangOpts())))) {
8047         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8048         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8049           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8050               << Scope << "global or constant";
8051         else
8052           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8053               << Scope << "constant";
8054         NewVD->setInvalidDecl();
8055         return;
8056       }
8057     } else {
8058       if (T.getAddressSpace() == LangAS::opencl_global) {
8059         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8060             << 1 /*is any function*/ << "global";
8061         NewVD->setInvalidDecl();
8062         return;
8063       }
8064       if (T.getAddressSpace() == LangAS::opencl_constant ||
8065           T.getAddressSpace() == LangAS::opencl_local) {
8066         FunctionDecl *FD = getCurFunctionDecl();
8067         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8068         // in functions.
8069         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8070           if (T.getAddressSpace() == LangAS::opencl_constant)
8071             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8072                 << 0 /*non-kernel only*/ << "constant";
8073           else
8074             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8075                 << 0 /*non-kernel only*/ << "local";
8076           NewVD->setInvalidDecl();
8077           return;
8078         }
8079         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8080         // in the outermost scope of a kernel function.
8081         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8082           if (!getCurScope()->isFunctionScope()) {
8083             if (T.getAddressSpace() == LangAS::opencl_constant)
8084               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8085                   << "constant";
8086             else
8087               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8088                   << "local";
8089             NewVD->setInvalidDecl();
8090             return;
8091           }
8092         }
8093       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8094                  // If we are parsing a template we didn't deduce an addr
8095                  // space yet.
8096                  T.getAddressSpace() != LangAS::Default) {
8097         // Do not allow other address spaces on automatic variable.
8098         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8099         NewVD->setInvalidDecl();
8100         return;
8101       }
8102     }
8103   }
8104 
8105   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8106       && !NewVD->hasAttr<BlocksAttr>()) {
8107     if (getLangOpts().getGC() != LangOptions::NonGC)
8108       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8109     else {
8110       assert(!getLangOpts().ObjCAutoRefCount);
8111       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8112     }
8113   }
8114 
8115   bool isVM = T->isVariablyModifiedType();
8116   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8117       NewVD->hasAttr<BlocksAttr>())
8118     setFunctionHasBranchProtectedScope();
8119 
8120   if ((isVM && NewVD->hasLinkage()) ||
8121       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8122     bool SizeIsNegative;
8123     llvm::APSInt Oversized;
8124     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8125         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8126     QualType FixedT;
8127     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8128       FixedT = FixedTInfo->getType();
8129     else if (FixedTInfo) {
8130       // Type and type-as-written are canonically different. We need to fix up
8131       // both types separately.
8132       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8133                                                    Oversized);
8134     }
8135     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8136       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8137       // FIXME: This won't give the correct result for
8138       // int a[10][n];
8139       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8140 
8141       if (NewVD->isFileVarDecl())
8142         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8143         << SizeRange;
8144       else if (NewVD->isStaticLocal())
8145         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8146         << SizeRange;
8147       else
8148         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8149         << SizeRange;
8150       NewVD->setInvalidDecl();
8151       return;
8152     }
8153 
8154     if (!FixedTInfo) {
8155       if (NewVD->isFileVarDecl())
8156         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8157       else
8158         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8159       NewVD->setInvalidDecl();
8160       return;
8161     }
8162 
8163     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8164     NewVD->setType(FixedT);
8165     NewVD->setTypeSourceInfo(FixedTInfo);
8166   }
8167 
8168   if (T->isVoidType()) {
8169     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8170     //                    of objects and functions.
8171     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8172       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8173         << T;
8174       NewVD->setInvalidDecl();
8175       return;
8176     }
8177   }
8178 
8179   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8180     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8181     NewVD->setInvalidDecl();
8182     return;
8183   }
8184 
8185   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8186     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8187     NewVD->setInvalidDecl();
8188     return;
8189   }
8190 
8191   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8192     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8193     NewVD->setInvalidDecl();
8194     return;
8195   }
8196 
8197   if (NewVD->isConstexpr() && !T->isDependentType() &&
8198       RequireLiteralType(NewVD->getLocation(), T,
8199                          diag::err_constexpr_var_non_literal)) {
8200     NewVD->setInvalidDecl();
8201     return;
8202   }
8203 
8204   // PPC MMA non-pointer types are not allowed as non-local variable types.
8205   if (Context.getTargetInfo().getTriple().isPPC64() &&
8206       !NewVD->isLocalVarDecl() &&
8207       CheckPPCMMAType(T, NewVD->getLocation())) {
8208     NewVD->setInvalidDecl();
8209     return;
8210   }
8211 }
8212 
8213 /// Perform semantic checking on a newly-created variable
8214 /// declaration.
8215 ///
8216 /// This routine performs all of the type-checking required for a
8217 /// variable declaration once it has been built. It is used both to
8218 /// check variables after they have been parsed and their declarators
8219 /// have been translated into a declaration, and to check variables
8220 /// that have been instantiated from a template.
8221 ///
8222 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8223 ///
8224 /// Returns true if the variable declaration is a redeclaration.
8225 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8226   CheckVariableDeclarationType(NewVD);
8227 
8228   // If the decl is already known invalid, don't check it.
8229   if (NewVD->isInvalidDecl())
8230     return false;
8231 
8232   // If we did not find anything by this name, look for a non-visible
8233   // extern "C" declaration with the same name.
8234   if (Previous.empty() &&
8235       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8236     Previous.setShadowed();
8237 
8238   if (!Previous.empty()) {
8239     MergeVarDecl(NewVD, Previous);
8240     return true;
8241   }
8242   return false;
8243 }
8244 
8245 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8246 /// and if so, check that it's a valid override and remember it.
8247 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8248   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8249 
8250   // Look for methods in base classes that this method might override.
8251   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8252                      /*DetectVirtual=*/false);
8253   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8254     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8255     DeclarationName Name = MD->getDeclName();
8256 
8257     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8258       // We really want to find the base class destructor here.
8259       QualType T = Context.getTypeDeclType(BaseRecord);
8260       CanQualType CT = Context.getCanonicalType(T);
8261       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8262     }
8263 
8264     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8265       CXXMethodDecl *BaseMD =
8266           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8267       if (!BaseMD || !BaseMD->isVirtual() ||
8268           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8269                      /*ConsiderCudaAttrs=*/true,
8270                      // C++2a [class.virtual]p2 does not consider requires
8271                      // clauses when overriding.
8272                      /*ConsiderRequiresClauses=*/false))
8273         continue;
8274 
8275       if (Overridden.insert(BaseMD).second) {
8276         MD->addOverriddenMethod(BaseMD);
8277         CheckOverridingFunctionReturnType(MD, BaseMD);
8278         CheckOverridingFunctionAttributes(MD, BaseMD);
8279         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8280         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8281       }
8282 
8283       // A method can only override one function from each base class. We
8284       // don't track indirectly overridden methods from bases of bases.
8285       return true;
8286     }
8287 
8288     return false;
8289   };
8290 
8291   DC->lookupInBases(VisitBase, Paths);
8292   return !Overridden.empty();
8293 }
8294 
8295 namespace {
8296   // Struct for holding all of the extra arguments needed by
8297   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8298   struct ActOnFDArgs {
8299     Scope *S;
8300     Declarator &D;
8301     MultiTemplateParamsArg TemplateParamLists;
8302     bool AddToScope;
8303   };
8304 } // end anonymous namespace
8305 
8306 namespace {
8307 
8308 // Callback to only accept typo corrections that have a non-zero edit distance.
8309 // Also only accept corrections that have the same parent decl.
8310 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8311  public:
8312   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8313                             CXXRecordDecl *Parent)
8314       : Context(Context), OriginalFD(TypoFD),
8315         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8316 
8317   bool ValidateCandidate(const TypoCorrection &candidate) override {
8318     if (candidate.getEditDistance() == 0)
8319       return false;
8320 
8321     SmallVector<unsigned, 1> MismatchedParams;
8322     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8323                                           CDeclEnd = candidate.end();
8324          CDecl != CDeclEnd; ++CDecl) {
8325       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8326 
8327       if (FD && !FD->hasBody() &&
8328           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8329         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8330           CXXRecordDecl *Parent = MD->getParent();
8331           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8332             return true;
8333         } else if (!ExpectedParent) {
8334           return true;
8335         }
8336       }
8337     }
8338 
8339     return false;
8340   }
8341 
8342   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8343     return std::make_unique<DifferentNameValidatorCCC>(*this);
8344   }
8345 
8346  private:
8347   ASTContext &Context;
8348   FunctionDecl *OriginalFD;
8349   CXXRecordDecl *ExpectedParent;
8350 };
8351 
8352 } // end anonymous namespace
8353 
8354 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8355   TypoCorrectedFunctionDefinitions.insert(F);
8356 }
8357 
8358 /// Generate diagnostics for an invalid function redeclaration.
8359 ///
8360 /// This routine handles generating the diagnostic messages for an invalid
8361 /// function redeclaration, including finding possible similar declarations
8362 /// or performing typo correction if there are no previous declarations with
8363 /// the same name.
8364 ///
8365 /// Returns a NamedDecl iff typo correction was performed and substituting in
8366 /// the new declaration name does not cause new errors.
8367 static NamedDecl *DiagnoseInvalidRedeclaration(
8368     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8369     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8370   DeclarationName Name = NewFD->getDeclName();
8371   DeclContext *NewDC = NewFD->getDeclContext();
8372   SmallVector<unsigned, 1> MismatchedParams;
8373   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8374   TypoCorrection Correction;
8375   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8376   unsigned DiagMsg =
8377     IsLocalFriend ? diag::err_no_matching_local_friend :
8378     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8379     diag::err_member_decl_does_not_match;
8380   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8381                     IsLocalFriend ? Sema::LookupLocalFriendName
8382                                   : Sema::LookupOrdinaryName,
8383                     Sema::ForVisibleRedeclaration);
8384 
8385   NewFD->setInvalidDecl();
8386   if (IsLocalFriend)
8387     SemaRef.LookupName(Prev, S);
8388   else
8389     SemaRef.LookupQualifiedName(Prev, NewDC);
8390   assert(!Prev.isAmbiguous() &&
8391          "Cannot have an ambiguity in previous-declaration lookup");
8392   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8393   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8394                                 MD ? MD->getParent() : nullptr);
8395   if (!Prev.empty()) {
8396     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8397          Func != FuncEnd; ++Func) {
8398       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8399       if (FD &&
8400           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8401         // Add 1 to the index so that 0 can mean the mismatch didn't
8402         // involve a parameter
8403         unsigned ParamNum =
8404             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8405         NearMatches.push_back(std::make_pair(FD, ParamNum));
8406       }
8407     }
8408   // If the qualified name lookup yielded nothing, try typo correction
8409   } else if ((Correction = SemaRef.CorrectTypo(
8410                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8411                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8412                   IsLocalFriend ? nullptr : NewDC))) {
8413     // Set up everything for the call to ActOnFunctionDeclarator
8414     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8415                               ExtraArgs.D.getIdentifierLoc());
8416     Previous.clear();
8417     Previous.setLookupName(Correction.getCorrection());
8418     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8419                                     CDeclEnd = Correction.end();
8420          CDecl != CDeclEnd; ++CDecl) {
8421       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8422       if (FD && !FD->hasBody() &&
8423           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8424         Previous.addDecl(FD);
8425       }
8426     }
8427     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8428 
8429     NamedDecl *Result;
8430     // Retry building the function declaration with the new previous
8431     // declarations, and with errors suppressed.
8432     {
8433       // Trap errors.
8434       Sema::SFINAETrap Trap(SemaRef);
8435 
8436       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8437       // pieces need to verify the typo-corrected C++ declaration and hopefully
8438       // eliminate the need for the parameter pack ExtraArgs.
8439       Result = SemaRef.ActOnFunctionDeclarator(
8440           ExtraArgs.S, ExtraArgs.D,
8441           Correction.getCorrectionDecl()->getDeclContext(),
8442           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8443           ExtraArgs.AddToScope);
8444 
8445       if (Trap.hasErrorOccurred())
8446         Result = nullptr;
8447     }
8448 
8449     if (Result) {
8450       // Determine which correction we picked.
8451       Decl *Canonical = Result->getCanonicalDecl();
8452       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8453            I != E; ++I)
8454         if ((*I)->getCanonicalDecl() == Canonical)
8455           Correction.setCorrectionDecl(*I);
8456 
8457       // Let Sema know about the correction.
8458       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8459       SemaRef.diagnoseTypo(
8460           Correction,
8461           SemaRef.PDiag(IsLocalFriend
8462                           ? diag::err_no_matching_local_friend_suggest
8463                           : diag::err_member_decl_does_not_match_suggest)
8464             << Name << NewDC << IsDefinition);
8465       return Result;
8466     }
8467 
8468     // Pretend the typo correction never occurred
8469     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8470                               ExtraArgs.D.getIdentifierLoc());
8471     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8472     Previous.clear();
8473     Previous.setLookupName(Name);
8474   }
8475 
8476   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8477       << Name << NewDC << IsDefinition << NewFD->getLocation();
8478 
8479   bool NewFDisConst = false;
8480   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8481     NewFDisConst = NewMD->isConst();
8482 
8483   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8484        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8485        NearMatch != NearMatchEnd; ++NearMatch) {
8486     FunctionDecl *FD = NearMatch->first;
8487     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8488     bool FDisConst = MD && MD->isConst();
8489     bool IsMember = MD || !IsLocalFriend;
8490 
8491     // FIXME: These notes are poorly worded for the local friend case.
8492     if (unsigned Idx = NearMatch->second) {
8493       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8494       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8495       if (Loc.isInvalid()) Loc = FD->getLocation();
8496       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8497                                  : diag::note_local_decl_close_param_match)
8498         << Idx << FDParam->getType()
8499         << NewFD->getParamDecl(Idx - 1)->getType();
8500     } else if (FDisConst != NewFDisConst) {
8501       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8502           << NewFDisConst << FD->getSourceRange().getEnd();
8503     } else
8504       SemaRef.Diag(FD->getLocation(),
8505                    IsMember ? diag::note_member_def_close_match
8506                             : diag::note_local_decl_close_match);
8507   }
8508   return nullptr;
8509 }
8510 
8511 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8512   switch (D.getDeclSpec().getStorageClassSpec()) {
8513   default: llvm_unreachable("Unknown storage class!");
8514   case DeclSpec::SCS_auto:
8515   case DeclSpec::SCS_register:
8516   case DeclSpec::SCS_mutable:
8517     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8518                  diag::err_typecheck_sclass_func);
8519     D.getMutableDeclSpec().ClearStorageClassSpecs();
8520     D.setInvalidType();
8521     break;
8522   case DeclSpec::SCS_unspecified: break;
8523   case DeclSpec::SCS_extern:
8524     if (D.getDeclSpec().isExternInLinkageSpec())
8525       return SC_None;
8526     return SC_Extern;
8527   case DeclSpec::SCS_static: {
8528     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8529       // C99 6.7.1p5:
8530       //   The declaration of an identifier for a function that has
8531       //   block scope shall have no explicit storage-class specifier
8532       //   other than extern
8533       // See also (C++ [dcl.stc]p4).
8534       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8535                    diag::err_static_block_func);
8536       break;
8537     } else
8538       return SC_Static;
8539   }
8540   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8541   }
8542 
8543   // No explicit storage class has already been returned
8544   return SC_None;
8545 }
8546 
8547 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8548                                            DeclContext *DC, QualType &R,
8549                                            TypeSourceInfo *TInfo,
8550                                            StorageClass SC,
8551                                            bool &IsVirtualOkay) {
8552   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8553   DeclarationName Name = NameInfo.getName();
8554 
8555   FunctionDecl *NewFD = nullptr;
8556   bool isInline = D.getDeclSpec().isInlineSpecified();
8557 
8558   if (!SemaRef.getLangOpts().CPlusPlus) {
8559     // Determine whether the function was written with a
8560     // prototype. This true when:
8561     //   - there is a prototype in the declarator, or
8562     //   - the type R of the function is some kind of typedef or other non-
8563     //     attributed reference to a type name (which eventually refers to a
8564     //     function type).
8565     bool HasPrototype =
8566       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8567       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8568 
8569     NewFD = FunctionDecl::Create(
8570         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8571         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8572         ConstexprSpecKind::Unspecified,
8573         /*TrailingRequiresClause=*/nullptr);
8574     if (D.isInvalidType())
8575       NewFD->setInvalidDecl();
8576 
8577     return NewFD;
8578   }
8579 
8580   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8581 
8582   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8583   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8584     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8585                  diag::err_constexpr_wrong_decl_kind)
8586         << static_cast<int>(ConstexprKind);
8587     ConstexprKind = ConstexprSpecKind::Unspecified;
8588     D.getMutableDeclSpec().ClearConstexprSpec();
8589   }
8590   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8591 
8592   // Check that the return type is not an abstract class type.
8593   // For record types, this is done by the AbstractClassUsageDiagnoser once
8594   // the class has been completely parsed.
8595   if (!DC->isRecord() &&
8596       SemaRef.RequireNonAbstractType(
8597           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8598           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8599     D.setInvalidType();
8600 
8601   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8602     // This is a C++ constructor declaration.
8603     assert(DC->isRecord() &&
8604            "Constructors can only be declared in a member context");
8605 
8606     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8607     return CXXConstructorDecl::Create(
8608         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8609         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8610         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8611         InheritedConstructor(), TrailingRequiresClause);
8612 
8613   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8614     // This is a C++ destructor declaration.
8615     if (DC->isRecord()) {
8616       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8617       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8618       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8619           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8620           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8621           /*isImplicitlyDeclared=*/false, ConstexprKind,
8622           TrailingRequiresClause);
8623 
8624       // If the destructor needs an implicit exception specification, set it
8625       // now. FIXME: It'd be nice to be able to create the right type to start
8626       // with, but the type needs to reference the destructor declaration.
8627       if (SemaRef.getLangOpts().CPlusPlus11)
8628         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8629 
8630       IsVirtualOkay = true;
8631       return NewDD;
8632 
8633     } else {
8634       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8635       D.setInvalidType();
8636 
8637       // Create a FunctionDecl to satisfy the function definition parsing
8638       // code path.
8639       return FunctionDecl::Create(
8640           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8641           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8642           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8643     }
8644 
8645   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8646     if (!DC->isRecord()) {
8647       SemaRef.Diag(D.getIdentifierLoc(),
8648            diag::err_conv_function_not_member);
8649       return nullptr;
8650     }
8651 
8652     SemaRef.CheckConversionDeclarator(D, R, SC);
8653     if (D.isInvalidType())
8654       return nullptr;
8655 
8656     IsVirtualOkay = true;
8657     return CXXConversionDecl::Create(
8658         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8659         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8660         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8661         TrailingRequiresClause);
8662 
8663   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8664     if (TrailingRequiresClause)
8665       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8666                    diag::err_trailing_requires_clause_on_deduction_guide)
8667           << TrailingRequiresClause->getSourceRange();
8668     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8669 
8670     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8671                                          ExplicitSpecifier, NameInfo, R, TInfo,
8672                                          D.getEndLoc());
8673   } else if (DC->isRecord()) {
8674     // If the name of the function is the same as the name of the record,
8675     // then this must be an invalid constructor that has a return type.
8676     // (The parser checks for a return type and makes the declarator a
8677     // constructor if it has no return type).
8678     if (Name.getAsIdentifierInfo() &&
8679         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8680       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8681         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8682         << SourceRange(D.getIdentifierLoc());
8683       return nullptr;
8684     }
8685 
8686     // This is a C++ method declaration.
8687     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8688         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8689         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8690         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8691     IsVirtualOkay = !Ret->isStatic();
8692     return Ret;
8693   } else {
8694     bool isFriend =
8695         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8696     if (!isFriend && SemaRef.CurContext->isRecord())
8697       return nullptr;
8698 
8699     // Determine whether the function was written with a
8700     // prototype. This true when:
8701     //   - we're in C++ (where every function has a prototype),
8702     return FunctionDecl::Create(
8703         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8704         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8705         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8706   }
8707 }
8708 
8709 enum OpenCLParamType {
8710   ValidKernelParam,
8711   PtrPtrKernelParam,
8712   PtrKernelParam,
8713   InvalidAddrSpacePtrKernelParam,
8714   InvalidKernelParam,
8715   RecordKernelParam
8716 };
8717 
8718 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8719   // Size dependent types are just typedefs to normal integer types
8720   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8721   // integers other than by their names.
8722   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8723 
8724   // Remove typedefs one by one until we reach a typedef
8725   // for a size dependent type.
8726   QualType DesugaredTy = Ty;
8727   do {
8728     ArrayRef<StringRef> Names(SizeTypeNames);
8729     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8730     if (Names.end() != Match)
8731       return true;
8732 
8733     Ty = DesugaredTy;
8734     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8735   } while (DesugaredTy != Ty);
8736 
8737   return false;
8738 }
8739 
8740 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8741   if (PT->isDependentType())
8742     return InvalidKernelParam;
8743 
8744   if (PT->isPointerType() || PT->isReferenceType()) {
8745     QualType PointeeType = PT->getPointeeType();
8746     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8747         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8748         PointeeType.getAddressSpace() == LangAS::Default)
8749       return InvalidAddrSpacePtrKernelParam;
8750 
8751     if (PointeeType->isPointerType()) {
8752       // This is a pointer to pointer parameter.
8753       // Recursively check inner type.
8754       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8755       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8756           ParamKind == InvalidKernelParam)
8757         return ParamKind;
8758 
8759       return PtrPtrKernelParam;
8760     }
8761 
8762     // C++ for OpenCL v1.0 s2.4:
8763     // Moreover the types used in parameters of the kernel functions must be:
8764     // Standard layout types for pointer parameters. The same applies to
8765     // reference if an implementation supports them in kernel parameters.
8766     if (S.getLangOpts().OpenCLCPlusPlus &&
8767         !S.getOpenCLOptions().isAvailableOption(
8768             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8769         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8770         !PointeeType->isStandardLayoutType())
8771       return InvalidKernelParam;
8772 
8773     return PtrKernelParam;
8774   }
8775 
8776   // OpenCL v1.2 s6.9.k:
8777   // Arguments to kernel functions in a program cannot be declared with the
8778   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8779   // uintptr_t or a struct and/or union that contain fields declared to be one
8780   // of these built-in scalar types.
8781   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8782     return InvalidKernelParam;
8783 
8784   if (PT->isImageType())
8785     return PtrKernelParam;
8786 
8787   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8788     return InvalidKernelParam;
8789 
8790   // OpenCL extension spec v1.2 s9.5:
8791   // This extension adds support for half scalar and vector types as built-in
8792   // types that can be used for arithmetic operations, conversions etc.
8793   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8794       PT->isHalfType())
8795     return InvalidKernelParam;
8796 
8797   // Look into an array argument to check if it has a forbidden type.
8798   if (PT->isArrayType()) {
8799     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8800     // Call ourself to check an underlying type of an array. Since the
8801     // getPointeeOrArrayElementType returns an innermost type which is not an
8802     // array, this recursive call only happens once.
8803     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8804   }
8805 
8806   // C++ for OpenCL v1.0 s2.4:
8807   // Moreover the types used in parameters of the kernel functions must be:
8808   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8809   // types) for parameters passed by value;
8810   if (S.getLangOpts().OpenCLCPlusPlus &&
8811       !S.getOpenCLOptions().isAvailableOption(
8812           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8813       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8814     return InvalidKernelParam;
8815 
8816   if (PT->isRecordType())
8817     return RecordKernelParam;
8818 
8819   return ValidKernelParam;
8820 }
8821 
8822 static void checkIsValidOpenCLKernelParameter(
8823   Sema &S,
8824   Declarator &D,
8825   ParmVarDecl *Param,
8826   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8827   QualType PT = Param->getType();
8828 
8829   // Cache the valid types we encounter to avoid rechecking structs that are
8830   // used again
8831   if (ValidTypes.count(PT.getTypePtr()))
8832     return;
8833 
8834   switch (getOpenCLKernelParameterType(S, PT)) {
8835   case PtrPtrKernelParam:
8836     // OpenCL v3.0 s6.11.a:
8837     // A kernel function argument cannot be declared as a pointer to a pointer
8838     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8839     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8840       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8841       D.setInvalidType();
8842       return;
8843     }
8844 
8845     ValidTypes.insert(PT.getTypePtr());
8846     return;
8847 
8848   case InvalidAddrSpacePtrKernelParam:
8849     // OpenCL v1.0 s6.5:
8850     // __kernel function arguments declared to be a pointer of a type can point
8851     // to one of the following address spaces only : __global, __local or
8852     // __constant.
8853     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8854     D.setInvalidType();
8855     return;
8856 
8857     // OpenCL v1.2 s6.9.k:
8858     // Arguments to kernel functions in a program cannot be declared with the
8859     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8860     // uintptr_t or a struct and/or union that contain fields declared to be
8861     // one of these built-in scalar types.
8862 
8863   case InvalidKernelParam:
8864     // OpenCL v1.2 s6.8 n:
8865     // A kernel function argument cannot be declared
8866     // of event_t type.
8867     // Do not diagnose half type since it is diagnosed as invalid argument
8868     // type for any function elsewhere.
8869     if (!PT->isHalfType()) {
8870       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8871 
8872       // Explain what typedefs are involved.
8873       const TypedefType *Typedef = nullptr;
8874       while ((Typedef = PT->getAs<TypedefType>())) {
8875         SourceLocation Loc = Typedef->getDecl()->getLocation();
8876         // SourceLocation may be invalid for a built-in type.
8877         if (Loc.isValid())
8878           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8879         PT = Typedef->desugar();
8880       }
8881     }
8882 
8883     D.setInvalidType();
8884     return;
8885 
8886   case PtrKernelParam:
8887   case ValidKernelParam:
8888     ValidTypes.insert(PT.getTypePtr());
8889     return;
8890 
8891   case RecordKernelParam:
8892     break;
8893   }
8894 
8895   // Track nested structs we will inspect
8896   SmallVector<const Decl *, 4> VisitStack;
8897 
8898   // Track where we are in the nested structs. Items will migrate from
8899   // VisitStack to HistoryStack as we do the DFS for bad field.
8900   SmallVector<const FieldDecl *, 4> HistoryStack;
8901   HistoryStack.push_back(nullptr);
8902 
8903   // At this point we already handled everything except of a RecordType or
8904   // an ArrayType of a RecordType.
8905   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8906   const RecordType *RecTy =
8907       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8908   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8909 
8910   VisitStack.push_back(RecTy->getDecl());
8911   assert(VisitStack.back() && "First decl null?");
8912 
8913   do {
8914     const Decl *Next = VisitStack.pop_back_val();
8915     if (!Next) {
8916       assert(!HistoryStack.empty());
8917       // Found a marker, we have gone up a level
8918       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8919         ValidTypes.insert(Hist->getType().getTypePtr());
8920 
8921       continue;
8922     }
8923 
8924     // Adds everything except the original parameter declaration (which is not a
8925     // field itself) to the history stack.
8926     const RecordDecl *RD;
8927     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8928       HistoryStack.push_back(Field);
8929 
8930       QualType FieldTy = Field->getType();
8931       // Other field types (known to be valid or invalid) are handled while we
8932       // walk around RecordDecl::fields().
8933       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8934              "Unexpected type.");
8935       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8936 
8937       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8938     } else {
8939       RD = cast<RecordDecl>(Next);
8940     }
8941 
8942     // Add a null marker so we know when we've gone back up a level
8943     VisitStack.push_back(nullptr);
8944 
8945     for (const auto *FD : RD->fields()) {
8946       QualType QT = FD->getType();
8947 
8948       if (ValidTypes.count(QT.getTypePtr()))
8949         continue;
8950 
8951       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8952       if (ParamType == ValidKernelParam)
8953         continue;
8954 
8955       if (ParamType == RecordKernelParam) {
8956         VisitStack.push_back(FD);
8957         continue;
8958       }
8959 
8960       // OpenCL v1.2 s6.9.p:
8961       // Arguments to kernel functions that are declared to be a struct or union
8962       // do not allow OpenCL objects to be passed as elements of the struct or
8963       // union.
8964       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8965           ParamType == InvalidAddrSpacePtrKernelParam) {
8966         S.Diag(Param->getLocation(),
8967                diag::err_record_with_pointers_kernel_param)
8968           << PT->isUnionType()
8969           << PT;
8970       } else {
8971         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8972       }
8973 
8974       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8975           << OrigRecDecl->getDeclName();
8976 
8977       // We have an error, now let's go back up through history and show where
8978       // the offending field came from
8979       for (ArrayRef<const FieldDecl *>::const_iterator
8980                I = HistoryStack.begin() + 1,
8981                E = HistoryStack.end();
8982            I != E; ++I) {
8983         const FieldDecl *OuterField = *I;
8984         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8985           << OuterField->getType();
8986       }
8987 
8988       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8989         << QT->isPointerType()
8990         << QT;
8991       D.setInvalidType();
8992       return;
8993     }
8994   } while (!VisitStack.empty());
8995 }
8996 
8997 /// Find the DeclContext in which a tag is implicitly declared if we see an
8998 /// elaborated type specifier in the specified context, and lookup finds
8999 /// nothing.
9000 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9001   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9002     DC = DC->getParent();
9003   return DC;
9004 }
9005 
9006 /// Find the Scope in which a tag is implicitly declared if we see an
9007 /// elaborated type specifier in the specified context, and lookup finds
9008 /// nothing.
9009 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9010   while (S->isClassScope() ||
9011          (LangOpts.CPlusPlus &&
9012           S->isFunctionPrototypeScope()) ||
9013          ((S->getFlags() & Scope::DeclScope) == 0) ||
9014          (S->getEntity() && S->getEntity()->isTransparentContext()))
9015     S = S->getParent();
9016   return S;
9017 }
9018 
9019 NamedDecl*
9020 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9021                               TypeSourceInfo *TInfo, LookupResult &Previous,
9022                               MultiTemplateParamsArg TemplateParamListsRef,
9023                               bool &AddToScope) {
9024   QualType R = TInfo->getType();
9025 
9026   assert(R->isFunctionType());
9027   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9028     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9029 
9030   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9031   for (TemplateParameterList *TPL : TemplateParamListsRef)
9032     TemplateParamLists.push_back(TPL);
9033   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9034     if (!TemplateParamLists.empty() &&
9035         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9036       TemplateParamLists.back() = Invented;
9037     else
9038       TemplateParamLists.push_back(Invented);
9039   }
9040 
9041   // TODO: consider using NameInfo for diagnostic.
9042   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9043   DeclarationName Name = NameInfo.getName();
9044   StorageClass SC = getFunctionStorageClass(*this, D);
9045 
9046   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9047     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9048          diag::err_invalid_thread)
9049       << DeclSpec::getSpecifierName(TSCS);
9050 
9051   if (D.isFirstDeclarationOfMember())
9052     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9053                            D.getIdentifierLoc());
9054 
9055   bool isFriend = false;
9056   FunctionTemplateDecl *FunctionTemplate = nullptr;
9057   bool isMemberSpecialization = false;
9058   bool isFunctionTemplateSpecialization = false;
9059 
9060   bool isDependentClassScopeExplicitSpecialization = false;
9061   bool HasExplicitTemplateArgs = false;
9062   TemplateArgumentListInfo TemplateArgs;
9063 
9064   bool isVirtualOkay = false;
9065 
9066   DeclContext *OriginalDC = DC;
9067   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9068 
9069   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9070                                               isVirtualOkay);
9071   if (!NewFD) return nullptr;
9072 
9073   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9074     NewFD->setTopLevelDeclInObjCContainer();
9075 
9076   // Set the lexical context. If this is a function-scope declaration, or has a
9077   // C++ scope specifier, or is the object of a friend declaration, the lexical
9078   // context will be different from the semantic context.
9079   NewFD->setLexicalDeclContext(CurContext);
9080 
9081   if (IsLocalExternDecl)
9082     NewFD->setLocalExternDecl();
9083 
9084   if (getLangOpts().CPlusPlus) {
9085     bool isInline = D.getDeclSpec().isInlineSpecified();
9086     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9087     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9088     isFriend = D.getDeclSpec().isFriendSpecified();
9089     if (isFriend && !isInline && D.isFunctionDefinition()) {
9090       // C++ [class.friend]p5
9091       //   A function can be defined in a friend declaration of a
9092       //   class . . . . Such a function is implicitly inline.
9093       NewFD->setImplicitlyInline();
9094     }
9095 
9096     // If this is a method defined in an __interface, and is not a constructor
9097     // or an overloaded operator, then set the pure flag (isVirtual will already
9098     // return true).
9099     if (const CXXRecordDecl *Parent =
9100           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9101       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9102         NewFD->setPure(true);
9103 
9104       // C++ [class.union]p2
9105       //   A union can have member functions, but not virtual functions.
9106       if (isVirtual && Parent->isUnion())
9107         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9108     }
9109 
9110     SetNestedNameSpecifier(*this, NewFD, D);
9111     isMemberSpecialization = false;
9112     isFunctionTemplateSpecialization = false;
9113     if (D.isInvalidType())
9114       NewFD->setInvalidDecl();
9115 
9116     // Match up the template parameter lists with the scope specifier, then
9117     // determine whether we have a template or a template specialization.
9118     bool Invalid = false;
9119     TemplateParameterList *TemplateParams =
9120         MatchTemplateParametersToScopeSpecifier(
9121             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9122             D.getCXXScopeSpec(),
9123             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9124                 ? D.getName().TemplateId
9125                 : nullptr,
9126             TemplateParamLists, isFriend, isMemberSpecialization,
9127             Invalid);
9128     if (TemplateParams) {
9129       // Check that we can declare a template here.
9130       if (CheckTemplateDeclScope(S, TemplateParams))
9131         NewFD->setInvalidDecl();
9132 
9133       if (TemplateParams->size() > 0) {
9134         // This is a function template
9135 
9136         // A destructor cannot be a template.
9137         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9138           Diag(NewFD->getLocation(), diag::err_destructor_template);
9139           NewFD->setInvalidDecl();
9140         }
9141 
9142         // If we're adding a template to a dependent context, we may need to
9143         // rebuilding some of the types used within the template parameter list,
9144         // now that we know what the current instantiation is.
9145         if (DC->isDependentContext()) {
9146           ContextRAII SavedContext(*this, DC);
9147           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9148             Invalid = true;
9149         }
9150 
9151         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9152                                                         NewFD->getLocation(),
9153                                                         Name, TemplateParams,
9154                                                         NewFD);
9155         FunctionTemplate->setLexicalDeclContext(CurContext);
9156         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9157 
9158         // For source fidelity, store the other template param lists.
9159         if (TemplateParamLists.size() > 1) {
9160           NewFD->setTemplateParameterListsInfo(Context,
9161               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9162                   .drop_back(1));
9163         }
9164       } else {
9165         // This is a function template specialization.
9166         isFunctionTemplateSpecialization = true;
9167         // For source fidelity, store all the template param lists.
9168         if (TemplateParamLists.size() > 0)
9169           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9170 
9171         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9172         if (isFriend) {
9173           // We want to remove the "template<>", found here.
9174           SourceRange RemoveRange = TemplateParams->getSourceRange();
9175 
9176           // If we remove the template<> and the name is not a
9177           // template-id, we're actually silently creating a problem:
9178           // the friend declaration will refer to an untemplated decl,
9179           // and clearly the user wants a template specialization.  So
9180           // we need to insert '<>' after the name.
9181           SourceLocation InsertLoc;
9182           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9183             InsertLoc = D.getName().getSourceRange().getEnd();
9184             InsertLoc = getLocForEndOfToken(InsertLoc);
9185           }
9186 
9187           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9188             << Name << RemoveRange
9189             << FixItHint::CreateRemoval(RemoveRange)
9190             << FixItHint::CreateInsertion(InsertLoc, "<>");
9191         }
9192       }
9193     } else {
9194       // Check that we can declare a template here.
9195       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9196           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9197         NewFD->setInvalidDecl();
9198 
9199       // All template param lists were matched against the scope specifier:
9200       // this is NOT (an explicit specialization of) a template.
9201       if (TemplateParamLists.size() > 0)
9202         // For source fidelity, store all the template param lists.
9203         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9204     }
9205 
9206     if (Invalid) {
9207       NewFD->setInvalidDecl();
9208       if (FunctionTemplate)
9209         FunctionTemplate->setInvalidDecl();
9210     }
9211 
9212     // C++ [dcl.fct.spec]p5:
9213     //   The virtual specifier shall only be used in declarations of
9214     //   nonstatic class member functions that appear within a
9215     //   member-specification of a class declaration; see 10.3.
9216     //
9217     if (isVirtual && !NewFD->isInvalidDecl()) {
9218       if (!isVirtualOkay) {
9219         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9220              diag::err_virtual_non_function);
9221       } else if (!CurContext->isRecord()) {
9222         // 'virtual' was specified outside of the class.
9223         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9224              diag::err_virtual_out_of_class)
9225           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9226       } else if (NewFD->getDescribedFunctionTemplate()) {
9227         // C++ [temp.mem]p3:
9228         //  A member function template shall not be virtual.
9229         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9230              diag::err_virtual_member_function_template)
9231           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9232       } else {
9233         // Okay: Add virtual to the method.
9234         NewFD->setVirtualAsWritten(true);
9235       }
9236 
9237       if (getLangOpts().CPlusPlus14 &&
9238           NewFD->getReturnType()->isUndeducedType())
9239         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9240     }
9241 
9242     if (getLangOpts().CPlusPlus14 &&
9243         (NewFD->isDependentContext() ||
9244          (isFriend && CurContext->isDependentContext())) &&
9245         NewFD->getReturnType()->isUndeducedType()) {
9246       // If the function template is referenced directly (for instance, as a
9247       // member of the current instantiation), pretend it has a dependent type.
9248       // This is not really justified by the standard, but is the only sane
9249       // thing to do.
9250       // FIXME: For a friend function, we have not marked the function as being
9251       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9252       const FunctionProtoType *FPT =
9253           NewFD->getType()->castAs<FunctionProtoType>();
9254       QualType Result =
9255           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9256       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9257                                              FPT->getExtProtoInfo()));
9258     }
9259 
9260     // C++ [dcl.fct.spec]p3:
9261     //  The inline specifier shall not appear on a block scope function
9262     //  declaration.
9263     if (isInline && !NewFD->isInvalidDecl()) {
9264       if (CurContext->isFunctionOrMethod()) {
9265         // 'inline' is not allowed on block scope function declaration.
9266         Diag(D.getDeclSpec().getInlineSpecLoc(),
9267              diag::err_inline_declaration_block_scope) << Name
9268           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9269       }
9270     }
9271 
9272     // C++ [dcl.fct.spec]p6:
9273     //  The explicit specifier shall be used only in the declaration of a
9274     //  constructor or conversion function within its class definition;
9275     //  see 12.3.1 and 12.3.2.
9276     if (hasExplicit && !NewFD->isInvalidDecl() &&
9277         !isa<CXXDeductionGuideDecl>(NewFD)) {
9278       if (!CurContext->isRecord()) {
9279         // 'explicit' was specified outside of the class.
9280         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9281              diag::err_explicit_out_of_class)
9282             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9283       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9284                  !isa<CXXConversionDecl>(NewFD)) {
9285         // 'explicit' was specified on a function that wasn't a constructor
9286         // or conversion function.
9287         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9288              diag::err_explicit_non_ctor_or_conv_function)
9289             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9290       }
9291     }
9292 
9293     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9294     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9295       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9296       // are implicitly inline.
9297       NewFD->setImplicitlyInline();
9298 
9299       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9300       // be either constructors or to return a literal type. Therefore,
9301       // destructors cannot be declared constexpr.
9302       if (isa<CXXDestructorDecl>(NewFD) &&
9303           (!getLangOpts().CPlusPlus20 ||
9304            ConstexprKind == ConstexprSpecKind::Consteval)) {
9305         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9306             << static_cast<int>(ConstexprKind);
9307         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9308                                     ? ConstexprSpecKind::Unspecified
9309                                     : ConstexprSpecKind::Constexpr);
9310       }
9311       // C++20 [dcl.constexpr]p2: An allocation function, or a
9312       // deallocation function shall not be declared with the consteval
9313       // specifier.
9314       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9315           (NewFD->getOverloadedOperator() == OO_New ||
9316            NewFD->getOverloadedOperator() == OO_Array_New ||
9317            NewFD->getOverloadedOperator() == OO_Delete ||
9318            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9319         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9320              diag::err_invalid_consteval_decl_kind)
9321             << NewFD;
9322         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9323       }
9324     }
9325 
9326     // If __module_private__ was specified, mark the function accordingly.
9327     if (D.getDeclSpec().isModulePrivateSpecified()) {
9328       if (isFunctionTemplateSpecialization) {
9329         SourceLocation ModulePrivateLoc
9330           = D.getDeclSpec().getModulePrivateSpecLoc();
9331         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9332           << 0
9333           << FixItHint::CreateRemoval(ModulePrivateLoc);
9334       } else {
9335         NewFD->setModulePrivate();
9336         if (FunctionTemplate)
9337           FunctionTemplate->setModulePrivate();
9338       }
9339     }
9340 
9341     if (isFriend) {
9342       if (FunctionTemplate) {
9343         FunctionTemplate->setObjectOfFriendDecl();
9344         FunctionTemplate->setAccess(AS_public);
9345       }
9346       NewFD->setObjectOfFriendDecl();
9347       NewFD->setAccess(AS_public);
9348     }
9349 
9350     // If a function is defined as defaulted or deleted, mark it as such now.
9351     // We'll do the relevant checks on defaulted / deleted functions later.
9352     switch (D.getFunctionDefinitionKind()) {
9353     case FunctionDefinitionKind::Declaration:
9354     case FunctionDefinitionKind::Definition:
9355       break;
9356 
9357     case FunctionDefinitionKind::Defaulted:
9358       NewFD->setDefaulted();
9359       break;
9360 
9361     case FunctionDefinitionKind::Deleted:
9362       NewFD->setDeletedAsWritten();
9363       break;
9364     }
9365 
9366     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9367         D.isFunctionDefinition()) {
9368       // C++ [class.mfct]p2:
9369       //   A member function may be defined (8.4) in its class definition, in
9370       //   which case it is an inline member function (7.1.2)
9371       NewFD->setImplicitlyInline();
9372     }
9373 
9374     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9375         !CurContext->isRecord()) {
9376       // C++ [class.static]p1:
9377       //   A data or function member of a class may be declared static
9378       //   in a class definition, in which case it is a static member of
9379       //   the class.
9380 
9381       // Complain about the 'static' specifier if it's on an out-of-line
9382       // member function definition.
9383 
9384       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9385       // member function template declaration and class member template
9386       // declaration (MSVC versions before 2015), warn about this.
9387       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9388            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9389              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9390            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9391            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9392         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9393     }
9394 
9395     // C++11 [except.spec]p15:
9396     //   A deallocation function with no exception-specification is treated
9397     //   as if it were specified with noexcept(true).
9398     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9399     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9400          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9401         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9402       NewFD->setType(Context.getFunctionType(
9403           FPT->getReturnType(), FPT->getParamTypes(),
9404           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9405   }
9406 
9407   // Filter out previous declarations that don't match the scope.
9408   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9409                        D.getCXXScopeSpec().isNotEmpty() ||
9410                        isMemberSpecialization ||
9411                        isFunctionTemplateSpecialization);
9412 
9413   // Handle GNU asm-label extension (encoded as an attribute).
9414   if (Expr *E = (Expr*) D.getAsmLabel()) {
9415     // The parser guarantees this is a string.
9416     StringLiteral *SE = cast<StringLiteral>(E);
9417     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9418                                         /*IsLiteralLabel=*/true,
9419                                         SE->getStrTokenLoc(0)));
9420   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9421     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9422       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9423     if (I != ExtnameUndeclaredIdentifiers.end()) {
9424       if (isDeclExternC(NewFD)) {
9425         NewFD->addAttr(I->second);
9426         ExtnameUndeclaredIdentifiers.erase(I);
9427       } else
9428         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9429             << /*Variable*/0 << NewFD;
9430     }
9431   }
9432 
9433   // Copy the parameter declarations from the declarator D to the function
9434   // declaration NewFD, if they are available.  First scavenge them into Params.
9435   SmallVector<ParmVarDecl*, 16> Params;
9436   unsigned FTIIdx;
9437   if (D.isFunctionDeclarator(FTIIdx)) {
9438     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9439 
9440     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9441     // function that takes no arguments, not a function that takes a
9442     // single void argument.
9443     // We let through "const void" here because Sema::GetTypeForDeclarator
9444     // already checks for that case.
9445     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9446       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9447         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9448         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9449         Param->setDeclContext(NewFD);
9450         Params.push_back(Param);
9451 
9452         if (Param->isInvalidDecl())
9453           NewFD->setInvalidDecl();
9454       }
9455     }
9456 
9457     if (!getLangOpts().CPlusPlus) {
9458       // In C, find all the tag declarations from the prototype and move them
9459       // into the function DeclContext. Remove them from the surrounding tag
9460       // injection context of the function, which is typically but not always
9461       // the TU.
9462       DeclContext *PrototypeTagContext =
9463           getTagInjectionContext(NewFD->getLexicalDeclContext());
9464       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9465         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9466 
9467         // We don't want to reparent enumerators. Look at their parent enum
9468         // instead.
9469         if (!TD) {
9470           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9471             TD = cast<EnumDecl>(ECD->getDeclContext());
9472         }
9473         if (!TD)
9474           continue;
9475         DeclContext *TagDC = TD->getLexicalDeclContext();
9476         if (!TagDC->containsDecl(TD))
9477           continue;
9478         TagDC->removeDecl(TD);
9479         TD->setDeclContext(NewFD);
9480         NewFD->addDecl(TD);
9481 
9482         // Preserve the lexical DeclContext if it is not the surrounding tag
9483         // injection context of the FD. In this example, the semantic context of
9484         // E will be f and the lexical context will be S, while both the
9485         // semantic and lexical contexts of S will be f:
9486         //   void f(struct S { enum E { a } f; } s);
9487         if (TagDC != PrototypeTagContext)
9488           TD->setLexicalDeclContext(TagDC);
9489       }
9490     }
9491   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9492     // When we're declaring a function with a typedef, typeof, etc as in the
9493     // following example, we'll need to synthesize (unnamed)
9494     // parameters for use in the declaration.
9495     //
9496     // @code
9497     // typedef void fn(int);
9498     // fn f;
9499     // @endcode
9500 
9501     // Synthesize a parameter for each argument type.
9502     for (const auto &AI : FT->param_types()) {
9503       ParmVarDecl *Param =
9504           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9505       Param->setScopeInfo(0, Params.size());
9506       Params.push_back(Param);
9507     }
9508   } else {
9509     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9510            "Should not need args for typedef of non-prototype fn");
9511   }
9512 
9513   // Finally, we know we have the right number of parameters, install them.
9514   NewFD->setParams(Params);
9515 
9516   if (D.getDeclSpec().isNoreturnSpecified())
9517     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9518                                            D.getDeclSpec().getNoreturnSpecLoc(),
9519                                            AttributeCommonInfo::AS_Keyword));
9520 
9521   // Functions returning a variably modified type violate C99 6.7.5.2p2
9522   // because all functions have linkage.
9523   if (!NewFD->isInvalidDecl() &&
9524       NewFD->getReturnType()->isVariablyModifiedType()) {
9525     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9526     NewFD->setInvalidDecl();
9527   }
9528 
9529   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9530   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9531       !NewFD->hasAttr<SectionAttr>())
9532     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9533         Context, PragmaClangTextSection.SectionName,
9534         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9535 
9536   // Apply an implicit SectionAttr if #pragma code_seg is active.
9537   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9538       !NewFD->hasAttr<SectionAttr>()) {
9539     NewFD->addAttr(SectionAttr::CreateImplicit(
9540         Context, CodeSegStack.CurrentValue->getString(),
9541         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9542         SectionAttr::Declspec_allocate));
9543     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9544                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9545                          ASTContext::PSF_Read,
9546                      NewFD))
9547       NewFD->dropAttr<SectionAttr>();
9548   }
9549 
9550   // Apply an implicit CodeSegAttr from class declspec or
9551   // apply an implicit SectionAttr from #pragma code_seg if active.
9552   if (!NewFD->hasAttr<CodeSegAttr>()) {
9553     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9554                                                                  D.isFunctionDefinition())) {
9555       NewFD->addAttr(SAttr);
9556     }
9557   }
9558 
9559   // Handle attributes.
9560   ProcessDeclAttributes(S, NewFD, D);
9561 
9562   if (getLangOpts().OpenCL) {
9563     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9564     // type declaration will generate a compilation error.
9565     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9566     if (AddressSpace != LangAS::Default) {
9567       Diag(NewFD->getLocation(),
9568            diag::err_opencl_return_value_with_address_space);
9569       NewFD->setInvalidDecl();
9570     }
9571   }
9572 
9573   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9574     checkDeviceDecl(NewFD, D.getBeginLoc());
9575 
9576   if (!getLangOpts().CPlusPlus) {
9577     // Perform semantic checking on the function declaration.
9578     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9579       CheckMain(NewFD, D.getDeclSpec());
9580 
9581     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9582       CheckMSVCRTEntryPoint(NewFD);
9583 
9584     if (!NewFD->isInvalidDecl())
9585       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9586                                                   isMemberSpecialization));
9587     else if (!Previous.empty())
9588       // Recover gracefully from an invalid redeclaration.
9589       D.setRedeclaration(true);
9590     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9591             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9592            "previous declaration set still overloaded");
9593 
9594     // Diagnose no-prototype function declarations with calling conventions that
9595     // don't support variadic calls. Only do this in C and do it after merging
9596     // possibly prototyped redeclarations.
9597     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9598     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9599       CallingConv CC = FT->getExtInfo().getCC();
9600       if (!supportsVariadicCall(CC)) {
9601         // Windows system headers sometimes accidentally use stdcall without
9602         // (void) parameters, so we relax this to a warning.
9603         int DiagID =
9604             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9605         Diag(NewFD->getLocation(), DiagID)
9606             << FunctionType::getNameForCallConv(CC);
9607       }
9608     }
9609 
9610    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9611        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9612      checkNonTrivialCUnion(NewFD->getReturnType(),
9613                            NewFD->getReturnTypeSourceRange().getBegin(),
9614                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9615   } else {
9616     // C++11 [replacement.functions]p3:
9617     //  The program's definitions shall not be specified as inline.
9618     //
9619     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9620     //
9621     // Suppress the diagnostic if the function is __attribute__((used)), since
9622     // that forces an external definition to be emitted.
9623     if (D.getDeclSpec().isInlineSpecified() &&
9624         NewFD->isReplaceableGlobalAllocationFunction() &&
9625         !NewFD->hasAttr<UsedAttr>())
9626       Diag(D.getDeclSpec().getInlineSpecLoc(),
9627            diag::ext_operator_new_delete_declared_inline)
9628         << NewFD->getDeclName();
9629 
9630     // If the declarator is a template-id, translate the parser's template
9631     // argument list into our AST format.
9632     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9633       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9634       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9635       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9636       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9637                                          TemplateId->NumArgs);
9638       translateTemplateArguments(TemplateArgsPtr,
9639                                  TemplateArgs);
9640 
9641       HasExplicitTemplateArgs = true;
9642 
9643       if (NewFD->isInvalidDecl()) {
9644         HasExplicitTemplateArgs = false;
9645       } else if (FunctionTemplate) {
9646         // Function template with explicit template arguments.
9647         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9648           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9649 
9650         HasExplicitTemplateArgs = false;
9651       } else {
9652         assert((isFunctionTemplateSpecialization ||
9653                 D.getDeclSpec().isFriendSpecified()) &&
9654                "should have a 'template<>' for this decl");
9655         // "friend void foo<>(int);" is an implicit specialization decl.
9656         isFunctionTemplateSpecialization = true;
9657       }
9658     } else if (isFriend && isFunctionTemplateSpecialization) {
9659       // This combination is only possible in a recovery case;  the user
9660       // wrote something like:
9661       //   template <> friend void foo(int);
9662       // which we're recovering from as if the user had written:
9663       //   friend void foo<>(int);
9664       // Go ahead and fake up a template id.
9665       HasExplicitTemplateArgs = true;
9666       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9667       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9668     }
9669 
9670     // We do not add HD attributes to specializations here because
9671     // they may have different constexpr-ness compared to their
9672     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9673     // may end up with different effective targets. Instead, a
9674     // specialization inherits its target attributes from its template
9675     // in the CheckFunctionTemplateSpecialization() call below.
9676     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9677       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9678 
9679     // If it's a friend (and only if it's a friend), it's possible
9680     // that either the specialized function type or the specialized
9681     // template is dependent, and therefore matching will fail.  In
9682     // this case, don't check the specialization yet.
9683     if (isFunctionTemplateSpecialization && isFriend &&
9684         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9685          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9686              TemplateArgs.arguments()))) {
9687       assert(HasExplicitTemplateArgs &&
9688              "friend function specialization without template args");
9689       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9690                                                        Previous))
9691         NewFD->setInvalidDecl();
9692     } else if (isFunctionTemplateSpecialization) {
9693       if (CurContext->isDependentContext() && CurContext->isRecord()
9694           && !isFriend) {
9695         isDependentClassScopeExplicitSpecialization = true;
9696       } else if (!NewFD->isInvalidDecl() &&
9697                  CheckFunctionTemplateSpecialization(
9698                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9699                      Previous))
9700         NewFD->setInvalidDecl();
9701 
9702       // C++ [dcl.stc]p1:
9703       //   A storage-class-specifier shall not be specified in an explicit
9704       //   specialization (14.7.3)
9705       FunctionTemplateSpecializationInfo *Info =
9706           NewFD->getTemplateSpecializationInfo();
9707       if (Info && SC != SC_None) {
9708         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9709           Diag(NewFD->getLocation(),
9710                diag::err_explicit_specialization_inconsistent_storage_class)
9711             << SC
9712             << FixItHint::CreateRemoval(
9713                                       D.getDeclSpec().getStorageClassSpecLoc());
9714 
9715         else
9716           Diag(NewFD->getLocation(),
9717                diag::ext_explicit_specialization_storage_class)
9718             << FixItHint::CreateRemoval(
9719                                       D.getDeclSpec().getStorageClassSpecLoc());
9720       }
9721     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9722       if (CheckMemberSpecialization(NewFD, Previous))
9723           NewFD->setInvalidDecl();
9724     }
9725 
9726     // Perform semantic checking on the function declaration.
9727     if (!isDependentClassScopeExplicitSpecialization) {
9728       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9729         CheckMain(NewFD, D.getDeclSpec());
9730 
9731       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9732         CheckMSVCRTEntryPoint(NewFD);
9733 
9734       if (!NewFD->isInvalidDecl())
9735         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9736                                                     isMemberSpecialization));
9737       else if (!Previous.empty())
9738         // Recover gracefully from an invalid redeclaration.
9739         D.setRedeclaration(true);
9740     }
9741 
9742     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9743             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9744            "previous declaration set still overloaded");
9745 
9746     NamedDecl *PrincipalDecl = (FunctionTemplate
9747                                 ? cast<NamedDecl>(FunctionTemplate)
9748                                 : NewFD);
9749 
9750     if (isFriend && NewFD->getPreviousDecl()) {
9751       AccessSpecifier Access = AS_public;
9752       if (!NewFD->isInvalidDecl())
9753         Access = NewFD->getPreviousDecl()->getAccess();
9754 
9755       NewFD->setAccess(Access);
9756       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9757     }
9758 
9759     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9760         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9761       PrincipalDecl->setNonMemberOperator();
9762 
9763     // If we have a function template, check the template parameter
9764     // list. This will check and merge default template arguments.
9765     if (FunctionTemplate) {
9766       FunctionTemplateDecl *PrevTemplate =
9767                                      FunctionTemplate->getPreviousDecl();
9768       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9769                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9770                                     : nullptr,
9771                             D.getDeclSpec().isFriendSpecified()
9772                               ? (D.isFunctionDefinition()
9773                                    ? TPC_FriendFunctionTemplateDefinition
9774                                    : TPC_FriendFunctionTemplate)
9775                               : (D.getCXXScopeSpec().isSet() &&
9776                                  DC && DC->isRecord() &&
9777                                  DC->isDependentContext())
9778                                   ? TPC_ClassTemplateMember
9779                                   : TPC_FunctionTemplate);
9780     }
9781 
9782     if (NewFD->isInvalidDecl()) {
9783       // Ignore all the rest of this.
9784     } else if (!D.isRedeclaration()) {
9785       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9786                                        AddToScope };
9787       // Fake up an access specifier if it's supposed to be a class member.
9788       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9789         NewFD->setAccess(AS_public);
9790 
9791       // Qualified decls generally require a previous declaration.
9792       if (D.getCXXScopeSpec().isSet()) {
9793         // ...with the major exception of templated-scope or
9794         // dependent-scope friend declarations.
9795 
9796         // TODO: we currently also suppress this check in dependent
9797         // contexts because (1) the parameter depth will be off when
9798         // matching friend templates and (2) we might actually be
9799         // selecting a friend based on a dependent factor.  But there
9800         // are situations where these conditions don't apply and we
9801         // can actually do this check immediately.
9802         //
9803         // Unless the scope is dependent, it's always an error if qualified
9804         // redeclaration lookup found nothing at all. Diagnose that now;
9805         // nothing will diagnose that error later.
9806         if (isFriend &&
9807             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9808              (!Previous.empty() && CurContext->isDependentContext()))) {
9809           // ignore these
9810         } else if (NewFD->isCPUDispatchMultiVersion() ||
9811                    NewFD->isCPUSpecificMultiVersion()) {
9812           // ignore this, we allow the redeclaration behavior here to create new
9813           // versions of the function.
9814         } else {
9815           // The user tried to provide an out-of-line definition for a
9816           // function that is a member of a class or namespace, but there
9817           // was no such member function declared (C++ [class.mfct]p2,
9818           // C++ [namespace.memdef]p2). For example:
9819           //
9820           // class X {
9821           //   void f() const;
9822           // };
9823           //
9824           // void X::f() { } // ill-formed
9825           //
9826           // Complain about this problem, and attempt to suggest close
9827           // matches (e.g., those that differ only in cv-qualifiers and
9828           // whether the parameter types are references).
9829 
9830           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9831                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9832             AddToScope = ExtraArgs.AddToScope;
9833             return Result;
9834           }
9835         }
9836 
9837         // Unqualified local friend declarations are required to resolve
9838         // to something.
9839       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9840         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9841                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9842           AddToScope = ExtraArgs.AddToScope;
9843           return Result;
9844         }
9845       }
9846     } else if (!D.isFunctionDefinition() &&
9847                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9848                !isFriend && !isFunctionTemplateSpecialization &&
9849                !isMemberSpecialization) {
9850       // An out-of-line member function declaration must also be a
9851       // definition (C++ [class.mfct]p2).
9852       // Note that this is not the case for explicit specializations of
9853       // function templates or member functions of class templates, per
9854       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9855       // extension for compatibility with old SWIG code which likes to
9856       // generate them.
9857       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9858         << D.getCXXScopeSpec().getRange();
9859     }
9860   }
9861 
9862   // If this is the first declaration of a library builtin function, add
9863   // attributes as appropriate.
9864   if (!D.isRedeclaration() &&
9865       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9866     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9867       if (unsigned BuiltinID = II->getBuiltinID()) {
9868         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9869           // Validate the type matches unless this builtin is specified as
9870           // matching regardless of its declared type.
9871           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9872             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9873           } else {
9874             ASTContext::GetBuiltinTypeError Error;
9875             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9876             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9877 
9878             if (!Error && !BuiltinType.isNull() &&
9879                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9880                     NewFD->getType(), BuiltinType))
9881               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9882           }
9883         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9884                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9885           // FIXME: We should consider this a builtin only in the std namespace.
9886           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9887         }
9888       }
9889     }
9890   }
9891 
9892   ProcessPragmaWeak(S, NewFD);
9893   checkAttributesAfterMerging(*this, *NewFD);
9894 
9895   AddKnownFunctionAttributes(NewFD);
9896 
9897   if (NewFD->hasAttr<OverloadableAttr>() &&
9898       !NewFD->getType()->getAs<FunctionProtoType>()) {
9899     Diag(NewFD->getLocation(),
9900          diag::err_attribute_overloadable_no_prototype)
9901       << NewFD;
9902 
9903     // Turn this into a variadic function with no parameters.
9904     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9905     FunctionProtoType::ExtProtoInfo EPI(
9906         Context.getDefaultCallingConvention(true, false));
9907     EPI.Variadic = true;
9908     EPI.ExtInfo = FT->getExtInfo();
9909 
9910     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9911     NewFD->setType(R);
9912   }
9913 
9914   // If there's a #pragma GCC visibility in scope, and this isn't a class
9915   // member, set the visibility of this function.
9916   if (!DC->isRecord() && NewFD->isExternallyVisible())
9917     AddPushedVisibilityAttribute(NewFD);
9918 
9919   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9920   // marking the function.
9921   AddCFAuditedAttribute(NewFD);
9922 
9923   // If this is a function definition, check if we have to apply optnone due to
9924   // a pragma.
9925   if(D.isFunctionDefinition())
9926     AddRangeBasedOptnone(NewFD);
9927 
9928   // If this is the first declaration of an extern C variable, update
9929   // the map of such variables.
9930   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9931       isIncompleteDeclExternC(*this, NewFD))
9932     RegisterLocallyScopedExternCDecl(NewFD, S);
9933 
9934   // Set this FunctionDecl's range up to the right paren.
9935   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9936 
9937   if (D.isRedeclaration() && !Previous.empty()) {
9938     NamedDecl *Prev = Previous.getRepresentativeDecl();
9939     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9940                                    isMemberSpecialization ||
9941                                        isFunctionTemplateSpecialization,
9942                                    D.isFunctionDefinition());
9943   }
9944 
9945   if (getLangOpts().CUDA) {
9946     IdentifierInfo *II = NewFD->getIdentifier();
9947     if (II && II->isStr(getCudaConfigureFuncName()) &&
9948         !NewFD->isInvalidDecl() &&
9949         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9950       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9951         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9952             << getCudaConfigureFuncName();
9953       Context.setcudaConfigureCallDecl(NewFD);
9954     }
9955 
9956     // Variadic functions, other than a *declaration* of printf, are not allowed
9957     // in device-side CUDA code, unless someone passed
9958     // -fcuda-allow-variadic-functions.
9959     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9960         (NewFD->hasAttr<CUDADeviceAttr>() ||
9961          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9962         !(II && II->isStr("printf") && NewFD->isExternC() &&
9963           !D.isFunctionDefinition())) {
9964       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9965     }
9966   }
9967 
9968   MarkUnusedFileScopedDecl(NewFD);
9969 
9970 
9971 
9972   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9973     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9974     if (SC == SC_Static) {
9975       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9976       D.setInvalidType();
9977     }
9978 
9979     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9980     if (!NewFD->getReturnType()->isVoidType()) {
9981       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9982       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9983           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9984                                 : FixItHint());
9985       D.setInvalidType();
9986     }
9987 
9988     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9989     for (auto Param : NewFD->parameters())
9990       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9991 
9992     if (getLangOpts().OpenCLCPlusPlus) {
9993       if (DC->isRecord()) {
9994         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9995         D.setInvalidType();
9996       }
9997       if (FunctionTemplate) {
9998         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9999         D.setInvalidType();
10000       }
10001     }
10002   }
10003 
10004   if (getLangOpts().CPlusPlus) {
10005     if (FunctionTemplate) {
10006       if (NewFD->isInvalidDecl())
10007         FunctionTemplate->setInvalidDecl();
10008       return FunctionTemplate;
10009     }
10010 
10011     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10012       CompleteMemberSpecialization(NewFD, Previous);
10013   }
10014 
10015   for (const ParmVarDecl *Param : NewFD->parameters()) {
10016     QualType PT = Param->getType();
10017 
10018     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10019     // types.
10020     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10021       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10022         QualType ElemTy = PipeTy->getElementType();
10023           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10024             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10025             D.setInvalidType();
10026           }
10027       }
10028     }
10029   }
10030 
10031   // Here we have an function template explicit specialization at class scope.
10032   // The actual specialization will be postponed to template instatiation
10033   // time via the ClassScopeFunctionSpecializationDecl node.
10034   if (isDependentClassScopeExplicitSpecialization) {
10035     ClassScopeFunctionSpecializationDecl *NewSpec =
10036                          ClassScopeFunctionSpecializationDecl::Create(
10037                                 Context, CurContext, NewFD->getLocation(),
10038                                 cast<CXXMethodDecl>(NewFD),
10039                                 HasExplicitTemplateArgs, TemplateArgs);
10040     CurContext->addDecl(NewSpec);
10041     AddToScope = false;
10042   }
10043 
10044   // Diagnose availability attributes. Availability cannot be used on functions
10045   // that are run during load/unload.
10046   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10047     if (NewFD->hasAttr<ConstructorAttr>()) {
10048       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10049           << 1;
10050       NewFD->dropAttr<AvailabilityAttr>();
10051     }
10052     if (NewFD->hasAttr<DestructorAttr>()) {
10053       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10054           << 2;
10055       NewFD->dropAttr<AvailabilityAttr>();
10056     }
10057   }
10058 
10059   // Diagnose no_builtin attribute on function declaration that are not a
10060   // definition.
10061   // FIXME: We should really be doing this in
10062   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10063   // the FunctionDecl and at this point of the code
10064   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10065   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10066   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10067     switch (D.getFunctionDefinitionKind()) {
10068     case FunctionDefinitionKind::Defaulted:
10069     case FunctionDefinitionKind::Deleted:
10070       Diag(NBA->getLocation(),
10071            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10072           << NBA->getSpelling();
10073       break;
10074     case FunctionDefinitionKind::Declaration:
10075       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10076           << NBA->getSpelling();
10077       break;
10078     case FunctionDefinitionKind::Definition:
10079       break;
10080     }
10081 
10082   return NewFD;
10083 }
10084 
10085 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10086 /// when __declspec(code_seg) "is applied to a class, all member functions of
10087 /// the class and nested classes -- this includes compiler-generated special
10088 /// member functions -- are put in the specified segment."
10089 /// The actual behavior is a little more complicated. The Microsoft compiler
10090 /// won't check outer classes if there is an active value from #pragma code_seg.
10091 /// The CodeSeg is always applied from the direct parent but only from outer
10092 /// classes when the #pragma code_seg stack is empty. See:
10093 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10094 /// available since MS has removed the page.
10095 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10096   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10097   if (!Method)
10098     return nullptr;
10099   const CXXRecordDecl *Parent = Method->getParent();
10100   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10101     Attr *NewAttr = SAttr->clone(S.getASTContext());
10102     NewAttr->setImplicit(true);
10103     return NewAttr;
10104   }
10105 
10106   // The Microsoft compiler won't check outer classes for the CodeSeg
10107   // when the #pragma code_seg stack is active.
10108   if (S.CodeSegStack.CurrentValue)
10109    return nullptr;
10110 
10111   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10112     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10113       Attr *NewAttr = SAttr->clone(S.getASTContext());
10114       NewAttr->setImplicit(true);
10115       return NewAttr;
10116     }
10117   }
10118   return nullptr;
10119 }
10120 
10121 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10122 /// containing class. Otherwise it will return implicit SectionAttr if the
10123 /// function is a definition and there is an active value on CodeSegStack
10124 /// (from the current #pragma code-seg value).
10125 ///
10126 /// \param FD Function being declared.
10127 /// \param IsDefinition Whether it is a definition or just a declarartion.
10128 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10129 ///          nullptr if no attribute should be added.
10130 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10131                                                        bool IsDefinition) {
10132   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10133     return A;
10134   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10135       CodeSegStack.CurrentValue)
10136     return SectionAttr::CreateImplicit(
10137         getASTContext(), CodeSegStack.CurrentValue->getString(),
10138         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10139         SectionAttr::Declspec_allocate);
10140   return nullptr;
10141 }
10142 
10143 /// Determines if we can perform a correct type check for \p D as a
10144 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10145 /// best-effort check.
10146 ///
10147 /// \param NewD The new declaration.
10148 /// \param OldD The old declaration.
10149 /// \param NewT The portion of the type of the new declaration to check.
10150 /// \param OldT The portion of the type of the old declaration to check.
10151 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10152                                           QualType NewT, QualType OldT) {
10153   if (!NewD->getLexicalDeclContext()->isDependentContext())
10154     return true;
10155 
10156   // For dependently-typed local extern declarations and friends, we can't
10157   // perform a correct type check in general until instantiation:
10158   //
10159   //   int f();
10160   //   template<typename T> void g() { T f(); }
10161   //
10162   // (valid if g() is only instantiated with T = int).
10163   if (NewT->isDependentType() &&
10164       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10165     return false;
10166 
10167   // Similarly, if the previous declaration was a dependent local extern
10168   // declaration, we don't really know its type yet.
10169   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10170     return false;
10171 
10172   return true;
10173 }
10174 
10175 /// Checks if the new declaration declared in dependent context must be
10176 /// put in the same redeclaration chain as the specified declaration.
10177 ///
10178 /// \param D Declaration that is checked.
10179 /// \param PrevDecl Previous declaration found with proper lookup method for the
10180 ///                 same declaration name.
10181 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10182 ///          belongs to.
10183 ///
10184 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10185   if (!D->getLexicalDeclContext()->isDependentContext())
10186     return true;
10187 
10188   // Don't chain dependent friend function definitions until instantiation, to
10189   // permit cases like
10190   //
10191   //   void func();
10192   //   template<typename T> class C1 { friend void func() {} };
10193   //   template<typename T> class C2 { friend void func() {} };
10194   //
10195   // ... which is valid if only one of C1 and C2 is ever instantiated.
10196   //
10197   // FIXME: This need only apply to function definitions. For now, we proxy
10198   // this by checking for a file-scope function. We do not want this to apply
10199   // to friend declarations nominating member functions, because that gets in
10200   // the way of access checks.
10201   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10202     return false;
10203 
10204   auto *VD = dyn_cast<ValueDecl>(D);
10205   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10206   return !VD || !PrevVD ||
10207          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10208                                         PrevVD->getType());
10209 }
10210 
10211 /// Check the target attribute of the function for MultiVersion
10212 /// validity.
10213 ///
10214 /// Returns true if there was an error, false otherwise.
10215 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10216   const auto *TA = FD->getAttr<TargetAttr>();
10217   assert(TA && "MultiVersion Candidate requires a target attribute");
10218   ParsedTargetAttr ParseInfo = TA->parse();
10219   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10220   enum ErrType { Feature = 0, Architecture = 1 };
10221 
10222   if (!ParseInfo.Architecture.empty() &&
10223       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10224     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10225         << Architecture << ParseInfo.Architecture;
10226     return true;
10227   }
10228 
10229   for (const auto &Feat : ParseInfo.Features) {
10230     auto BareFeat = StringRef{Feat}.substr(1);
10231     if (Feat[0] == '-') {
10232       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10233           << Feature << ("no-" + BareFeat).str();
10234       return true;
10235     }
10236 
10237     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10238         !TargetInfo.isValidFeatureName(BareFeat)) {
10239       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10240           << Feature << BareFeat;
10241       return true;
10242     }
10243   }
10244   return false;
10245 }
10246 
10247 // Provide a white-list of attributes that are allowed to be combined with
10248 // multiversion functions.
10249 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10250                                            MultiVersionKind MVType) {
10251   // Note: this list/diagnosis must match the list in
10252   // checkMultiversionAttributesAllSame.
10253   switch (Kind) {
10254   default:
10255     return false;
10256   case attr::Used:
10257     return MVType == MultiVersionKind::Target;
10258   case attr::NonNull:
10259   case attr::NoThrow:
10260     return true;
10261   }
10262 }
10263 
10264 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10265                                                  const FunctionDecl *FD,
10266                                                  const FunctionDecl *CausedFD,
10267                                                  MultiVersionKind MVType) {
10268   bool IsCPUSpecificCPUDispatchMVType =
10269       MVType == MultiVersionKind::CPUDispatch ||
10270       MVType == MultiVersionKind::CPUSpecific;
10271   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10272                             Sema &S, const Attr *A) {
10273     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10274         << IsCPUSpecificCPUDispatchMVType << A;
10275     if (CausedFD)
10276       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10277     return true;
10278   };
10279 
10280   for (const Attr *A : FD->attrs()) {
10281     switch (A->getKind()) {
10282     case attr::CPUDispatch:
10283     case attr::CPUSpecific:
10284       if (MVType != MultiVersionKind::CPUDispatch &&
10285           MVType != MultiVersionKind::CPUSpecific)
10286         return Diagnose(S, A);
10287       break;
10288     case attr::Target:
10289       if (MVType != MultiVersionKind::Target)
10290         return Diagnose(S, A);
10291       break;
10292     default:
10293       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10294         return Diagnose(S, A);
10295       break;
10296     }
10297   }
10298   return false;
10299 }
10300 
10301 bool Sema::areMultiversionVariantFunctionsCompatible(
10302     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10303     const PartialDiagnostic &NoProtoDiagID,
10304     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10305     const PartialDiagnosticAt &NoSupportDiagIDAt,
10306     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10307     bool ConstexprSupported, bool CLinkageMayDiffer) {
10308   enum DoesntSupport {
10309     FuncTemplates = 0,
10310     VirtFuncs = 1,
10311     DeducedReturn = 2,
10312     Constructors = 3,
10313     Destructors = 4,
10314     DeletedFuncs = 5,
10315     DefaultedFuncs = 6,
10316     ConstexprFuncs = 7,
10317     ConstevalFuncs = 8,
10318   };
10319   enum Different {
10320     CallingConv = 0,
10321     ReturnType = 1,
10322     ConstexprSpec = 2,
10323     InlineSpec = 3,
10324     Linkage = 4,
10325     LanguageLinkage = 5,
10326   };
10327 
10328   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10329       !OldFD->getType()->getAs<FunctionProtoType>()) {
10330     Diag(OldFD->getLocation(), NoProtoDiagID);
10331     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10332     return true;
10333   }
10334 
10335   if (NoProtoDiagID.getDiagID() != 0 &&
10336       !NewFD->getType()->getAs<FunctionProtoType>())
10337     return Diag(NewFD->getLocation(), NoProtoDiagID);
10338 
10339   if (!TemplatesSupported &&
10340       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10341     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10342            << FuncTemplates;
10343 
10344   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10345     if (NewCXXFD->isVirtual())
10346       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10347              << VirtFuncs;
10348 
10349     if (isa<CXXConstructorDecl>(NewCXXFD))
10350       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10351              << Constructors;
10352 
10353     if (isa<CXXDestructorDecl>(NewCXXFD))
10354       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10355              << Destructors;
10356   }
10357 
10358   if (NewFD->isDeleted())
10359     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10360            << DeletedFuncs;
10361 
10362   if (NewFD->isDefaulted())
10363     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10364            << DefaultedFuncs;
10365 
10366   if (!ConstexprSupported && NewFD->isConstexpr())
10367     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10368            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10369 
10370   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10371   const auto *NewType = cast<FunctionType>(NewQType);
10372   QualType NewReturnType = NewType->getReturnType();
10373 
10374   if (NewReturnType->isUndeducedType())
10375     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10376            << DeducedReturn;
10377 
10378   // Ensure the return type is identical.
10379   if (OldFD) {
10380     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10381     const auto *OldType = cast<FunctionType>(OldQType);
10382     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10383     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10384 
10385     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10386       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10387 
10388     QualType OldReturnType = OldType->getReturnType();
10389 
10390     if (OldReturnType != NewReturnType)
10391       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10392 
10393     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10394       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10395 
10396     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10397       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10398 
10399     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10400       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10401 
10402     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10403       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10404 
10405     if (CheckEquivalentExceptionSpec(
10406             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10407             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10408       return true;
10409   }
10410   return false;
10411 }
10412 
10413 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10414                                              const FunctionDecl *NewFD,
10415                                              bool CausesMV,
10416                                              MultiVersionKind MVType) {
10417   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10418     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10419     if (OldFD)
10420       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10421     return true;
10422   }
10423 
10424   bool IsCPUSpecificCPUDispatchMVType =
10425       MVType == MultiVersionKind::CPUDispatch ||
10426       MVType == MultiVersionKind::CPUSpecific;
10427 
10428   if (CausesMV && OldFD &&
10429       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10430     return true;
10431 
10432   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10433     return true;
10434 
10435   // Only allow transition to MultiVersion if it hasn't been used.
10436   if (OldFD && CausesMV && OldFD->isUsed(false))
10437     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10438 
10439   return S.areMultiversionVariantFunctionsCompatible(
10440       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10441       PartialDiagnosticAt(NewFD->getLocation(),
10442                           S.PDiag(diag::note_multiversioning_caused_here)),
10443       PartialDiagnosticAt(NewFD->getLocation(),
10444                           S.PDiag(diag::err_multiversion_doesnt_support)
10445                               << IsCPUSpecificCPUDispatchMVType),
10446       PartialDiagnosticAt(NewFD->getLocation(),
10447                           S.PDiag(diag::err_multiversion_diff)),
10448       /*TemplatesSupported=*/false,
10449       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10450       /*CLinkageMayDiffer=*/false);
10451 }
10452 
10453 /// Check the validity of a multiversion function declaration that is the
10454 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10455 ///
10456 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10457 ///
10458 /// Returns true if there was an error, false otherwise.
10459 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10460                                            MultiVersionKind MVType,
10461                                            const TargetAttr *TA) {
10462   assert(MVType != MultiVersionKind::None &&
10463          "Function lacks multiversion attribute");
10464 
10465   // Target only causes MV if it is default, otherwise this is a normal
10466   // function.
10467   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10468     return false;
10469 
10470   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10471     FD->setInvalidDecl();
10472     return true;
10473   }
10474 
10475   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10476     FD->setInvalidDecl();
10477     return true;
10478   }
10479 
10480   FD->setIsMultiVersion();
10481   return false;
10482 }
10483 
10484 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10485   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10486     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10487       return true;
10488   }
10489 
10490   return false;
10491 }
10492 
10493 static bool CheckTargetCausesMultiVersioning(
10494     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10495     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10496     LookupResult &Previous) {
10497   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10498   ParsedTargetAttr NewParsed = NewTA->parse();
10499   // Sort order doesn't matter, it just needs to be consistent.
10500   llvm::sort(NewParsed.Features);
10501 
10502   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10503   // to change, this is a simple redeclaration.
10504   if (!NewTA->isDefaultVersion() &&
10505       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10506     return false;
10507 
10508   // Otherwise, this decl causes MultiVersioning.
10509   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10510     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10511     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10512     NewFD->setInvalidDecl();
10513     return true;
10514   }
10515 
10516   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10517                                        MultiVersionKind::Target)) {
10518     NewFD->setInvalidDecl();
10519     return true;
10520   }
10521 
10522   if (CheckMultiVersionValue(S, NewFD)) {
10523     NewFD->setInvalidDecl();
10524     return true;
10525   }
10526 
10527   // If this is 'default', permit the forward declaration.
10528   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10529     Redeclaration = true;
10530     OldDecl = OldFD;
10531     OldFD->setIsMultiVersion();
10532     NewFD->setIsMultiVersion();
10533     return false;
10534   }
10535 
10536   if (CheckMultiVersionValue(S, OldFD)) {
10537     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10538     NewFD->setInvalidDecl();
10539     return true;
10540   }
10541 
10542   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10543 
10544   if (OldParsed == NewParsed) {
10545     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10546     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10547     NewFD->setInvalidDecl();
10548     return true;
10549   }
10550 
10551   for (const auto *FD : OldFD->redecls()) {
10552     const auto *CurTA = FD->getAttr<TargetAttr>();
10553     // We allow forward declarations before ANY multiversioning attributes, but
10554     // nothing after the fact.
10555     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10556         (!CurTA || CurTA->isInherited())) {
10557       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10558           << 0;
10559       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10560       NewFD->setInvalidDecl();
10561       return true;
10562     }
10563   }
10564 
10565   OldFD->setIsMultiVersion();
10566   NewFD->setIsMultiVersion();
10567   Redeclaration = false;
10568   MergeTypeWithPrevious = false;
10569   OldDecl = nullptr;
10570   Previous.clear();
10571   return false;
10572 }
10573 
10574 /// Check the validity of a new function declaration being added to an existing
10575 /// multiversioned declaration collection.
10576 static bool CheckMultiVersionAdditionalDecl(
10577     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10578     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10579     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10580     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10581     LookupResult &Previous) {
10582 
10583   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10584   // Disallow mixing of multiversioning types.
10585   if ((OldMVType == MultiVersionKind::Target &&
10586        NewMVType != MultiVersionKind::Target) ||
10587       (NewMVType == MultiVersionKind::Target &&
10588        OldMVType != MultiVersionKind::Target)) {
10589     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10590     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10591     NewFD->setInvalidDecl();
10592     return true;
10593   }
10594 
10595   ParsedTargetAttr NewParsed;
10596   if (NewTA) {
10597     NewParsed = NewTA->parse();
10598     llvm::sort(NewParsed.Features);
10599   }
10600 
10601   bool UseMemberUsingDeclRules =
10602       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10603 
10604   // Next, check ALL non-overloads to see if this is a redeclaration of a
10605   // previous member of the MultiVersion set.
10606   for (NamedDecl *ND : Previous) {
10607     FunctionDecl *CurFD = ND->getAsFunction();
10608     if (!CurFD)
10609       continue;
10610     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10611       continue;
10612 
10613     if (NewMVType == MultiVersionKind::Target) {
10614       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10615       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10616         NewFD->setIsMultiVersion();
10617         Redeclaration = true;
10618         OldDecl = ND;
10619         return false;
10620       }
10621 
10622       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10623       if (CurParsed == NewParsed) {
10624         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10625         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10626         NewFD->setInvalidDecl();
10627         return true;
10628       }
10629     } else {
10630       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10631       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10632       // Handle CPUDispatch/CPUSpecific versions.
10633       // Only 1 CPUDispatch function is allowed, this will make it go through
10634       // the redeclaration errors.
10635       if (NewMVType == MultiVersionKind::CPUDispatch &&
10636           CurFD->hasAttr<CPUDispatchAttr>()) {
10637         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10638             std::equal(
10639                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10640                 NewCPUDisp->cpus_begin(),
10641                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10642                   return Cur->getName() == New->getName();
10643                 })) {
10644           NewFD->setIsMultiVersion();
10645           Redeclaration = true;
10646           OldDecl = ND;
10647           return false;
10648         }
10649 
10650         // If the declarations don't match, this is an error condition.
10651         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10652         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10653         NewFD->setInvalidDecl();
10654         return true;
10655       }
10656       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10657 
10658         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10659             std::equal(
10660                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10661                 NewCPUSpec->cpus_begin(),
10662                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10663                   return Cur->getName() == New->getName();
10664                 })) {
10665           NewFD->setIsMultiVersion();
10666           Redeclaration = true;
10667           OldDecl = ND;
10668           return false;
10669         }
10670 
10671         // Only 1 version of CPUSpecific is allowed for each CPU.
10672         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10673           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10674             if (CurII == NewII) {
10675               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10676                   << NewII;
10677               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10678               NewFD->setInvalidDecl();
10679               return true;
10680             }
10681           }
10682         }
10683       }
10684       // If the two decls aren't the same MVType, there is no possible error
10685       // condition.
10686     }
10687   }
10688 
10689   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10690   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10691   // handled in the attribute adding step.
10692   if (NewMVType == MultiVersionKind::Target &&
10693       CheckMultiVersionValue(S, NewFD)) {
10694     NewFD->setInvalidDecl();
10695     return true;
10696   }
10697 
10698   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10699                                        !OldFD->isMultiVersion(), NewMVType)) {
10700     NewFD->setInvalidDecl();
10701     return true;
10702   }
10703 
10704   // Permit forward declarations in the case where these two are compatible.
10705   if (!OldFD->isMultiVersion()) {
10706     OldFD->setIsMultiVersion();
10707     NewFD->setIsMultiVersion();
10708     Redeclaration = true;
10709     OldDecl = OldFD;
10710     return false;
10711   }
10712 
10713   NewFD->setIsMultiVersion();
10714   Redeclaration = false;
10715   MergeTypeWithPrevious = false;
10716   OldDecl = nullptr;
10717   Previous.clear();
10718   return false;
10719 }
10720 
10721 
10722 /// Check the validity of a mulitversion function declaration.
10723 /// Also sets the multiversion'ness' of the function itself.
10724 ///
10725 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10726 ///
10727 /// Returns true if there was an error, false otherwise.
10728 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10729                                       bool &Redeclaration, NamedDecl *&OldDecl,
10730                                       bool &MergeTypeWithPrevious,
10731                                       LookupResult &Previous) {
10732   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10733   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10734   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10735 
10736   // Mixing Multiversioning types is prohibited.
10737   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10738       (NewCPUDisp && NewCPUSpec)) {
10739     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10740     NewFD->setInvalidDecl();
10741     return true;
10742   }
10743 
10744   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10745 
10746   // Main isn't allowed to become a multiversion function, however it IS
10747   // permitted to have 'main' be marked with the 'target' optimization hint.
10748   if (NewFD->isMain()) {
10749     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10750         MVType == MultiVersionKind::CPUDispatch ||
10751         MVType == MultiVersionKind::CPUSpecific) {
10752       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10753       NewFD->setInvalidDecl();
10754       return true;
10755     }
10756     return false;
10757   }
10758 
10759   if (!OldDecl || !OldDecl->getAsFunction() ||
10760       OldDecl->getDeclContext()->getRedeclContext() !=
10761           NewFD->getDeclContext()->getRedeclContext()) {
10762     // If there's no previous declaration, AND this isn't attempting to cause
10763     // multiversioning, this isn't an error condition.
10764     if (MVType == MultiVersionKind::None)
10765       return false;
10766     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10767   }
10768 
10769   FunctionDecl *OldFD = OldDecl->getAsFunction();
10770 
10771   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10772     return false;
10773 
10774   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10775     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10776         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10777     NewFD->setInvalidDecl();
10778     return true;
10779   }
10780 
10781   // Handle the target potentially causes multiversioning case.
10782   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10783     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10784                                             Redeclaration, OldDecl,
10785                                             MergeTypeWithPrevious, Previous);
10786 
10787   // At this point, we have a multiversion function decl (in OldFD) AND an
10788   // appropriate attribute in the current function decl.  Resolve that these are
10789   // still compatible with previous declarations.
10790   return CheckMultiVersionAdditionalDecl(
10791       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10792       OldDecl, MergeTypeWithPrevious, Previous);
10793 }
10794 
10795 /// Perform semantic checking of a new function declaration.
10796 ///
10797 /// Performs semantic analysis of the new function declaration
10798 /// NewFD. This routine performs all semantic checking that does not
10799 /// require the actual declarator involved in the declaration, and is
10800 /// used both for the declaration of functions as they are parsed
10801 /// (called via ActOnDeclarator) and for the declaration of functions
10802 /// that have been instantiated via C++ template instantiation (called
10803 /// via InstantiateDecl).
10804 ///
10805 /// \param IsMemberSpecialization whether this new function declaration is
10806 /// a member specialization (that replaces any definition provided by the
10807 /// previous declaration).
10808 ///
10809 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10810 ///
10811 /// \returns true if the function declaration is a redeclaration.
10812 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10813                                     LookupResult &Previous,
10814                                     bool IsMemberSpecialization) {
10815   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10816          "Variably modified return types are not handled here");
10817 
10818   // Determine whether the type of this function should be merged with
10819   // a previous visible declaration. This never happens for functions in C++,
10820   // and always happens in C if the previous declaration was visible.
10821   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10822                                !Previous.isShadowed();
10823 
10824   bool Redeclaration = false;
10825   NamedDecl *OldDecl = nullptr;
10826   bool MayNeedOverloadableChecks = false;
10827 
10828   // Merge or overload the declaration with an existing declaration of
10829   // the same name, if appropriate.
10830   if (!Previous.empty()) {
10831     // Determine whether NewFD is an overload of PrevDecl or
10832     // a declaration that requires merging. If it's an overload,
10833     // there's no more work to do here; we'll just add the new
10834     // function to the scope.
10835     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10836       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10837       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10838         Redeclaration = true;
10839         OldDecl = Candidate;
10840       }
10841     } else {
10842       MayNeedOverloadableChecks = true;
10843       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10844                             /*NewIsUsingDecl*/ false)) {
10845       case Ovl_Match:
10846         Redeclaration = true;
10847         break;
10848 
10849       case Ovl_NonFunction:
10850         Redeclaration = true;
10851         break;
10852 
10853       case Ovl_Overload:
10854         Redeclaration = false;
10855         break;
10856       }
10857     }
10858   }
10859 
10860   // Check for a previous extern "C" declaration with this name.
10861   if (!Redeclaration &&
10862       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10863     if (!Previous.empty()) {
10864       // This is an extern "C" declaration with the same name as a previous
10865       // declaration, and thus redeclares that entity...
10866       Redeclaration = true;
10867       OldDecl = Previous.getFoundDecl();
10868       MergeTypeWithPrevious = false;
10869 
10870       // ... except in the presence of __attribute__((overloadable)).
10871       if (OldDecl->hasAttr<OverloadableAttr>() ||
10872           NewFD->hasAttr<OverloadableAttr>()) {
10873         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10874           MayNeedOverloadableChecks = true;
10875           Redeclaration = false;
10876           OldDecl = nullptr;
10877         }
10878       }
10879     }
10880   }
10881 
10882   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10883                                 MergeTypeWithPrevious, Previous))
10884     return Redeclaration;
10885 
10886   // PPC MMA non-pointer types are not allowed as function return types.
10887   if (Context.getTargetInfo().getTriple().isPPC64() &&
10888       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10889     NewFD->setInvalidDecl();
10890   }
10891 
10892   // C++11 [dcl.constexpr]p8:
10893   //   A constexpr specifier for a non-static member function that is not
10894   //   a constructor declares that member function to be const.
10895   //
10896   // This needs to be delayed until we know whether this is an out-of-line
10897   // definition of a static member function.
10898   //
10899   // This rule is not present in C++1y, so we produce a backwards
10900   // compatibility warning whenever it happens in C++11.
10901   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10902   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10903       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10904       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10905     CXXMethodDecl *OldMD = nullptr;
10906     if (OldDecl)
10907       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10908     if (!OldMD || !OldMD->isStatic()) {
10909       const FunctionProtoType *FPT =
10910         MD->getType()->castAs<FunctionProtoType>();
10911       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10912       EPI.TypeQuals.addConst();
10913       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10914                                           FPT->getParamTypes(), EPI));
10915 
10916       // Warn that we did this, if we're not performing template instantiation.
10917       // In that case, we'll have warned already when the template was defined.
10918       if (!inTemplateInstantiation()) {
10919         SourceLocation AddConstLoc;
10920         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10921                 .IgnoreParens().getAs<FunctionTypeLoc>())
10922           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10923 
10924         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10925           << FixItHint::CreateInsertion(AddConstLoc, " const");
10926       }
10927     }
10928   }
10929 
10930   if (Redeclaration) {
10931     // NewFD and OldDecl represent declarations that need to be
10932     // merged.
10933     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10934       NewFD->setInvalidDecl();
10935       return Redeclaration;
10936     }
10937 
10938     Previous.clear();
10939     Previous.addDecl(OldDecl);
10940 
10941     if (FunctionTemplateDecl *OldTemplateDecl =
10942             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10943       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10944       FunctionTemplateDecl *NewTemplateDecl
10945         = NewFD->getDescribedFunctionTemplate();
10946       assert(NewTemplateDecl && "Template/non-template mismatch");
10947 
10948       // The call to MergeFunctionDecl above may have created some state in
10949       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10950       // can add it as a redeclaration.
10951       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10952 
10953       NewFD->setPreviousDeclaration(OldFD);
10954       if (NewFD->isCXXClassMember()) {
10955         NewFD->setAccess(OldTemplateDecl->getAccess());
10956         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10957       }
10958 
10959       // If this is an explicit specialization of a member that is a function
10960       // template, mark it as a member specialization.
10961       if (IsMemberSpecialization &&
10962           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10963         NewTemplateDecl->setMemberSpecialization();
10964         assert(OldTemplateDecl->isMemberSpecialization());
10965         // Explicit specializations of a member template do not inherit deleted
10966         // status from the parent member template that they are specializing.
10967         if (OldFD->isDeleted()) {
10968           // FIXME: This assert will not hold in the presence of modules.
10969           assert(OldFD->getCanonicalDecl() == OldFD);
10970           // FIXME: We need an update record for this AST mutation.
10971           OldFD->setDeletedAsWritten(false);
10972         }
10973       }
10974 
10975     } else {
10976       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10977         auto *OldFD = cast<FunctionDecl>(OldDecl);
10978         // This needs to happen first so that 'inline' propagates.
10979         NewFD->setPreviousDeclaration(OldFD);
10980         if (NewFD->isCXXClassMember())
10981           NewFD->setAccess(OldFD->getAccess());
10982       }
10983     }
10984   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10985              !NewFD->getAttr<OverloadableAttr>()) {
10986     assert((Previous.empty() ||
10987             llvm::any_of(Previous,
10988                          [](const NamedDecl *ND) {
10989                            return ND->hasAttr<OverloadableAttr>();
10990                          })) &&
10991            "Non-redecls shouldn't happen without overloadable present");
10992 
10993     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10994       const auto *FD = dyn_cast<FunctionDecl>(ND);
10995       return FD && !FD->hasAttr<OverloadableAttr>();
10996     });
10997 
10998     if (OtherUnmarkedIter != Previous.end()) {
10999       Diag(NewFD->getLocation(),
11000            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11001       Diag((*OtherUnmarkedIter)->getLocation(),
11002            diag::note_attribute_overloadable_prev_overload)
11003           << false;
11004 
11005       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11006     }
11007   }
11008 
11009   if (LangOpts.OpenMP)
11010     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11011 
11012   // Semantic checking for this function declaration (in isolation).
11013 
11014   if (getLangOpts().CPlusPlus) {
11015     // C++-specific checks.
11016     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11017       CheckConstructor(Constructor);
11018     } else if (CXXDestructorDecl *Destructor =
11019                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11020       CXXRecordDecl *Record = Destructor->getParent();
11021       QualType ClassType = Context.getTypeDeclType(Record);
11022 
11023       // FIXME: Shouldn't we be able to perform this check even when the class
11024       // type is dependent? Both gcc and edg can handle that.
11025       if (!ClassType->isDependentType()) {
11026         DeclarationName Name
11027           = Context.DeclarationNames.getCXXDestructorName(
11028                                         Context.getCanonicalType(ClassType));
11029         if (NewFD->getDeclName() != Name) {
11030           Diag(NewFD->getLocation(), diag::err_destructor_name);
11031           NewFD->setInvalidDecl();
11032           return Redeclaration;
11033         }
11034       }
11035     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11036       if (auto *TD = Guide->getDescribedFunctionTemplate())
11037         CheckDeductionGuideTemplate(TD);
11038 
11039       // A deduction guide is not on the list of entities that can be
11040       // explicitly specialized.
11041       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11042         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11043             << /*explicit specialization*/ 1;
11044     }
11045 
11046     // Find any virtual functions that this function overrides.
11047     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11048       if (!Method->isFunctionTemplateSpecialization() &&
11049           !Method->getDescribedFunctionTemplate() &&
11050           Method->isCanonicalDecl()) {
11051         AddOverriddenMethods(Method->getParent(), Method);
11052       }
11053       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11054         // C++2a [class.virtual]p6
11055         // A virtual method shall not have a requires-clause.
11056         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11057              diag::err_constrained_virtual_method);
11058 
11059       if (Method->isStatic())
11060         checkThisInStaticMemberFunctionType(Method);
11061     }
11062 
11063     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11064       ActOnConversionDeclarator(Conversion);
11065 
11066     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11067     if (NewFD->isOverloadedOperator() &&
11068         CheckOverloadedOperatorDeclaration(NewFD)) {
11069       NewFD->setInvalidDecl();
11070       return Redeclaration;
11071     }
11072 
11073     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11074     if (NewFD->getLiteralIdentifier() &&
11075         CheckLiteralOperatorDeclaration(NewFD)) {
11076       NewFD->setInvalidDecl();
11077       return Redeclaration;
11078     }
11079 
11080     // In C++, check default arguments now that we have merged decls. Unless
11081     // the lexical context is the class, because in this case this is done
11082     // during delayed parsing anyway.
11083     if (!CurContext->isRecord())
11084       CheckCXXDefaultArguments(NewFD);
11085 
11086     // If this function is declared as being extern "C", then check to see if
11087     // the function returns a UDT (class, struct, or union type) that is not C
11088     // compatible, and if it does, warn the user.
11089     // But, issue any diagnostic on the first declaration only.
11090     if (Previous.empty() && NewFD->isExternC()) {
11091       QualType R = NewFD->getReturnType();
11092       if (R->isIncompleteType() && !R->isVoidType())
11093         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11094             << NewFD << R;
11095       else if (!R.isPODType(Context) && !R->isVoidType() &&
11096                !R->isObjCObjectPointerType())
11097         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11098     }
11099 
11100     // C++1z [dcl.fct]p6:
11101     //   [...] whether the function has a non-throwing exception-specification
11102     //   [is] part of the function type
11103     //
11104     // This results in an ABI break between C++14 and C++17 for functions whose
11105     // declared type includes an exception-specification in a parameter or
11106     // return type. (Exception specifications on the function itself are OK in
11107     // most cases, and exception specifications are not permitted in most other
11108     // contexts where they could make it into a mangling.)
11109     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11110       auto HasNoexcept = [&](QualType T) -> bool {
11111         // Strip off declarator chunks that could be between us and a function
11112         // type. We don't need to look far, exception specifications are very
11113         // restricted prior to C++17.
11114         if (auto *RT = T->getAs<ReferenceType>())
11115           T = RT->getPointeeType();
11116         else if (T->isAnyPointerType())
11117           T = T->getPointeeType();
11118         else if (auto *MPT = T->getAs<MemberPointerType>())
11119           T = MPT->getPointeeType();
11120         if (auto *FPT = T->getAs<FunctionProtoType>())
11121           if (FPT->isNothrow())
11122             return true;
11123         return false;
11124       };
11125 
11126       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11127       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11128       for (QualType T : FPT->param_types())
11129         AnyNoexcept |= HasNoexcept(T);
11130       if (AnyNoexcept)
11131         Diag(NewFD->getLocation(),
11132              diag::warn_cxx17_compat_exception_spec_in_signature)
11133             << NewFD;
11134     }
11135 
11136     if (!Redeclaration && LangOpts.CUDA)
11137       checkCUDATargetOverload(NewFD, Previous);
11138   }
11139   return Redeclaration;
11140 }
11141 
11142 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11143   // C++11 [basic.start.main]p3:
11144   //   A program that [...] declares main to be inline, static or
11145   //   constexpr is ill-formed.
11146   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11147   //   appear in a declaration of main.
11148   // static main is not an error under C99, but we should warn about it.
11149   // We accept _Noreturn main as an extension.
11150   if (FD->getStorageClass() == SC_Static)
11151     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11152          ? diag::err_static_main : diag::warn_static_main)
11153       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11154   if (FD->isInlineSpecified())
11155     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11156       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11157   if (DS.isNoreturnSpecified()) {
11158     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11159     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11160     Diag(NoreturnLoc, diag::ext_noreturn_main);
11161     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11162       << FixItHint::CreateRemoval(NoreturnRange);
11163   }
11164   if (FD->isConstexpr()) {
11165     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11166         << FD->isConsteval()
11167         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11168     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11169   }
11170 
11171   if (getLangOpts().OpenCL) {
11172     Diag(FD->getLocation(), diag::err_opencl_no_main)
11173         << FD->hasAttr<OpenCLKernelAttr>();
11174     FD->setInvalidDecl();
11175     return;
11176   }
11177 
11178   QualType T = FD->getType();
11179   assert(T->isFunctionType() && "function decl is not of function type");
11180   const FunctionType* FT = T->castAs<FunctionType>();
11181 
11182   // Set default calling convention for main()
11183   if (FT->getCallConv() != CC_C) {
11184     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11185     FD->setType(QualType(FT, 0));
11186     T = Context.getCanonicalType(FD->getType());
11187   }
11188 
11189   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11190     // In C with GNU extensions we allow main() to have non-integer return
11191     // type, but we should warn about the extension, and we disable the
11192     // implicit-return-zero rule.
11193 
11194     // GCC in C mode accepts qualified 'int'.
11195     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11196       FD->setHasImplicitReturnZero(true);
11197     else {
11198       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11199       SourceRange RTRange = FD->getReturnTypeSourceRange();
11200       if (RTRange.isValid())
11201         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11202             << FixItHint::CreateReplacement(RTRange, "int");
11203     }
11204   } else {
11205     // In C and C++, main magically returns 0 if you fall off the end;
11206     // set the flag which tells us that.
11207     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11208 
11209     // All the standards say that main() should return 'int'.
11210     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11211       FD->setHasImplicitReturnZero(true);
11212     else {
11213       // Otherwise, this is just a flat-out error.
11214       SourceRange RTRange = FD->getReturnTypeSourceRange();
11215       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11216           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11217                                 : FixItHint());
11218       FD->setInvalidDecl(true);
11219     }
11220   }
11221 
11222   // Treat protoless main() as nullary.
11223   if (isa<FunctionNoProtoType>(FT)) return;
11224 
11225   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11226   unsigned nparams = FTP->getNumParams();
11227   assert(FD->getNumParams() == nparams);
11228 
11229   bool HasExtraParameters = (nparams > 3);
11230 
11231   if (FTP->isVariadic()) {
11232     Diag(FD->getLocation(), diag::ext_variadic_main);
11233     // FIXME: if we had information about the location of the ellipsis, we
11234     // could add a FixIt hint to remove it as a parameter.
11235   }
11236 
11237   // Darwin passes an undocumented fourth argument of type char**.  If
11238   // other platforms start sprouting these, the logic below will start
11239   // getting shifty.
11240   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11241     HasExtraParameters = false;
11242 
11243   if (HasExtraParameters) {
11244     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11245     FD->setInvalidDecl(true);
11246     nparams = 3;
11247   }
11248 
11249   // FIXME: a lot of the following diagnostics would be improved
11250   // if we had some location information about types.
11251 
11252   QualType CharPP =
11253     Context.getPointerType(Context.getPointerType(Context.CharTy));
11254   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11255 
11256   for (unsigned i = 0; i < nparams; ++i) {
11257     QualType AT = FTP->getParamType(i);
11258 
11259     bool mismatch = true;
11260 
11261     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11262       mismatch = false;
11263     else if (Expected[i] == CharPP) {
11264       // As an extension, the following forms are okay:
11265       //   char const **
11266       //   char const * const *
11267       //   char * const *
11268 
11269       QualifierCollector qs;
11270       const PointerType* PT;
11271       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11272           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11273           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11274                               Context.CharTy)) {
11275         qs.removeConst();
11276         mismatch = !qs.empty();
11277       }
11278     }
11279 
11280     if (mismatch) {
11281       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11282       // TODO: suggest replacing given type with expected type
11283       FD->setInvalidDecl(true);
11284     }
11285   }
11286 
11287   if (nparams == 1 && !FD->isInvalidDecl()) {
11288     Diag(FD->getLocation(), diag::warn_main_one_arg);
11289   }
11290 
11291   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11292     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11293     FD->setInvalidDecl();
11294   }
11295 }
11296 
11297 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11298 
11299   // Default calling convention for main and wmain is __cdecl
11300   if (FD->getName() == "main" || FD->getName() == "wmain")
11301     return false;
11302 
11303   // Default calling convention for MinGW is __cdecl
11304   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11305   if (T.isWindowsGNUEnvironment())
11306     return false;
11307 
11308   // Default calling convention for WinMain, wWinMain and DllMain
11309   // is __stdcall on 32 bit Windows
11310   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11311     return true;
11312 
11313   return false;
11314 }
11315 
11316 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11317   QualType T = FD->getType();
11318   assert(T->isFunctionType() && "function decl is not of function type");
11319   const FunctionType *FT = T->castAs<FunctionType>();
11320 
11321   // Set an implicit return of 'zero' if the function can return some integral,
11322   // enumeration, pointer or nullptr type.
11323   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11324       FT->getReturnType()->isAnyPointerType() ||
11325       FT->getReturnType()->isNullPtrType())
11326     // DllMain is exempt because a return value of zero means it failed.
11327     if (FD->getName() != "DllMain")
11328       FD->setHasImplicitReturnZero(true);
11329 
11330   // Explicity specified calling conventions are applied to MSVC entry points
11331   if (!hasExplicitCallingConv(T)) {
11332     if (isDefaultStdCall(FD, *this)) {
11333       if (FT->getCallConv() != CC_X86StdCall) {
11334         FT = Context.adjustFunctionType(
11335             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11336         FD->setType(QualType(FT, 0));
11337       }
11338     } else if (FT->getCallConv() != CC_C) {
11339       FT = Context.adjustFunctionType(FT,
11340                                       FT->getExtInfo().withCallingConv(CC_C));
11341       FD->setType(QualType(FT, 0));
11342     }
11343   }
11344 
11345   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11346     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11347     FD->setInvalidDecl();
11348   }
11349 }
11350 
11351 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11352   // FIXME: Need strict checking.  In C89, we need to check for
11353   // any assignment, increment, decrement, function-calls, or
11354   // commas outside of a sizeof.  In C99, it's the same list,
11355   // except that the aforementioned are allowed in unevaluated
11356   // expressions.  Everything else falls under the
11357   // "may accept other forms of constant expressions" exception.
11358   //
11359   // Regular C++ code will not end up here (exceptions: language extensions,
11360   // OpenCL C++ etc), so the constant expression rules there don't matter.
11361   if (Init->isValueDependent()) {
11362     assert(Init->containsErrors() &&
11363            "Dependent code should only occur in error-recovery path.");
11364     return true;
11365   }
11366   const Expr *Culprit;
11367   if (Init->isConstantInitializer(Context, false, &Culprit))
11368     return false;
11369   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11370     << Culprit->getSourceRange();
11371   return true;
11372 }
11373 
11374 namespace {
11375   // Visits an initialization expression to see if OrigDecl is evaluated in
11376   // its own initialization and throws a warning if it does.
11377   class SelfReferenceChecker
11378       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11379     Sema &S;
11380     Decl *OrigDecl;
11381     bool isRecordType;
11382     bool isPODType;
11383     bool isReferenceType;
11384 
11385     bool isInitList;
11386     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11387 
11388   public:
11389     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11390 
11391     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11392                                                     S(S), OrigDecl(OrigDecl) {
11393       isPODType = false;
11394       isRecordType = false;
11395       isReferenceType = false;
11396       isInitList = false;
11397       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11398         isPODType = VD->getType().isPODType(S.Context);
11399         isRecordType = VD->getType()->isRecordType();
11400         isReferenceType = VD->getType()->isReferenceType();
11401       }
11402     }
11403 
11404     // For most expressions, just call the visitor.  For initializer lists,
11405     // track the index of the field being initialized since fields are
11406     // initialized in order allowing use of previously initialized fields.
11407     void CheckExpr(Expr *E) {
11408       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11409       if (!InitList) {
11410         Visit(E);
11411         return;
11412       }
11413 
11414       // Track and increment the index here.
11415       isInitList = true;
11416       InitFieldIndex.push_back(0);
11417       for (auto Child : InitList->children()) {
11418         CheckExpr(cast<Expr>(Child));
11419         ++InitFieldIndex.back();
11420       }
11421       InitFieldIndex.pop_back();
11422     }
11423 
11424     // Returns true if MemberExpr is checked and no further checking is needed.
11425     // Returns false if additional checking is required.
11426     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11427       llvm::SmallVector<FieldDecl*, 4> Fields;
11428       Expr *Base = E;
11429       bool ReferenceField = false;
11430 
11431       // Get the field members used.
11432       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11433         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11434         if (!FD)
11435           return false;
11436         Fields.push_back(FD);
11437         if (FD->getType()->isReferenceType())
11438           ReferenceField = true;
11439         Base = ME->getBase()->IgnoreParenImpCasts();
11440       }
11441 
11442       // Keep checking only if the base Decl is the same.
11443       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11444       if (!DRE || DRE->getDecl() != OrigDecl)
11445         return false;
11446 
11447       // A reference field can be bound to an unininitialized field.
11448       if (CheckReference && !ReferenceField)
11449         return true;
11450 
11451       // Convert FieldDecls to their index number.
11452       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11453       for (const FieldDecl *I : llvm::reverse(Fields))
11454         UsedFieldIndex.push_back(I->getFieldIndex());
11455 
11456       // See if a warning is needed by checking the first difference in index
11457       // numbers.  If field being used has index less than the field being
11458       // initialized, then the use is safe.
11459       for (auto UsedIter = UsedFieldIndex.begin(),
11460                 UsedEnd = UsedFieldIndex.end(),
11461                 OrigIter = InitFieldIndex.begin(),
11462                 OrigEnd = InitFieldIndex.end();
11463            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11464         if (*UsedIter < *OrigIter)
11465           return true;
11466         if (*UsedIter > *OrigIter)
11467           break;
11468       }
11469 
11470       // TODO: Add a different warning which will print the field names.
11471       HandleDeclRefExpr(DRE);
11472       return true;
11473     }
11474 
11475     // For most expressions, the cast is directly above the DeclRefExpr.
11476     // For conditional operators, the cast can be outside the conditional
11477     // operator if both expressions are DeclRefExpr's.
11478     void HandleValue(Expr *E) {
11479       E = E->IgnoreParens();
11480       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11481         HandleDeclRefExpr(DRE);
11482         return;
11483       }
11484 
11485       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11486         Visit(CO->getCond());
11487         HandleValue(CO->getTrueExpr());
11488         HandleValue(CO->getFalseExpr());
11489         return;
11490       }
11491 
11492       if (BinaryConditionalOperator *BCO =
11493               dyn_cast<BinaryConditionalOperator>(E)) {
11494         Visit(BCO->getCond());
11495         HandleValue(BCO->getFalseExpr());
11496         return;
11497       }
11498 
11499       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11500         HandleValue(OVE->getSourceExpr());
11501         return;
11502       }
11503 
11504       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11505         if (BO->getOpcode() == BO_Comma) {
11506           Visit(BO->getLHS());
11507           HandleValue(BO->getRHS());
11508           return;
11509         }
11510       }
11511 
11512       if (isa<MemberExpr>(E)) {
11513         if (isInitList) {
11514           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11515                                       false /*CheckReference*/))
11516             return;
11517         }
11518 
11519         Expr *Base = E->IgnoreParenImpCasts();
11520         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11521           // Check for static member variables and don't warn on them.
11522           if (!isa<FieldDecl>(ME->getMemberDecl()))
11523             return;
11524           Base = ME->getBase()->IgnoreParenImpCasts();
11525         }
11526         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11527           HandleDeclRefExpr(DRE);
11528         return;
11529       }
11530 
11531       Visit(E);
11532     }
11533 
11534     // Reference types not handled in HandleValue are handled here since all
11535     // uses of references are bad, not just r-value uses.
11536     void VisitDeclRefExpr(DeclRefExpr *E) {
11537       if (isReferenceType)
11538         HandleDeclRefExpr(E);
11539     }
11540 
11541     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11542       if (E->getCastKind() == CK_LValueToRValue) {
11543         HandleValue(E->getSubExpr());
11544         return;
11545       }
11546 
11547       Inherited::VisitImplicitCastExpr(E);
11548     }
11549 
11550     void VisitMemberExpr(MemberExpr *E) {
11551       if (isInitList) {
11552         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11553           return;
11554       }
11555 
11556       // Don't warn on arrays since they can be treated as pointers.
11557       if (E->getType()->canDecayToPointerType()) return;
11558 
11559       // Warn when a non-static method call is followed by non-static member
11560       // field accesses, which is followed by a DeclRefExpr.
11561       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11562       bool Warn = (MD && !MD->isStatic());
11563       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11564       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11565         if (!isa<FieldDecl>(ME->getMemberDecl()))
11566           Warn = false;
11567         Base = ME->getBase()->IgnoreParenImpCasts();
11568       }
11569 
11570       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11571         if (Warn)
11572           HandleDeclRefExpr(DRE);
11573         return;
11574       }
11575 
11576       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11577       // Visit that expression.
11578       Visit(Base);
11579     }
11580 
11581     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11582       Expr *Callee = E->getCallee();
11583 
11584       if (isa<UnresolvedLookupExpr>(Callee))
11585         return Inherited::VisitCXXOperatorCallExpr(E);
11586 
11587       Visit(Callee);
11588       for (auto Arg: E->arguments())
11589         HandleValue(Arg->IgnoreParenImpCasts());
11590     }
11591 
11592     void VisitUnaryOperator(UnaryOperator *E) {
11593       // For POD record types, addresses of its own members are well-defined.
11594       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11595           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11596         if (!isPODType)
11597           HandleValue(E->getSubExpr());
11598         return;
11599       }
11600 
11601       if (E->isIncrementDecrementOp()) {
11602         HandleValue(E->getSubExpr());
11603         return;
11604       }
11605 
11606       Inherited::VisitUnaryOperator(E);
11607     }
11608 
11609     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11610 
11611     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11612       if (E->getConstructor()->isCopyConstructor()) {
11613         Expr *ArgExpr = E->getArg(0);
11614         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11615           if (ILE->getNumInits() == 1)
11616             ArgExpr = ILE->getInit(0);
11617         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11618           if (ICE->getCastKind() == CK_NoOp)
11619             ArgExpr = ICE->getSubExpr();
11620         HandleValue(ArgExpr);
11621         return;
11622       }
11623       Inherited::VisitCXXConstructExpr(E);
11624     }
11625 
11626     void VisitCallExpr(CallExpr *E) {
11627       // Treat std::move as a use.
11628       if (E->isCallToStdMove()) {
11629         HandleValue(E->getArg(0));
11630         return;
11631       }
11632 
11633       Inherited::VisitCallExpr(E);
11634     }
11635 
11636     void VisitBinaryOperator(BinaryOperator *E) {
11637       if (E->isCompoundAssignmentOp()) {
11638         HandleValue(E->getLHS());
11639         Visit(E->getRHS());
11640         return;
11641       }
11642 
11643       Inherited::VisitBinaryOperator(E);
11644     }
11645 
11646     // A custom visitor for BinaryConditionalOperator is needed because the
11647     // regular visitor would check the condition and true expression separately
11648     // but both point to the same place giving duplicate diagnostics.
11649     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11650       Visit(E->getCond());
11651       Visit(E->getFalseExpr());
11652     }
11653 
11654     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11655       Decl* ReferenceDecl = DRE->getDecl();
11656       if (OrigDecl != ReferenceDecl) return;
11657       unsigned diag;
11658       if (isReferenceType) {
11659         diag = diag::warn_uninit_self_reference_in_reference_init;
11660       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11661         diag = diag::warn_static_self_reference_in_init;
11662       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11663                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11664                  DRE->getDecl()->getType()->isRecordType()) {
11665         diag = diag::warn_uninit_self_reference_in_init;
11666       } else {
11667         // Local variables will be handled by the CFG analysis.
11668         return;
11669       }
11670 
11671       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11672                             S.PDiag(diag)
11673                                 << DRE->getDecl() << OrigDecl->getLocation()
11674                                 << DRE->getSourceRange());
11675     }
11676   };
11677 
11678   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11679   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11680                                  bool DirectInit) {
11681     // Parameters arguments are occassionially constructed with itself,
11682     // for instance, in recursive functions.  Skip them.
11683     if (isa<ParmVarDecl>(OrigDecl))
11684       return;
11685 
11686     E = E->IgnoreParens();
11687 
11688     // Skip checking T a = a where T is not a record or reference type.
11689     // Doing so is a way to silence uninitialized warnings.
11690     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11691       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11692         if (ICE->getCastKind() == CK_LValueToRValue)
11693           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11694             if (DRE->getDecl() == OrigDecl)
11695               return;
11696 
11697     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11698   }
11699 } // end anonymous namespace
11700 
11701 namespace {
11702   // Simple wrapper to add the name of a variable or (if no variable is
11703   // available) a DeclarationName into a diagnostic.
11704   struct VarDeclOrName {
11705     VarDecl *VDecl;
11706     DeclarationName Name;
11707 
11708     friend const Sema::SemaDiagnosticBuilder &
11709     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11710       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11711     }
11712   };
11713 } // end anonymous namespace
11714 
11715 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11716                                             DeclarationName Name, QualType Type,
11717                                             TypeSourceInfo *TSI,
11718                                             SourceRange Range, bool DirectInit,
11719                                             Expr *Init) {
11720   bool IsInitCapture = !VDecl;
11721   assert((!VDecl || !VDecl->isInitCapture()) &&
11722          "init captures are expected to be deduced prior to initialization");
11723 
11724   VarDeclOrName VN{VDecl, Name};
11725 
11726   DeducedType *Deduced = Type->getContainedDeducedType();
11727   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11728 
11729   // C++11 [dcl.spec.auto]p3
11730   if (!Init) {
11731     assert(VDecl && "no init for init capture deduction?");
11732 
11733     // Except for class argument deduction, and then for an initializing
11734     // declaration only, i.e. no static at class scope or extern.
11735     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11736         VDecl->hasExternalStorage() ||
11737         VDecl->isStaticDataMember()) {
11738       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11739         << VDecl->getDeclName() << Type;
11740       return QualType();
11741     }
11742   }
11743 
11744   ArrayRef<Expr*> DeduceInits;
11745   if (Init)
11746     DeduceInits = Init;
11747 
11748   if (DirectInit) {
11749     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11750       DeduceInits = PL->exprs();
11751   }
11752 
11753   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11754     assert(VDecl && "non-auto type for init capture deduction?");
11755     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11756     InitializationKind Kind = InitializationKind::CreateForInit(
11757         VDecl->getLocation(), DirectInit, Init);
11758     // FIXME: Initialization should not be taking a mutable list of inits.
11759     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11760     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11761                                                        InitsCopy);
11762   }
11763 
11764   if (DirectInit) {
11765     if (auto *IL = dyn_cast<InitListExpr>(Init))
11766       DeduceInits = IL->inits();
11767   }
11768 
11769   // Deduction only works if we have exactly one source expression.
11770   if (DeduceInits.empty()) {
11771     // It isn't possible to write this directly, but it is possible to
11772     // end up in this situation with "auto x(some_pack...);"
11773     Diag(Init->getBeginLoc(), IsInitCapture
11774                                   ? diag::err_init_capture_no_expression
11775                                   : diag::err_auto_var_init_no_expression)
11776         << VN << Type << Range;
11777     return QualType();
11778   }
11779 
11780   if (DeduceInits.size() > 1) {
11781     Diag(DeduceInits[1]->getBeginLoc(),
11782          IsInitCapture ? diag::err_init_capture_multiple_expressions
11783                        : diag::err_auto_var_init_multiple_expressions)
11784         << VN << Type << Range;
11785     return QualType();
11786   }
11787 
11788   Expr *DeduceInit = DeduceInits[0];
11789   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11790     Diag(Init->getBeginLoc(), IsInitCapture
11791                                   ? diag::err_init_capture_paren_braces
11792                                   : diag::err_auto_var_init_paren_braces)
11793         << isa<InitListExpr>(Init) << VN << Type << Range;
11794     return QualType();
11795   }
11796 
11797   // Expressions default to 'id' when we're in a debugger.
11798   bool DefaultedAnyToId = false;
11799   if (getLangOpts().DebuggerCastResultToId &&
11800       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11801     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11802     if (Result.isInvalid()) {
11803       return QualType();
11804     }
11805     Init = Result.get();
11806     DefaultedAnyToId = true;
11807   }
11808 
11809   // C++ [dcl.decomp]p1:
11810   //   If the assignment-expression [...] has array type A and no ref-qualifier
11811   //   is present, e has type cv A
11812   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11813       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11814       DeduceInit->getType()->isConstantArrayType())
11815     return Context.getQualifiedType(DeduceInit->getType(),
11816                                     Type.getQualifiers());
11817 
11818   QualType DeducedType;
11819   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11820     if (!IsInitCapture)
11821       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11822     else if (isa<InitListExpr>(Init))
11823       Diag(Range.getBegin(),
11824            diag::err_init_capture_deduction_failure_from_init_list)
11825           << VN
11826           << (DeduceInit->getType().isNull() ? TSI->getType()
11827                                              : DeduceInit->getType())
11828           << DeduceInit->getSourceRange();
11829     else
11830       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11831           << VN << TSI->getType()
11832           << (DeduceInit->getType().isNull() ? TSI->getType()
11833                                              : DeduceInit->getType())
11834           << DeduceInit->getSourceRange();
11835   }
11836 
11837   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11838   // 'id' instead of a specific object type prevents most of our usual
11839   // checks.
11840   // We only want to warn outside of template instantiations, though:
11841   // inside a template, the 'id' could have come from a parameter.
11842   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11843       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11844     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11845     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11846   }
11847 
11848   return DeducedType;
11849 }
11850 
11851 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11852                                          Expr *Init) {
11853   assert(!Init || !Init->containsErrors());
11854   QualType DeducedType = deduceVarTypeFromInitializer(
11855       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11856       VDecl->getSourceRange(), DirectInit, Init);
11857   if (DeducedType.isNull()) {
11858     VDecl->setInvalidDecl();
11859     return true;
11860   }
11861 
11862   VDecl->setType(DeducedType);
11863   assert(VDecl->isLinkageValid());
11864 
11865   // In ARC, infer lifetime.
11866   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11867     VDecl->setInvalidDecl();
11868 
11869   if (getLangOpts().OpenCL)
11870     deduceOpenCLAddressSpace(VDecl);
11871 
11872   // If this is a redeclaration, check that the type we just deduced matches
11873   // the previously declared type.
11874   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11875     // We never need to merge the type, because we cannot form an incomplete
11876     // array of auto, nor deduce such a type.
11877     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11878   }
11879 
11880   // Check the deduced type is valid for a variable declaration.
11881   CheckVariableDeclarationType(VDecl);
11882   return VDecl->isInvalidDecl();
11883 }
11884 
11885 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11886                                               SourceLocation Loc) {
11887   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11888     Init = EWC->getSubExpr();
11889 
11890   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11891     Init = CE->getSubExpr();
11892 
11893   QualType InitType = Init->getType();
11894   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11895           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11896          "shouldn't be called if type doesn't have a non-trivial C struct");
11897   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11898     for (auto I : ILE->inits()) {
11899       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11900           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11901         continue;
11902       SourceLocation SL = I->getExprLoc();
11903       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11904     }
11905     return;
11906   }
11907 
11908   if (isa<ImplicitValueInitExpr>(Init)) {
11909     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11910       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11911                             NTCUK_Init);
11912   } else {
11913     // Assume all other explicit initializers involving copying some existing
11914     // object.
11915     // TODO: ignore any explicit initializers where we can guarantee
11916     // copy-elision.
11917     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11918       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11919   }
11920 }
11921 
11922 namespace {
11923 
11924 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11925   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11926   // in the source code or implicitly by the compiler if it is in a union
11927   // defined in a system header and has non-trivial ObjC ownership
11928   // qualifications. We don't want those fields to participate in determining
11929   // whether the containing union is non-trivial.
11930   return FD->hasAttr<UnavailableAttr>();
11931 }
11932 
11933 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11934     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11935                                     void> {
11936   using Super =
11937       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11938                                     void>;
11939 
11940   DiagNonTrivalCUnionDefaultInitializeVisitor(
11941       QualType OrigTy, SourceLocation OrigLoc,
11942       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11943       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11944 
11945   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11946                      const FieldDecl *FD, bool InNonTrivialUnion) {
11947     if (const auto *AT = S.Context.getAsArrayType(QT))
11948       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11949                                      InNonTrivialUnion);
11950     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11951   }
11952 
11953   void visitARCStrong(QualType QT, const FieldDecl *FD,
11954                       bool InNonTrivialUnion) {
11955     if (InNonTrivialUnion)
11956       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11957           << 1 << 0 << QT << FD->getName();
11958   }
11959 
11960   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11961     if (InNonTrivialUnion)
11962       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11963           << 1 << 0 << QT << FD->getName();
11964   }
11965 
11966   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11967     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11968     if (RD->isUnion()) {
11969       if (OrigLoc.isValid()) {
11970         bool IsUnion = false;
11971         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11972           IsUnion = OrigRD->isUnion();
11973         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11974             << 0 << OrigTy << IsUnion << UseContext;
11975         // Reset OrigLoc so that this diagnostic is emitted only once.
11976         OrigLoc = SourceLocation();
11977       }
11978       InNonTrivialUnion = true;
11979     }
11980 
11981     if (InNonTrivialUnion)
11982       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11983           << 0 << 0 << QT.getUnqualifiedType() << "";
11984 
11985     for (const FieldDecl *FD : RD->fields())
11986       if (!shouldIgnoreForRecordTriviality(FD))
11987         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11988   }
11989 
11990   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11991 
11992   // The non-trivial C union type or the struct/union type that contains a
11993   // non-trivial C union.
11994   QualType OrigTy;
11995   SourceLocation OrigLoc;
11996   Sema::NonTrivialCUnionContext UseContext;
11997   Sema &S;
11998 };
11999 
12000 struct DiagNonTrivalCUnionDestructedTypeVisitor
12001     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12002   using Super =
12003       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12004 
12005   DiagNonTrivalCUnionDestructedTypeVisitor(
12006       QualType OrigTy, SourceLocation OrigLoc,
12007       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12008       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12009 
12010   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12011                      const FieldDecl *FD, bool InNonTrivialUnion) {
12012     if (const auto *AT = S.Context.getAsArrayType(QT))
12013       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12014                                      InNonTrivialUnion);
12015     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12016   }
12017 
12018   void visitARCStrong(QualType QT, const FieldDecl *FD,
12019                       bool InNonTrivialUnion) {
12020     if (InNonTrivialUnion)
12021       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12022           << 1 << 1 << QT << FD->getName();
12023   }
12024 
12025   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12026     if (InNonTrivialUnion)
12027       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12028           << 1 << 1 << QT << FD->getName();
12029   }
12030 
12031   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12032     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12033     if (RD->isUnion()) {
12034       if (OrigLoc.isValid()) {
12035         bool IsUnion = false;
12036         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12037           IsUnion = OrigRD->isUnion();
12038         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12039             << 1 << OrigTy << IsUnion << UseContext;
12040         // Reset OrigLoc so that this diagnostic is emitted only once.
12041         OrigLoc = SourceLocation();
12042       }
12043       InNonTrivialUnion = true;
12044     }
12045 
12046     if (InNonTrivialUnion)
12047       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12048           << 0 << 1 << QT.getUnqualifiedType() << "";
12049 
12050     for (const FieldDecl *FD : RD->fields())
12051       if (!shouldIgnoreForRecordTriviality(FD))
12052         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12053   }
12054 
12055   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12056   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12057                           bool InNonTrivialUnion) {}
12058 
12059   // The non-trivial C union type or the struct/union type that contains a
12060   // non-trivial C union.
12061   QualType OrigTy;
12062   SourceLocation OrigLoc;
12063   Sema::NonTrivialCUnionContext UseContext;
12064   Sema &S;
12065 };
12066 
12067 struct DiagNonTrivalCUnionCopyVisitor
12068     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12069   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12070 
12071   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12072                                  Sema::NonTrivialCUnionContext UseContext,
12073                                  Sema &S)
12074       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12075 
12076   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12077                      const FieldDecl *FD, bool InNonTrivialUnion) {
12078     if (const auto *AT = S.Context.getAsArrayType(QT))
12079       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12080                                      InNonTrivialUnion);
12081     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12082   }
12083 
12084   void visitARCStrong(QualType QT, const FieldDecl *FD,
12085                       bool InNonTrivialUnion) {
12086     if (InNonTrivialUnion)
12087       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12088           << 1 << 2 << QT << FD->getName();
12089   }
12090 
12091   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12092     if (InNonTrivialUnion)
12093       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12094           << 1 << 2 << QT << FD->getName();
12095   }
12096 
12097   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12098     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12099     if (RD->isUnion()) {
12100       if (OrigLoc.isValid()) {
12101         bool IsUnion = false;
12102         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12103           IsUnion = OrigRD->isUnion();
12104         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12105             << 2 << OrigTy << IsUnion << UseContext;
12106         // Reset OrigLoc so that this diagnostic is emitted only once.
12107         OrigLoc = SourceLocation();
12108       }
12109       InNonTrivialUnion = true;
12110     }
12111 
12112     if (InNonTrivialUnion)
12113       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12114           << 0 << 2 << QT.getUnqualifiedType() << "";
12115 
12116     for (const FieldDecl *FD : RD->fields())
12117       if (!shouldIgnoreForRecordTriviality(FD))
12118         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12119   }
12120 
12121   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12122                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12123   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12124   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12125                             bool InNonTrivialUnion) {}
12126 
12127   // The non-trivial C union type or the struct/union type that contains a
12128   // non-trivial C union.
12129   QualType OrigTy;
12130   SourceLocation OrigLoc;
12131   Sema::NonTrivialCUnionContext UseContext;
12132   Sema &S;
12133 };
12134 
12135 } // namespace
12136 
12137 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12138                                  NonTrivialCUnionContext UseContext,
12139                                  unsigned NonTrivialKind) {
12140   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12141           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12142           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12143          "shouldn't be called if type doesn't have a non-trivial C union");
12144 
12145   if ((NonTrivialKind & NTCUK_Init) &&
12146       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12147     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12148         .visit(QT, nullptr, false);
12149   if ((NonTrivialKind & NTCUK_Destruct) &&
12150       QT.hasNonTrivialToPrimitiveDestructCUnion())
12151     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12152         .visit(QT, nullptr, false);
12153   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12154     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12155         .visit(QT, nullptr, false);
12156 }
12157 
12158 /// AddInitializerToDecl - Adds the initializer Init to the
12159 /// declaration dcl. If DirectInit is true, this is C++ direct
12160 /// initialization rather than copy initialization.
12161 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12162   // If there is no declaration, there was an error parsing it.  Just ignore
12163   // the initializer.
12164   if (!RealDecl || RealDecl->isInvalidDecl()) {
12165     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12166     return;
12167   }
12168 
12169   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12170     // Pure-specifiers are handled in ActOnPureSpecifier.
12171     Diag(Method->getLocation(), diag::err_member_function_initialization)
12172       << Method->getDeclName() << Init->getSourceRange();
12173     Method->setInvalidDecl();
12174     return;
12175   }
12176 
12177   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12178   if (!VDecl) {
12179     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12180     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12181     RealDecl->setInvalidDecl();
12182     return;
12183   }
12184 
12185   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12186   if (VDecl->getType()->isUndeducedType()) {
12187     // Attempt typo correction early so that the type of the init expression can
12188     // be deduced based on the chosen correction if the original init contains a
12189     // TypoExpr.
12190     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12191     if (!Res.isUsable()) {
12192       // There are unresolved typos in Init, just drop them.
12193       // FIXME: improve the recovery strategy to preserve the Init.
12194       RealDecl->setInvalidDecl();
12195       return;
12196     }
12197     if (Res.get()->containsErrors()) {
12198       // Invalidate the decl as we don't know the type for recovery-expr yet.
12199       RealDecl->setInvalidDecl();
12200       VDecl->setInit(Res.get());
12201       return;
12202     }
12203     Init = Res.get();
12204 
12205     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12206       return;
12207   }
12208 
12209   // dllimport cannot be used on variable definitions.
12210   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12211     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12212     VDecl->setInvalidDecl();
12213     return;
12214   }
12215 
12216   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12217     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12218     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12219     VDecl->setInvalidDecl();
12220     return;
12221   }
12222 
12223   if (!VDecl->getType()->isDependentType()) {
12224     // A definition must end up with a complete type, which means it must be
12225     // complete with the restriction that an array type might be completed by
12226     // the initializer; note that later code assumes this restriction.
12227     QualType BaseDeclType = VDecl->getType();
12228     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12229       BaseDeclType = Array->getElementType();
12230     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12231                             diag::err_typecheck_decl_incomplete_type)) {
12232       RealDecl->setInvalidDecl();
12233       return;
12234     }
12235 
12236     // The variable can not have an abstract class type.
12237     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12238                                diag::err_abstract_type_in_decl,
12239                                AbstractVariableType))
12240       VDecl->setInvalidDecl();
12241   }
12242 
12243   // If adding the initializer will turn this declaration into a definition,
12244   // and we already have a definition for this variable, diagnose or otherwise
12245   // handle the situation.
12246   if (VarDecl *Def = VDecl->getDefinition())
12247     if (Def != VDecl &&
12248         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12249         !VDecl->isThisDeclarationADemotedDefinition() &&
12250         checkVarDeclRedefinition(Def, VDecl))
12251       return;
12252 
12253   if (getLangOpts().CPlusPlus) {
12254     // C++ [class.static.data]p4
12255     //   If a static data member is of const integral or const
12256     //   enumeration type, its declaration in the class definition can
12257     //   specify a constant-initializer which shall be an integral
12258     //   constant expression (5.19). In that case, the member can appear
12259     //   in integral constant expressions. The member shall still be
12260     //   defined in a namespace scope if it is used in the program and the
12261     //   namespace scope definition shall not contain an initializer.
12262     //
12263     // We already performed a redefinition check above, but for static
12264     // data members we also need to check whether there was an in-class
12265     // declaration with an initializer.
12266     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12267       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12268           << VDecl->getDeclName();
12269       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12270            diag::note_previous_initializer)
12271           << 0;
12272       return;
12273     }
12274 
12275     if (VDecl->hasLocalStorage())
12276       setFunctionHasBranchProtectedScope();
12277 
12278     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12279       VDecl->setInvalidDecl();
12280       return;
12281     }
12282   }
12283 
12284   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12285   // a kernel function cannot be initialized."
12286   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12287     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12288     VDecl->setInvalidDecl();
12289     return;
12290   }
12291 
12292   // The LoaderUninitialized attribute acts as a definition (of undef).
12293   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12294     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12295     VDecl->setInvalidDecl();
12296     return;
12297   }
12298 
12299   // Get the decls type and save a reference for later, since
12300   // CheckInitializerTypes may change it.
12301   QualType DclT = VDecl->getType(), SavT = DclT;
12302 
12303   // Expressions default to 'id' when we're in a debugger
12304   // and we are assigning it to a variable of Objective-C pointer type.
12305   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12306       Init->getType() == Context.UnknownAnyTy) {
12307     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12308     if (Result.isInvalid()) {
12309       VDecl->setInvalidDecl();
12310       return;
12311     }
12312     Init = Result.get();
12313   }
12314 
12315   // Perform the initialization.
12316   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12317   if (!VDecl->isInvalidDecl()) {
12318     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12319     InitializationKind Kind = InitializationKind::CreateForInit(
12320         VDecl->getLocation(), DirectInit, Init);
12321 
12322     MultiExprArg Args = Init;
12323     if (CXXDirectInit)
12324       Args = MultiExprArg(CXXDirectInit->getExprs(),
12325                           CXXDirectInit->getNumExprs());
12326 
12327     // Try to correct any TypoExprs in the initialization arguments.
12328     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12329       ExprResult Res = CorrectDelayedTyposInExpr(
12330           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12331           [this, Entity, Kind](Expr *E) {
12332             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12333             return Init.Failed() ? ExprError() : E;
12334           });
12335       if (Res.isInvalid()) {
12336         VDecl->setInvalidDecl();
12337       } else if (Res.get() != Args[Idx]) {
12338         Args[Idx] = Res.get();
12339       }
12340     }
12341     if (VDecl->isInvalidDecl())
12342       return;
12343 
12344     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12345                                    /*TopLevelOfInitList=*/false,
12346                                    /*TreatUnavailableAsInvalid=*/false);
12347     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12348     if (Result.isInvalid()) {
12349       // If the provied initializer fails to initialize the var decl,
12350       // we attach a recovery expr for better recovery.
12351       auto RecoveryExpr =
12352           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12353       if (RecoveryExpr.get())
12354         VDecl->setInit(RecoveryExpr.get());
12355       return;
12356     }
12357 
12358     Init = Result.getAs<Expr>();
12359   }
12360 
12361   // Check for self-references within variable initializers.
12362   // Variables declared within a function/method body (except for references)
12363   // are handled by a dataflow analysis.
12364   // This is undefined behavior in C++, but valid in C.
12365   if (getLangOpts().CPlusPlus)
12366     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12367         VDecl->getType()->isReferenceType())
12368       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12369 
12370   // If the type changed, it means we had an incomplete type that was
12371   // completed by the initializer. For example:
12372   //   int ary[] = { 1, 3, 5 };
12373   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12374   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12375     VDecl->setType(DclT);
12376 
12377   if (!VDecl->isInvalidDecl()) {
12378     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12379 
12380     if (VDecl->hasAttr<BlocksAttr>())
12381       checkRetainCycles(VDecl, Init);
12382 
12383     // It is safe to assign a weak reference into a strong variable.
12384     // Although this code can still have problems:
12385     //   id x = self.weakProp;
12386     //   id y = self.weakProp;
12387     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12388     // paths through the function. This should be revisited if
12389     // -Wrepeated-use-of-weak is made flow-sensitive.
12390     if (FunctionScopeInfo *FSI = getCurFunction())
12391       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12392            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12393           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12394                            Init->getBeginLoc()))
12395         FSI->markSafeWeakUse(Init);
12396   }
12397 
12398   // The initialization is usually a full-expression.
12399   //
12400   // FIXME: If this is a braced initialization of an aggregate, it is not
12401   // an expression, and each individual field initializer is a separate
12402   // full-expression. For instance, in:
12403   //
12404   //   struct Temp { ~Temp(); };
12405   //   struct S { S(Temp); };
12406   //   struct T { S a, b; } t = { Temp(), Temp() }
12407   //
12408   // we should destroy the first Temp before constructing the second.
12409   ExprResult Result =
12410       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12411                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12412   if (Result.isInvalid()) {
12413     VDecl->setInvalidDecl();
12414     return;
12415   }
12416   Init = Result.get();
12417 
12418   // Attach the initializer to the decl.
12419   VDecl->setInit(Init);
12420 
12421   if (VDecl->isLocalVarDecl()) {
12422     // Don't check the initializer if the declaration is malformed.
12423     if (VDecl->isInvalidDecl()) {
12424       // do nothing
12425 
12426     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12427     // This is true even in C++ for OpenCL.
12428     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12429       CheckForConstantInitializer(Init, DclT);
12430 
12431     // Otherwise, C++ does not restrict the initializer.
12432     } else if (getLangOpts().CPlusPlus) {
12433       // do nothing
12434 
12435     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12436     // static storage duration shall be constant expressions or string literals.
12437     } else if (VDecl->getStorageClass() == SC_Static) {
12438       CheckForConstantInitializer(Init, DclT);
12439 
12440     // C89 is stricter than C99 for aggregate initializers.
12441     // C89 6.5.7p3: All the expressions [...] in an initializer list
12442     // for an object that has aggregate or union type shall be
12443     // constant expressions.
12444     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12445                isa<InitListExpr>(Init)) {
12446       const Expr *Culprit;
12447       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12448         Diag(Culprit->getExprLoc(),
12449              diag::ext_aggregate_init_not_constant)
12450           << Culprit->getSourceRange();
12451       }
12452     }
12453 
12454     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12455       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12456         if (VDecl->hasLocalStorage())
12457           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12458   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12459              VDecl->getLexicalDeclContext()->isRecord()) {
12460     // This is an in-class initialization for a static data member, e.g.,
12461     //
12462     // struct S {
12463     //   static const int value = 17;
12464     // };
12465 
12466     // C++ [class.mem]p4:
12467     //   A member-declarator can contain a constant-initializer only
12468     //   if it declares a static member (9.4) of const integral or
12469     //   const enumeration type, see 9.4.2.
12470     //
12471     // C++11 [class.static.data]p3:
12472     //   If a non-volatile non-inline const static data member is of integral
12473     //   or enumeration type, its declaration in the class definition can
12474     //   specify a brace-or-equal-initializer in which every initializer-clause
12475     //   that is an assignment-expression is a constant expression. A static
12476     //   data member of literal type can be declared in the class definition
12477     //   with the constexpr specifier; if so, its declaration shall specify a
12478     //   brace-or-equal-initializer in which every initializer-clause that is
12479     //   an assignment-expression is a constant expression.
12480 
12481     // Do nothing on dependent types.
12482     if (DclT->isDependentType()) {
12483 
12484     // Allow any 'static constexpr' members, whether or not they are of literal
12485     // type. We separately check that every constexpr variable is of literal
12486     // type.
12487     } else if (VDecl->isConstexpr()) {
12488 
12489     // Require constness.
12490     } else if (!DclT.isConstQualified()) {
12491       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12492         << Init->getSourceRange();
12493       VDecl->setInvalidDecl();
12494 
12495     // We allow integer constant expressions in all cases.
12496     } else if (DclT->isIntegralOrEnumerationType()) {
12497       // Check whether the expression is a constant expression.
12498       SourceLocation Loc;
12499       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12500         // In C++11, a non-constexpr const static data member with an
12501         // in-class initializer cannot be volatile.
12502         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12503       else if (Init->isValueDependent())
12504         ; // Nothing to check.
12505       else if (Init->isIntegerConstantExpr(Context, &Loc))
12506         ; // Ok, it's an ICE!
12507       else if (Init->getType()->isScopedEnumeralType() &&
12508                Init->isCXX11ConstantExpr(Context))
12509         ; // Ok, it is a scoped-enum constant expression.
12510       else if (Init->isEvaluatable(Context)) {
12511         // If we can constant fold the initializer through heroics, accept it,
12512         // but report this as a use of an extension for -pedantic.
12513         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12514           << Init->getSourceRange();
12515       } else {
12516         // Otherwise, this is some crazy unknown case.  Report the issue at the
12517         // location provided by the isIntegerConstantExpr failed check.
12518         Diag(Loc, diag::err_in_class_initializer_non_constant)
12519           << Init->getSourceRange();
12520         VDecl->setInvalidDecl();
12521       }
12522 
12523     // We allow foldable floating-point constants as an extension.
12524     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12525       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12526       // it anyway and provide a fixit to add the 'constexpr'.
12527       if (getLangOpts().CPlusPlus11) {
12528         Diag(VDecl->getLocation(),
12529              diag::ext_in_class_initializer_float_type_cxx11)
12530             << DclT << Init->getSourceRange();
12531         Diag(VDecl->getBeginLoc(),
12532              diag::note_in_class_initializer_float_type_cxx11)
12533             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12534       } else {
12535         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12536           << DclT << Init->getSourceRange();
12537 
12538         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12539           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12540             << Init->getSourceRange();
12541           VDecl->setInvalidDecl();
12542         }
12543       }
12544 
12545     // Suggest adding 'constexpr' in C++11 for literal types.
12546     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12547       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12548           << DclT << Init->getSourceRange()
12549           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12550       VDecl->setConstexpr(true);
12551 
12552     } else {
12553       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12554         << DclT << Init->getSourceRange();
12555       VDecl->setInvalidDecl();
12556     }
12557   } else if (VDecl->isFileVarDecl()) {
12558     // In C, extern is typically used to avoid tentative definitions when
12559     // declaring variables in headers, but adding an intializer makes it a
12560     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12561     // In C++, extern is often used to give implictly static const variables
12562     // external linkage, so don't warn in that case. If selectany is present,
12563     // this might be header code intended for C and C++ inclusion, so apply the
12564     // C++ rules.
12565     if (VDecl->getStorageClass() == SC_Extern &&
12566         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12567          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12568         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12569         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12570       Diag(VDecl->getLocation(), diag::warn_extern_init);
12571 
12572     // In Microsoft C++ mode, a const variable defined in namespace scope has
12573     // external linkage by default if the variable is declared with
12574     // __declspec(dllexport).
12575     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12576         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12577         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12578       VDecl->setStorageClass(SC_Extern);
12579 
12580     // C99 6.7.8p4. All file scoped initializers need to be constant.
12581     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12582       CheckForConstantInitializer(Init, DclT);
12583   }
12584 
12585   QualType InitType = Init->getType();
12586   if (!InitType.isNull() &&
12587       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12588        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12589     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12590 
12591   // We will represent direct-initialization similarly to copy-initialization:
12592   //    int x(1);  -as-> int x = 1;
12593   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12594   //
12595   // Clients that want to distinguish between the two forms, can check for
12596   // direct initializer using VarDecl::getInitStyle().
12597   // A major benefit is that clients that don't particularly care about which
12598   // exactly form was it (like the CodeGen) can handle both cases without
12599   // special case code.
12600 
12601   // C++ 8.5p11:
12602   // The form of initialization (using parentheses or '=') is generally
12603   // insignificant, but does matter when the entity being initialized has a
12604   // class type.
12605   if (CXXDirectInit) {
12606     assert(DirectInit && "Call-style initializer must be direct init.");
12607     VDecl->setInitStyle(VarDecl::CallInit);
12608   } else if (DirectInit) {
12609     // This must be list-initialization. No other way is direct-initialization.
12610     VDecl->setInitStyle(VarDecl::ListInit);
12611   }
12612 
12613   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12614     DeclsToCheckForDeferredDiags.insert(VDecl);
12615   CheckCompleteVariableDeclaration(VDecl);
12616 }
12617 
12618 /// ActOnInitializerError - Given that there was an error parsing an
12619 /// initializer for the given declaration, try to return to some form
12620 /// of sanity.
12621 void Sema::ActOnInitializerError(Decl *D) {
12622   // Our main concern here is re-establishing invariants like "a
12623   // variable's type is either dependent or complete".
12624   if (!D || D->isInvalidDecl()) return;
12625 
12626   VarDecl *VD = dyn_cast<VarDecl>(D);
12627   if (!VD) return;
12628 
12629   // Bindings are not usable if we can't make sense of the initializer.
12630   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12631     for (auto *BD : DD->bindings())
12632       BD->setInvalidDecl();
12633 
12634   // Auto types are meaningless if we can't make sense of the initializer.
12635   if (VD->getType()->isUndeducedType()) {
12636     D->setInvalidDecl();
12637     return;
12638   }
12639 
12640   QualType Ty = VD->getType();
12641   if (Ty->isDependentType()) return;
12642 
12643   // Require a complete type.
12644   if (RequireCompleteType(VD->getLocation(),
12645                           Context.getBaseElementType(Ty),
12646                           diag::err_typecheck_decl_incomplete_type)) {
12647     VD->setInvalidDecl();
12648     return;
12649   }
12650 
12651   // Require a non-abstract type.
12652   if (RequireNonAbstractType(VD->getLocation(), Ty,
12653                              diag::err_abstract_type_in_decl,
12654                              AbstractVariableType)) {
12655     VD->setInvalidDecl();
12656     return;
12657   }
12658 
12659   // Don't bother complaining about constructors or destructors,
12660   // though.
12661 }
12662 
12663 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12664   // If there is no declaration, there was an error parsing it. Just ignore it.
12665   if (!RealDecl)
12666     return;
12667 
12668   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12669     QualType Type = Var->getType();
12670 
12671     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12672     if (isa<DecompositionDecl>(RealDecl)) {
12673       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12674       Var->setInvalidDecl();
12675       return;
12676     }
12677 
12678     if (Type->isUndeducedType() &&
12679         DeduceVariableDeclarationType(Var, false, nullptr))
12680       return;
12681 
12682     // C++11 [class.static.data]p3: A static data member can be declared with
12683     // the constexpr specifier; if so, its declaration shall specify
12684     // a brace-or-equal-initializer.
12685     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12686     // the definition of a variable [...] or the declaration of a static data
12687     // member.
12688     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12689         !Var->isThisDeclarationADemotedDefinition()) {
12690       if (Var->isStaticDataMember()) {
12691         // C++1z removes the relevant rule; the in-class declaration is always
12692         // a definition there.
12693         if (!getLangOpts().CPlusPlus17 &&
12694             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12695           Diag(Var->getLocation(),
12696                diag::err_constexpr_static_mem_var_requires_init)
12697               << Var;
12698           Var->setInvalidDecl();
12699           return;
12700         }
12701       } else {
12702         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12703         Var->setInvalidDecl();
12704         return;
12705       }
12706     }
12707 
12708     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12709     // be initialized.
12710     if (!Var->isInvalidDecl() &&
12711         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12712         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12713       bool HasConstExprDefaultConstructor = false;
12714       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12715         for (auto *Ctor : RD->ctors()) {
12716           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12717               Ctor->getMethodQualifiers().getAddressSpace() ==
12718                   LangAS::opencl_constant) {
12719             HasConstExprDefaultConstructor = true;
12720           }
12721         }
12722       }
12723       if (!HasConstExprDefaultConstructor) {
12724         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12725         Var->setInvalidDecl();
12726         return;
12727       }
12728     }
12729 
12730     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12731       if (Var->getStorageClass() == SC_Extern) {
12732         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12733             << Var;
12734         Var->setInvalidDecl();
12735         return;
12736       }
12737       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12738                               diag::err_typecheck_decl_incomplete_type)) {
12739         Var->setInvalidDecl();
12740         return;
12741       }
12742       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12743         if (!RD->hasTrivialDefaultConstructor()) {
12744           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12745           Var->setInvalidDecl();
12746           return;
12747         }
12748       }
12749       // The declaration is unitialized, no need for further checks.
12750       return;
12751     }
12752 
12753     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12754     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12755         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12756       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12757                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12758 
12759 
12760     switch (DefKind) {
12761     case VarDecl::Definition:
12762       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12763         break;
12764 
12765       // We have an out-of-line definition of a static data member
12766       // that has an in-class initializer, so we type-check this like
12767       // a declaration.
12768       //
12769       LLVM_FALLTHROUGH;
12770 
12771     case VarDecl::DeclarationOnly:
12772       // It's only a declaration.
12773 
12774       // Block scope. C99 6.7p7: If an identifier for an object is
12775       // declared with no linkage (C99 6.2.2p6), the type for the
12776       // object shall be complete.
12777       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12778           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12779           RequireCompleteType(Var->getLocation(), Type,
12780                               diag::err_typecheck_decl_incomplete_type))
12781         Var->setInvalidDecl();
12782 
12783       // Make sure that the type is not abstract.
12784       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12785           RequireNonAbstractType(Var->getLocation(), Type,
12786                                  diag::err_abstract_type_in_decl,
12787                                  AbstractVariableType))
12788         Var->setInvalidDecl();
12789       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12790           Var->getStorageClass() == SC_PrivateExtern) {
12791         Diag(Var->getLocation(), diag::warn_private_extern);
12792         Diag(Var->getLocation(), diag::note_private_extern);
12793       }
12794 
12795       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12796           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12797         ExternalDeclarations.push_back(Var);
12798 
12799       return;
12800 
12801     case VarDecl::TentativeDefinition:
12802       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12803       // object that has file scope without an initializer, and without a
12804       // storage-class specifier or with the storage-class specifier "static",
12805       // constitutes a tentative definition. Note: A tentative definition with
12806       // external linkage is valid (C99 6.2.2p5).
12807       if (!Var->isInvalidDecl()) {
12808         if (const IncompleteArrayType *ArrayT
12809                                     = Context.getAsIncompleteArrayType(Type)) {
12810           if (RequireCompleteSizedType(
12811                   Var->getLocation(), ArrayT->getElementType(),
12812                   diag::err_array_incomplete_or_sizeless_type))
12813             Var->setInvalidDecl();
12814         } else if (Var->getStorageClass() == SC_Static) {
12815           // C99 6.9.2p3: If the declaration of an identifier for an object is
12816           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12817           // declared type shall not be an incomplete type.
12818           // NOTE: code such as the following
12819           //     static struct s;
12820           //     struct s { int a; };
12821           // is accepted by gcc. Hence here we issue a warning instead of
12822           // an error and we do not invalidate the static declaration.
12823           // NOTE: to avoid multiple warnings, only check the first declaration.
12824           if (Var->isFirstDecl())
12825             RequireCompleteType(Var->getLocation(), Type,
12826                                 diag::ext_typecheck_decl_incomplete_type);
12827         }
12828       }
12829 
12830       // Record the tentative definition; we're done.
12831       if (!Var->isInvalidDecl())
12832         TentativeDefinitions.push_back(Var);
12833       return;
12834     }
12835 
12836     // Provide a specific diagnostic for uninitialized variable
12837     // definitions with incomplete array type.
12838     if (Type->isIncompleteArrayType()) {
12839       Diag(Var->getLocation(),
12840            diag::err_typecheck_incomplete_array_needs_initializer);
12841       Var->setInvalidDecl();
12842       return;
12843     }
12844 
12845     // Provide a specific diagnostic for uninitialized variable
12846     // definitions with reference type.
12847     if (Type->isReferenceType()) {
12848       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12849           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12850       Var->setInvalidDecl();
12851       return;
12852     }
12853 
12854     // Do not attempt to type-check the default initializer for a
12855     // variable with dependent type.
12856     if (Type->isDependentType())
12857       return;
12858 
12859     if (Var->isInvalidDecl())
12860       return;
12861 
12862     if (!Var->hasAttr<AliasAttr>()) {
12863       if (RequireCompleteType(Var->getLocation(),
12864                               Context.getBaseElementType(Type),
12865                               diag::err_typecheck_decl_incomplete_type)) {
12866         Var->setInvalidDecl();
12867         return;
12868       }
12869     } else {
12870       return;
12871     }
12872 
12873     // The variable can not have an abstract class type.
12874     if (RequireNonAbstractType(Var->getLocation(), Type,
12875                                diag::err_abstract_type_in_decl,
12876                                AbstractVariableType)) {
12877       Var->setInvalidDecl();
12878       return;
12879     }
12880 
12881     // Check for jumps past the implicit initializer.  C++0x
12882     // clarifies that this applies to a "variable with automatic
12883     // storage duration", not a "local variable".
12884     // C++11 [stmt.dcl]p3
12885     //   A program that jumps from a point where a variable with automatic
12886     //   storage duration is not in scope to a point where it is in scope is
12887     //   ill-formed unless the variable has scalar type, class type with a
12888     //   trivial default constructor and a trivial destructor, a cv-qualified
12889     //   version of one of these types, or an array of one of the preceding
12890     //   types and is declared without an initializer.
12891     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12892       if (const RecordType *Record
12893             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12894         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12895         // Mark the function (if we're in one) for further checking even if the
12896         // looser rules of C++11 do not require such checks, so that we can
12897         // diagnose incompatibilities with C++98.
12898         if (!CXXRecord->isPOD())
12899           setFunctionHasBranchProtectedScope();
12900       }
12901     }
12902     // In OpenCL, we can't initialize objects in the __local address space,
12903     // even implicitly, so don't synthesize an implicit initializer.
12904     if (getLangOpts().OpenCL &&
12905         Var->getType().getAddressSpace() == LangAS::opencl_local)
12906       return;
12907     // C++03 [dcl.init]p9:
12908     //   If no initializer is specified for an object, and the
12909     //   object is of (possibly cv-qualified) non-POD class type (or
12910     //   array thereof), the object shall be default-initialized; if
12911     //   the object is of const-qualified type, the underlying class
12912     //   type shall have a user-declared default
12913     //   constructor. Otherwise, if no initializer is specified for
12914     //   a non- static object, the object and its subobjects, if
12915     //   any, have an indeterminate initial value); if the object
12916     //   or any of its subobjects are of const-qualified type, the
12917     //   program is ill-formed.
12918     // C++0x [dcl.init]p11:
12919     //   If no initializer is specified for an object, the object is
12920     //   default-initialized; [...].
12921     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12922     InitializationKind Kind
12923       = InitializationKind::CreateDefault(Var->getLocation());
12924 
12925     InitializationSequence InitSeq(*this, Entity, Kind, None);
12926     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12927 
12928     if (Init.get()) {
12929       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12930       // This is important for template substitution.
12931       Var->setInitStyle(VarDecl::CallInit);
12932     } else if (Init.isInvalid()) {
12933       // If default-init fails, attach a recovery-expr initializer to track
12934       // that initialization was attempted and failed.
12935       auto RecoveryExpr =
12936           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12937       if (RecoveryExpr.get())
12938         Var->setInit(RecoveryExpr.get());
12939     }
12940 
12941     CheckCompleteVariableDeclaration(Var);
12942   }
12943 }
12944 
12945 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12946   // If there is no declaration, there was an error parsing it. Ignore it.
12947   if (!D)
12948     return;
12949 
12950   VarDecl *VD = dyn_cast<VarDecl>(D);
12951   if (!VD) {
12952     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12953     D->setInvalidDecl();
12954     return;
12955   }
12956 
12957   VD->setCXXForRangeDecl(true);
12958 
12959   // for-range-declaration cannot be given a storage class specifier.
12960   int Error = -1;
12961   switch (VD->getStorageClass()) {
12962   case SC_None:
12963     break;
12964   case SC_Extern:
12965     Error = 0;
12966     break;
12967   case SC_Static:
12968     Error = 1;
12969     break;
12970   case SC_PrivateExtern:
12971     Error = 2;
12972     break;
12973   case SC_Auto:
12974     Error = 3;
12975     break;
12976   case SC_Register:
12977     Error = 4;
12978     break;
12979   }
12980 
12981   // for-range-declaration cannot be given a storage class specifier con't.
12982   switch (VD->getTSCSpec()) {
12983   case TSCS_thread_local:
12984     Error = 6;
12985     break;
12986   case TSCS___thread:
12987   case TSCS__Thread_local:
12988   case TSCS_unspecified:
12989     break;
12990   }
12991 
12992   if (Error != -1) {
12993     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12994         << VD << Error;
12995     D->setInvalidDecl();
12996   }
12997 }
12998 
12999 StmtResult
13000 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13001                                  IdentifierInfo *Ident,
13002                                  ParsedAttributes &Attrs,
13003                                  SourceLocation AttrEnd) {
13004   // C++1y [stmt.iter]p1:
13005   //   A range-based for statement of the form
13006   //      for ( for-range-identifier : for-range-initializer ) statement
13007   //   is equivalent to
13008   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13009   DeclSpec DS(Attrs.getPool().getFactory());
13010 
13011   const char *PrevSpec;
13012   unsigned DiagID;
13013   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13014                      getPrintingPolicy());
13015 
13016   Declarator D(DS, DeclaratorContext::ForInit);
13017   D.SetIdentifier(Ident, IdentLoc);
13018   D.takeAttributes(Attrs, AttrEnd);
13019 
13020   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13021                 IdentLoc);
13022   Decl *Var = ActOnDeclarator(S, D);
13023   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13024   FinalizeDeclaration(Var);
13025   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13026                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13027 }
13028 
13029 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13030   if (var->isInvalidDecl()) return;
13031 
13032   MaybeAddCUDAConstantAttr(var);
13033 
13034   if (getLangOpts().OpenCL) {
13035     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13036     // initialiser
13037     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13038         !var->hasInit()) {
13039       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13040           << 1 /*Init*/;
13041       var->setInvalidDecl();
13042       return;
13043     }
13044   }
13045 
13046   // In Objective-C, don't allow jumps past the implicit initialization of a
13047   // local retaining variable.
13048   if (getLangOpts().ObjC &&
13049       var->hasLocalStorage()) {
13050     switch (var->getType().getObjCLifetime()) {
13051     case Qualifiers::OCL_None:
13052     case Qualifiers::OCL_ExplicitNone:
13053     case Qualifiers::OCL_Autoreleasing:
13054       break;
13055 
13056     case Qualifiers::OCL_Weak:
13057     case Qualifiers::OCL_Strong:
13058       setFunctionHasBranchProtectedScope();
13059       break;
13060     }
13061   }
13062 
13063   if (var->hasLocalStorage() &&
13064       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13065     setFunctionHasBranchProtectedScope();
13066 
13067   // Warn about externally-visible variables being defined without a
13068   // prior declaration.  We only want to do this for global
13069   // declarations, but we also specifically need to avoid doing it for
13070   // class members because the linkage of an anonymous class can
13071   // change if it's later given a typedef name.
13072   if (var->isThisDeclarationADefinition() &&
13073       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13074       var->isExternallyVisible() && var->hasLinkage() &&
13075       !var->isInline() && !var->getDescribedVarTemplate() &&
13076       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13077       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13078       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13079                                   var->getLocation())) {
13080     // Find a previous declaration that's not a definition.
13081     VarDecl *prev = var->getPreviousDecl();
13082     while (prev && prev->isThisDeclarationADefinition())
13083       prev = prev->getPreviousDecl();
13084 
13085     if (!prev) {
13086       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13087       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13088           << /* variable */ 0;
13089     }
13090   }
13091 
13092   // Cache the result of checking for constant initialization.
13093   Optional<bool> CacheHasConstInit;
13094   const Expr *CacheCulprit = nullptr;
13095   auto checkConstInit = [&]() mutable {
13096     if (!CacheHasConstInit)
13097       CacheHasConstInit = var->getInit()->isConstantInitializer(
13098             Context, var->getType()->isReferenceType(), &CacheCulprit);
13099     return *CacheHasConstInit;
13100   };
13101 
13102   if (var->getTLSKind() == VarDecl::TLS_Static) {
13103     if (var->getType().isDestructedType()) {
13104       // GNU C++98 edits for __thread, [basic.start.term]p3:
13105       //   The type of an object with thread storage duration shall not
13106       //   have a non-trivial destructor.
13107       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13108       if (getLangOpts().CPlusPlus11)
13109         Diag(var->getLocation(), diag::note_use_thread_local);
13110     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13111       if (!checkConstInit()) {
13112         // GNU C++98 edits for __thread, [basic.start.init]p4:
13113         //   An object of thread storage duration shall not require dynamic
13114         //   initialization.
13115         // FIXME: Need strict checking here.
13116         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13117           << CacheCulprit->getSourceRange();
13118         if (getLangOpts().CPlusPlus11)
13119           Diag(var->getLocation(), diag::note_use_thread_local);
13120       }
13121     }
13122   }
13123 
13124 
13125   if (!var->getType()->isStructureType() && var->hasInit() &&
13126       isa<InitListExpr>(var->getInit())) {
13127     const auto *ILE = cast<InitListExpr>(var->getInit());
13128     unsigned NumInits = ILE->getNumInits();
13129     if (NumInits > 2)
13130       for (unsigned I = 0; I < NumInits; ++I) {
13131         const auto *Init = ILE->getInit(I);
13132         if (!Init)
13133           break;
13134         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13135         if (!SL)
13136           break;
13137 
13138         unsigned NumConcat = SL->getNumConcatenated();
13139         // Diagnose missing comma in string array initialization.
13140         // Do not warn when all the elements in the initializer are concatenated
13141         // together. Do not warn for macros too.
13142         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13143           bool OnlyOneMissingComma = true;
13144           for (unsigned J = I + 1; J < NumInits; ++J) {
13145             const auto *Init = ILE->getInit(J);
13146             if (!Init)
13147               break;
13148             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13149             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13150               OnlyOneMissingComma = false;
13151               break;
13152             }
13153           }
13154 
13155           if (OnlyOneMissingComma) {
13156             SmallVector<FixItHint, 1> Hints;
13157             for (unsigned i = 0; i < NumConcat - 1; ++i)
13158               Hints.push_back(FixItHint::CreateInsertion(
13159                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13160 
13161             Diag(SL->getStrTokenLoc(1),
13162                  diag::warn_concatenated_literal_array_init)
13163                 << Hints;
13164             Diag(SL->getBeginLoc(),
13165                  diag::note_concatenated_string_literal_silence);
13166           }
13167           // In any case, stop now.
13168           break;
13169         }
13170       }
13171   }
13172 
13173 
13174   QualType type = var->getType();
13175 
13176   if (var->hasAttr<BlocksAttr>())
13177     getCurFunction()->addByrefBlockVar(var);
13178 
13179   Expr *Init = var->getInit();
13180   bool GlobalStorage = var->hasGlobalStorage();
13181   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13182   QualType baseType = Context.getBaseElementType(type);
13183   bool HasConstInit = true;
13184 
13185   // Check whether the initializer is sufficiently constant.
13186   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13187       !Init->isValueDependent() &&
13188       (GlobalStorage || var->isConstexpr() ||
13189        var->mightBeUsableInConstantExpressions(Context))) {
13190     // If this variable might have a constant initializer or might be usable in
13191     // constant expressions, check whether or not it actually is now.  We can't
13192     // do this lazily, because the result might depend on things that change
13193     // later, such as which constexpr functions happen to be defined.
13194     SmallVector<PartialDiagnosticAt, 8> Notes;
13195     if (!getLangOpts().CPlusPlus11) {
13196       // Prior to C++11, in contexts where a constant initializer is required,
13197       // the set of valid constant initializers is described by syntactic rules
13198       // in [expr.const]p2-6.
13199       // FIXME: Stricter checking for these rules would be useful for constinit /
13200       // -Wglobal-constructors.
13201       HasConstInit = checkConstInit();
13202 
13203       // Compute and cache the constant value, and remember that we have a
13204       // constant initializer.
13205       if (HasConstInit) {
13206         (void)var->checkForConstantInitialization(Notes);
13207         Notes.clear();
13208       } else if (CacheCulprit) {
13209         Notes.emplace_back(CacheCulprit->getExprLoc(),
13210                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13211         Notes.back().second << CacheCulprit->getSourceRange();
13212       }
13213     } else {
13214       // Evaluate the initializer to see if it's a constant initializer.
13215       HasConstInit = var->checkForConstantInitialization(Notes);
13216     }
13217 
13218     if (HasConstInit) {
13219       // FIXME: Consider replacing the initializer with a ConstantExpr.
13220     } else if (var->isConstexpr()) {
13221       SourceLocation DiagLoc = var->getLocation();
13222       // If the note doesn't add any useful information other than a source
13223       // location, fold it into the primary diagnostic.
13224       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13225                                    diag::note_invalid_subexpr_in_const_expr) {
13226         DiagLoc = Notes[0].first;
13227         Notes.clear();
13228       }
13229       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13230           << var << Init->getSourceRange();
13231       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13232         Diag(Notes[I].first, Notes[I].second);
13233     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13234       auto *Attr = var->getAttr<ConstInitAttr>();
13235       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13236           << Init->getSourceRange();
13237       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13238           << Attr->getRange() << Attr->isConstinit();
13239       for (auto &it : Notes)
13240         Diag(it.first, it.second);
13241     } else if (IsGlobal &&
13242                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13243                                            var->getLocation())) {
13244       // Warn about globals which don't have a constant initializer.  Don't
13245       // warn about globals with a non-trivial destructor because we already
13246       // warned about them.
13247       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13248       if (!(RD && !RD->hasTrivialDestructor())) {
13249         // checkConstInit() here permits trivial default initialization even in
13250         // C++11 onwards, where such an initializer is not a constant initializer
13251         // but nonetheless doesn't require a global constructor.
13252         if (!checkConstInit())
13253           Diag(var->getLocation(), diag::warn_global_constructor)
13254               << Init->getSourceRange();
13255       }
13256     }
13257   }
13258 
13259   // Apply section attributes and pragmas to global variables.
13260   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13261       !inTemplateInstantiation()) {
13262     PragmaStack<StringLiteral *> *Stack = nullptr;
13263     int SectionFlags = ASTContext::PSF_Read;
13264     if (var->getType().isConstQualified()) {
13265       if (HasConstInit)
13266         Stack = &ConstSegStack;
13267       else {
13268         Stack = &BSSSegStack;
13269         SectionFlags |= ASTContext::PSF_Write;
13270       }
13271     } else if (var->hasInit() && HasConstInit) {
13272       Stack = &DataSegStack;
13273       SectionFlags |= ASTContext::PSF_Write;
13274     } else {
13275       Stack = &BSSSegStack;
13276       SectionFlags |= ASTContext::PSF_Write;
13277     }
13278     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13279       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13280         SectionFlags |= ASTContext::PSF_Implicit;
13281       UnifySection(SA->getName(), SectionFlags, var);
13282     } else if (Stack->CurrentValue) {
13283       SectionFlags |= ASTContext::PSF_Implicit;
13284       auto SectionName = Stack->CurrentValue->getString();
13285       var->addAttr(SectionAttr::CreateImplicit(
13286           Context, SectionName, Stack->CurrentPragmaLocation,
13287           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13288       if (UnifySection(SectionName, SectionFlags, var))
13289         var->dropAttr<SectionAttr>();
13290     }
13291 
13292     // Apply the init_seg attribute if this has an initializer.  If the
13293     // initializer turns out to not be dynamic, we'll end up ignoring this
13294     // attribute.
13295     if (CurInitSeg && var->getInit())
13296       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13297                                                CurInitSegLoc,
13298                                                AttributeCommonInfo::AS_Pragma));
13299   }
13300 
13301   // All the following checks are C++ only.
13302   if (!getLangOpts().CPlusPlus) {
13303     // If this variable must be emitted, add it as an initializer for the
13304     // current module.
13305     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13306       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13307     return;
13308   }
13309 
13310   // Require the destructor.
13311   if (!type->isDependentType())
13312     if (const RecordType *recordType = baseType->getAs<RecordType>())
13313       FinalizeVarWithDestructor(var, recordType);
13314 
13315   // If this variable must be emitted, add it as an initializer for the current
13316   // module.
13317   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13318     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13319 
13320   // Build the bindings if this is a structured binding declaration.
13321   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13322     CheckCompleteDecompositionDeclaration(DD);
13323 }
13324 
13325 /// Check if VD needs to be dllexport/dllimport due to being in a
13326 /// dllexport/import function.
13327 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13328   assert(VD->isStaticLocal());
13329 
13330   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13331 
13332   // Find outermost function when VD is in lambda function.
13333   while (FD && !getDLLAttr(FD) &&
13334          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13335          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13336     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13337   }
13338 
13339   if (!FD)
13340     return;
13341 
13342   // Static locals inherit dll attributes from their function.
13343   if (Attr *A = getDLLAttr(FD)) {
13344     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13345     NewAttr->setInherited(true);
13346     VD->addAttr(NewAttr);
13347   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13348     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13349     NewAttr->setInherited(true);
13350     VD->addAttr(NewAttr);
13351 
13352     // Export this function to enforce exporting this static variable even
13353     // if it is not used in this compilation unit.
13354     if (!FD->hasAttr<DLLExportAttr>())
13355       FD->addAttr(NewAttr);
13356 
13357   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13358     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13359     NewAttr->setInherited(true);
13360     VD->addAttr(NewAttr);
13361   }
13362 }
13363 
13364 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13365 /// any semantic actions necessary after any initializer has been attached.
13366 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13367   // Note that we are no longer parsing the initializer for this declaration.
13368   ParsingInitForAutoVars.erase(ThisDecl);
13369 
13370   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13371   if (!VD)
13372     return;
13373 
13374   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13375   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13376       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13377     if (PragmaClangBSSSection.Valid)
13378       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13379           Context, PragmaClangBSSSection.SectionName,
13380           PragmaClangBSSSection.PragmaLocation,
13381           AttributeCommonInfo::AS_Pragma));
13382     if (PragmaClangDataSection.Valid)
13383       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13384           Context, PragmaClangDataSection.SectionName,
13385           PragmaClangDataSection.PragmaLocation,
13386           AttributeCommonInfo::AS_Pragma));
13387     if (PragmaClangRodataSection.Valid)
13388       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13389           Context, PragmaClangRodataSection.SectionName,
13390           PragmaClangRodataSection.PragmaLocation,
13391           AttributeCommonInfo::AS_Pragma));
13392     if (PragmaClangRelroSection.Valid)
13393       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13394           Context, PragmaClangRelroSection.SectionName,
13395           PragmaClangRelroSection.PragmaLocation,
13396           AttributeCommonInfo::AS_Pragma));
13397   }
13398 
13399   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13400     for (auto *BD : DD->bindings()) {
13401       FinalizeDeclaration(BD);
13402     }
13403   }
13404 
13405   checkAttributesAfterMerging(*this, *VD);
13406 
13407   // Perform TLS alignment check here after attributes attached to the variable
13408   // which may affect the alignment have been processed. Only perform the check
13409   // if the target has a maximum TLS alignment (zero means no constraints).
13410   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13411     // Protect the check so that it's not performed on dependent types and
13412     // dependent alignments (we can't determine the alignment in that case).
13413     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13414       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13415       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13416         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13417           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13418           << (unsigned)MaxAlignChars.getQuantity();
13419       }
13420     }
13421   }
13422 
13423   if (VD->isStaticLocal())
13424     CheckStaticLocalForDllExport(VD);
13425 
13426   // Perform check for initializers of device-side global variables.
13427   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13428   // 7.5). We must also apply the same checks to all __shared__
13429   // variables whether they are local or not. CUDA also allows
13430   // constant initializers for __constant__ and __device__ variables.
13431   if (getLangOpts().CUDA)
13432     checkAllowedCUDAInitializer(VD);
13433 
13434   // Grab the dllimport or dllexport attribute off of the VarDecl.
13435   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13436 
13437   // Imported static data members cannot be defined out-of-line.
13438   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13439     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13440         VD->isThisDeclarationADefinition()) {
13441       // We allow definitions of dllimport class template static data members
13442       // with a warning.
13443       CXXRecordDecl *Context =
13444         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13445       bool IsClassTemplateMember =
13446           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13447           Context->getDescribedClassTemplate();
13448 
13449       Diag(VD->getLocation(),
13450            IsClassTemplateMember
13451                ? diag::warn_attribute_dllimport_static_field_definition
13452                : diag::err_attribute_dllimport_static_field_definition);
13453       Diag(IA->getLocation(), diag::note_attribute);
13454       if (!IsClassTemplateMember)
13455         VD->setInvalidDecl();
13456     }
13457   }
13458 
13459   // dllimport/dllexport variables cannot be thread local, their TLS index
13460   // isn't exported with the variable.
13461   if (DLLAttr && VD->getTLSKind()) {
13462     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13463     if (F && getDLLAttr(F)) {
13464       assert(VD->isStaticLocal());
13465       // But if this is a static local in a dlimport/dllexport function, the
13466       // function will never be inlined, which means the var would never be
13467       // imported, so having it marked import/export is safe.
13468     } else {
13469       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13470                                                                     << DLLAttr;
13471       VD->setInvalidDecl();
13472     }
13473   }
13474 
13475   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13476     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13477       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13478           << Attr;
13479       VD->dropAttr<UsedAttr>();
13480     }
13481   }
13482   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13483     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13484       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13485           << Attr;
13486       VD->dropAttr<RetainAttr>();
13487     }
13488   }
13489 
13490   const DeclContext *DC = VD->getDeclContext();
13491   // If there's a #pragma GCC visibility in scope, and this isn't a class
13492   // member, set the visibility of this variable.
13493   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13494     AddPushedVisibilityAttribute(VD);
13495 
13496   // FIXME: Warn on unused var template partial specializations.
13497   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13498     MarkUnusedFileScopedDecl(VD);
13499 
13500   // Now we have parsed the initializer and can update the table of magic
13501   // tag values.
13502   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13503       !VD->getType()->isIntegralOrEnumerationType())
13504     return;
13505 
13506   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13507     const Expr *MagicValueExpr = VD->getInit();
13508     if (!MagicValueExpr) {
13509       continue;
13510     }
13511     Optional<llvm::APSInt> MagicValueInt;
13512     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13513       Diag(I->getRange().getBegin(),
13514            diag::err_type_tag_for_datatype_not_ice)
13515         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13516       continue;
13517     }
13518     if (MagicValueInt->getActiveBits() > 64) {
13519       Diag(I->getRange().getBegin(),
13520            diag::err_type_tag_for_datatype_too_large)
13521         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13522       continue;
13523     }
13524     uint64_t MagicValue = MagicValueInt->getZExtValue();
13525     RegisterTypeTagForDatatype(I->getArgumentKind(),
13526                                MagicValue,
13527                                I->getMatchingCType(),
13528                                I->getLayoutCompatible(),
13529                                I->getMustBeNull());
13530   }
13531 }
13532 
13533 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13534   auto *VD = dyn_cast<VarDecl>(DD);
13535   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13536 }
13537 
13538 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13539                                                    ArrayRef<Decl *> Group) {
13540   SmallVector<Decl*, 8> Decls;
13541 
13542   if (DS.isTypeSpecOwned())
13543     Decls.push_back(DS.getRepAsDecl());
13544 
13545   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13546   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13547   bool DiagnosedMultipleDecomps = false;
13548   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13549   bool DiagnosedNonDeducedAuto = false;
13550 
13551   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13552     if (Decl *D = Group[i]) {
13553       // For declarators, there are some additional syntactic-ish checks we need
13554       // to perform.
13555       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13556         if (!FirstDeclaratorInGroup)
13557           FirstDeclaratorInGroup = DD;
13558         if (!FirstDecompDeclaratorInGroup)
13559           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13560         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13561             !hasDeducedAuto(DD))
13562           FirstNonDeducedAutoInGroup = DD;
13563 
13564         if (FirstDeclaratorInGroup != DD) {
13565           // A decomposition declaration cannot be combined with any other
13566           // declaration in the same group.
13567           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13568             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13569                  diag::err_decomp_decl_not_alone)
13570                 << FirstDeclaratorInGroup->getSourceRange()
13571                 << DD->getSourceRange();
13572             DiagnosedMultipleDecomps = true;
13573           }
13574 
13575           // A declarator that uses 'auto' in any way other than to declare a
13576           // variable with a deduced type cannot be combined with any other
13577           // declarator in the same group.
13578           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13579             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13580                  diag::err_auto_non_deduced_not_alone)
13581                 << FirstNonDeducedAutoInGroup->getType()
13582                        ->hasAutoForTrailingReturnType()
13583                 << FirstDeclaratorInGroup->getSourceRange()
13584                 << DD->getSourceRange();
13585             DiagnosedNonDeducedAuto = true;
13586           }
13587         }
13588       }
13589 
13590       Decls.push_back(D);
13591     }
13592   }
13593 
13594   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13595     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13596       handleTagNumbering(Tag, S);
13597       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13598           getLangOpts().CPlusPlus)
13599         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13600     }
13601   }
13602 
13603   return BuildDeclaratorGroup(Decls);
13604 }
13605 
13606 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13607 /// group, performing any necessary semantic checking.
13608 Sema::DeclGroupPtrTy
13609 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13610   // C++14 [dcl.spec.auto]p7: (DR1347)
13611   //   If the type that replaces the placeholder type is not the same in each
13612   //   deduction, the program is ill-formed.
13613   if (Group.size() > 1) {
13614     QualType Deduced;
13615     VarDecl *DeducedDecl = nullptr;
13616     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13617       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13618       if (!D || D->isInvalidDecl())
13619         break;
13620       DeducedType *DT = D->getType()->getContainedDeducedType();
13621       if (!DT || DT->getDeducedType().isNull())
13622         continue;
13623       if (Deduced.isNull()) {
13624         Deduced = DT->getDeducedType();
13625         DeducedDecl = D;
13626       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13627         auto *AT = dyn_cast<AutoType>(DT);
13628         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13629                         diag::err_auto_different_deductions)
13630                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13631                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13632                    << D->getDeclName();
13633         if (DeducedDecl->hasInit())
13634           Dia << DeducedDecl->getInit()->getSourceRange();
13635         if (D->getInit())
13636           Dia << D->getInit()->getSourceRange();
13637         D->setInvalidDecl();
13638         break;
13639       }
13640     }
13641   }
13642 
13643   ActOnDocumentableDecls(Group);
13644 
13645   return DeclGroupPtrTy::make(
13646       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13647 }
13648 
13649 void Sema::ActOnDocumentableDecl(Decl *D) {
13650   ActOnDocumentableDecls(D);
13651 }
13652 
13653 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13654   // Don't parse the comment if Doxygen diagnostics are ignored.
13655   if (Group.empty() || !Group[0])
13656     return;
13657 
13658   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13659                       Group[0]->getLocation()) &&
13660       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13661                       Group[0]->getLocation()))
13662     return;
13663 
13664   if (Group.size() >= 2) {
13665     // This is a decl group.  Normally it will contain only declarations
13666     // produced from declarator list.  But in case we have any definitions or
13667     // additional declaration references:
13668     //   'typedef struct S {} S;'
13669     //   'typedef struct S *S;'
13670     //   'struct S *pS;'
13671     // FinalizeDeclaratorGroup adds these as separate declarations.
13672     Decl *MaybeTagDecl = Group[0];
13673     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13674       Group = Group.slice(1);
13675     }
13676   }
13677 
13678   // FIMXE: We assume every Decl in the group is in the same file.
13679   // This is false when preprocessor constructs the group from decls in
13680   // different files (e. g. macros or #include).
13681   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13682 }
13683 
13684 /// Common checks for a parameter-declaration that should apply to both function
13685 /// parameters and non-type template parameters.
13686 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13687   // Check that there are no default arguments inside the type of this
13688   // parameter.
13689   if (getLangOpts().CPlusPlus)
13690     CheckExtraCXXDefaultArguments(D);
13691 
13692   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13693   if (D.getCXXScopeSpec().isSet()) {
13694     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13695       << D.getCXXScopeSpec().getRange();
13696   }
13697 
13698   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13699   // simple identifier except [...irrelevant cases...].
13700   switch (D.getName().getKind()) {
13701   case UnqualifiedIdKind::IK_Identifier:
13702     break;
13703 
13704   case UnqualifiedIdKind::IK_OperatorFunctionId:
13705   case UnqualifiedIdKind::IK_ConversionFunctionId:
13706   case UnqualifiedIdKind::IK_LiteralOperatorId:
13707   case UnqualifiedIdKind::IK_ConstructorName:
13708   case UnqualifiedIdKind::IK_DestructorName:
13709   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13710   case UnqualifiedIdKind::IK_DeductionGuideName:
13711     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13712       << GetNameForDeclarator(D).getName();
13713     break;
13714 
13715   case UnqualifiedIdKind::IK_TemplateId:
13716   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13717     // GetNameForDeclarator would not produce a useful name in this case.
13718     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13719     break;
13720   }
13721 }
13722 
13723 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13724 /// to introduce parameters into function prototype scope.
13725 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13726   const DeclSpec &DS = D.getDeclSpec();
13727 
13728   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13729 
13730   // C++03 [dcl.stc]p2 also permits 'auto'.
13731   StorageClass SC = SC_None;
13732   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13733     SC = SC_Register;
13734     // In C++11, the 'register' storage class specifier is deprecated.
13735     // In C++17, it is not allowed, but we tolerate it as an extension.
13736     if (getLangOpts().CPlusPlus11) {
13737       Diag(DS.getStorageClassSpecLoc(),
13738            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13739                                      : diag::warn_deprecated_register)
13740         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13741     }
13742   } else if (getLangOpts().CPlusPlus &&
13743              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13744     SC = SC_Auto;
13745   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13746     Diag(DS.getStorageClassSpecLoc(),
13747          diag::err_invalid_storage_class_in_func_decl);
13748     D.getMutableDeclSpec().ClearStorageClassSpecs();
13749   }
13750 
13751   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13752     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13753       << DeclSpec::getSpecifierName(TSCS);
13754   if (DS.isInlineSpecified())
13755     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13756         << getLangOpts().CPlusPlus17;
13757   if (DS.hasConstexprSpecifier())
13758     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13759         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13760 
13761   DiagnoseFunctionSpecifiers(DS);
13762 
13763   CheckFunctionOrTemplateParamDeclarator(S, D);
13764 
13765   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13766   QualType parmDeclType = TInfo->getType();
13767 
13768   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13769   IdentifierInfo *II = D.getIdentifier();
13770   if (II) {
13771     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13772                    ForVisibleRedeclaration);
13773     LookupName(R, S);
13774     if (R.isSingleResult()) {
13775       NamedDecl *PrevDecl = R.getFoundDecl();
13776       if (PrevDecl->isTemplateParameter()) {
13777         // Maybe we will complain about the shadowed template parameter.
13778         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13779         // Just pretend that we didn't see the previous declaration.
13780         PrevDecl = nullptr;
13781       } else if (S->isDeclScope(PrevDecl)) {
13782         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13783         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13784 
13785         // Recover by removing the name
13786         II = nullptr;
13787         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13788         D.setInvalidType(true);
13789       }
13790     }
13791   }
13792 
13793   // Temporarily put parameter variables in the translation unit, not
13794   // the enclosing context.  This prevents them from accidentally
13795   // looking like class members in C++.
13796   ParmVarDecl *New =
13797       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13798                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13799 
13800   if (D.isInvalidType())
13801     New->setInvalidDecl();
13802 
13803   assert(S->isFunctionPrototypeScope());
13804   assert(S->getFunctionPrototypeDepth() >= 1);
13805   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13806                     S->getNextFunctionPrototypeIndex());
13807 
13808   // Add the parameter declaration into this scope.
13809   S->AddDecl(New);
13810   if (II)
13811     IdResolver.AddDecl(New);
13812 
13813   ProcessDeclAttributes(S, New, D);
13814 
13815   if (D.getDeclSpec().isModulePrivateSpecified())
13816     Diag(New->getLocation(), diag::err_module_private_local)
13817         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13818         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13819 
13820   if (New->hasAttr<BlocksAttr>()) {
13821     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13822   }
13823 
13824   if (getLangOpts().OpenCL)
13825     deduceOpenCLAddressSpace(New);
13826 
13827   return New;
13828 }
13829 
13830 /// Synthesizes a variable for a parameter arising from a
13831 /// typedef.
13832 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13833                                               SourceLocation Loc,
13834                                               QualType T) {
13835   /* FIXME: setting StartLoc == Loc.
13836      Would it be worth to modify callers so as to provide proper source
13837      location for the unnamed parameters, embedding the parameter's type? */
13838   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13839                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13840                                            SC_None, nullptr);
13841   Param->setImplicit();
13842   return Param;
13843 }
13844 
13845 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13846   // Don't diagnose unused-parameter errors in template instantiations; we
13847   // will already have done so in the template itself.
13848   if (inTemplateInstantiation())
13849     return;
13850 
13851   for (const ParmVarDecl *Parameter : Parameters) {
13852     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13853         !Parameter->hasAttr<UnusedAttr>()) {
13854       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13855         << Parameter->getDeclName();
13856     }
13857   }
13858 }
13859 
13860 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13861     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13862   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13863     return;
13864 
13865   // Warn if the return value is pass-by-value and larger than the specified
13866   // threshold.
13867   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13868     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13869     if (Size > LangOpts.NumLargeByValueCopy)
13870       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13871   }
13872 
13873   // Warn if any parameter is pass-by-value and larger than the specified
13874   // threshold.
13875   for (const ParmVarDecl *Parameter : Parameters) {
13876     QualType T = Parameter->getType();
13877     if (T->isDependentType() || !T.isPODType(Context))
13878       continue;
13879     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13880     if (Size > LangOpts.NumLargeByValueCopy)
13881       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13882           << Parameter << Size;
13883   }
13884 }
13885 
13886 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13887                                   SourceLocation NameLoc, IdentifierInfo *Name,
13888                                   QualType T, TypeSourceInfo *TSInfo,
13889                                   StorageClass SC) {
13890   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13891   if (getLangOpts().ObjCAutoRefCount &&
13892       T.getObjCLifetime() == Qualifiers::OCL_None &&
13893       T->isObjCLifetimeType()) {
13894 
13895     Qualifiers::ObjCLifetime lifetime;
13896 
13897     // Special cases for arrays:
13898     //   - if it's const, use __unsafe_unretained
13899     //   - otherwise, it's an error
13900     if (T->isArrayType()) {
13901       if (!T.isConstQualified()) {
13902         if (DelayedDiagnostics.shouldDelayDiagnostics())
13903           DelayedDiagnostics.add(
13904               sema::DelayedDiagnostic::makeForbiddenType(
13905               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13906         else
13907           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13908               << TSInfo->getTypeLoc().getSourceRange();
13909       }
13910       lifetime = Qualifiers::OCL_ExplicitNone;
13911     } else {
13912       lifetime = T->getObjCARCImplicitLifetime();
13913     }
13914     T = Context.getLifetimeQualifiedType(T, lifetime);
13915   }
13916 
13917   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13918                                          Context.getAdjustedParameterType(T),
13919                                          TSInfo, SC, nullptr);
13920 
13921   // Make a note if we created a new pack in the scope of a lambda, so that
13922   // we know that references to that pack must also be expanded within the
13923   // lambda scope.
13924   if (New->isParameterPack())
13925     if (auto *LSI = getEnclosingLambda())
13926       LSI->LocalPacks.push_back(New);
13927 
13928   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13929       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13930     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13931                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13932 
13933   // Parameters can not be abstract class types.
13934   // For record types, this is done by the AbstractClassUsageDiagnoser once
13935   // the class has been completely parsed.
13936   if (!CurContext->isRecord() &&
13937       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13938                              AbstractParamType))
13939     New->setInvalidDecl();
13940 
13941   // Parameter declarators cannot be interface types. All ObjC objects are
13942   // passed by reference.
13943   if (T->isObjCObjectType()) {
13944     SourceLocation TypeEndLoc =
13945         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13946     Diag(NameLoc,
13947          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13948       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13949     T = Context.getObjCObjectPointerType(T);
13950     New->setType(T);
13951   }
13952 
13953   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13954   // duration shall not be qualified by an address-space qualifier."
13955   // Since all parameters have automatic store duration, they can not have
13956   // an address space.
13957   if (T.getAddressSpace() != LangAS::Default &&
13958       // OpenCL allows function arguments declared to be an array of a type
13959       // to be qualified with an address space.
13960       !(getLangOpts().OpenCL &&
13961         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13962     Diag(NameLoc, diag::err_arg_with_address_space);
13963     New->setInvalidDecl();
13964   }
13965 
13966   // PPC MMA non-pointer types are not allowed as function argument types.
13967   if (Context.getTargetInfo().getTriple().isPPC64() &&
13968       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13969     New->setInvalidDecl();
13970   }
13971 
13972   return New;
13973 }
13974 
13975 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13976                                            SourceLocation LocAfterDecls) {
13977   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13978 
13979   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13980   // for a K&R function.
13981   if (!FTI.hasPrototype) {
13982     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13983       --i;
13984       if (FTI.Params[i].Param == nullptr) {
13985         SmallString<256> Code;
13986         llvm::raw_svector_ostream(Code)
13987             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13988         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13989             << FTI.Params[i].Ident
13990             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13991 
13992         // Implicitly declare the argument as type 'int' for lack of a better
13993         // type.
13994         AttributeFactory attrs;
13995         DeclSpec DS(attrs);
13996         const char* PrevSpec; // unused
13997         unsigned DiagID; // unused
13998         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13999                            DiagID, Context.getPrintingPolicy());
14000         // Use the identifier location for the type source range.
14001         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14002         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14003         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14004         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14005         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14006       }
14007     }
14008   }
14009 }
14010 
14011 Decl *
14012 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14013                               MultiTemplateParamsArg TemplateParameterLists,
14014                               SkipBodyInfo *SkipBody) {
14015   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14016   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14017   Scope *ParentScope = FnBodyScope->getParent();
14018 
14019   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14020   // we define a non-templated function definition, we will create a declaration
14021   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14022   // The base function declaration will have the equivalent of an `omp declare
14023   // variant` annotation which specifies the mangled definition as a
14024   // specialization function under the OpenMP context defined as part of the
14025   // `omp begin declare variant`.
14026   SmallVector<FunctionDecl *, 4> Bases;
14027   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14028     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14029         ParentScope, D, TemplateParameterLists, Bases);
14030 
14031   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14032   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14033   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14034 
14035   if (!Bases.empty())
14036     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14037 
14038   return Dcl;
14039 }
14040 
14041 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14042   Consumer.HandleInlineFunctionDefinition(D);
14043 }
14044 
14045 static bool
14046 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14047                                 const FunctionDecl *&PossiblePrototype) {
14048   // Don't warn about invalid declarations.
14049   if (FD->isInvalidDecl())
14050     return false;
14051 
14052   // Or declarations that aren't global.
14053   if (!FD->isGlobal())
14054     return false;
14055 
14056   // Don't warn about C++ member functions.
14057   if (isa<CXXMethodDecl>(FD))
14058     return false;
14059 
14060   // Don't warn about 'main'.
14061   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14062     if (IdentifierInfo *II = FD->getIdentifier())
14063       if (II->isStr("main") || II->isStr("efi_main"))
14064         return false;
14065 
14066   // Don't warn about inline functions.
14067   if (FD->isInlined())
14068     return false;
14069 
14070   // Don't warn about function templates.
14071   if (FD->getDescribedFunctionTemplate())
14072     return false;
14073 
14074   // Don't warn about function template specializations.
14075   if (FD->isFunctionTemplateSpecialization())
14076     return false;
14077 
14078   // Don't warn for OpenCL kernels.
14079   if (FD->hasAttr<OpenCLKernelAttr>())
14080     return false;
14081 
14082   // Don't warn on explicitly deleted functions.
14083   if (FD->isDeleted())
14084     return false;
14085 
14086   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14087        Prev; Prev = Prev->getPreviousDecl()) {
14088     // Ignore any declarations that occur in function or method
14089     // scope, because they aren't visible from the header.
14090     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14091       continue;
14092 
14093     PossiblePrototype = Prev;
14094     return Prev->getType()->isFunctionNoProtoType();
14095   }
14096 
14097   return true;
14098 }
14099 
14100 void
14101 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14102                                    const FunctionDecl *EffectiveDefinition,
14103                                    SkipBodyInfo *SkipBody) {
14104   const FunctionDecl *Definition = EffectiveDefinition;
14105   if (!Definition &&
14106       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14107     return;
14108 
14109   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14110     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14111       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14112         // A merged copy of the same function, instantiated as a member of
14113         // the same class, is OK.
14114         if (declaresSameEntity(OrigFD, OrigDef) &&
14115             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14116                                cast<Decl>(FD->getLexicalDeclContext())))
14117           return;
14118       }
14119     }
14120   }
14121 
14122   if (canRedefineFunction(Definition, getLangOpts()))
14123     return;
14124 
14125   // Don't emit an error when this is redefinition of a typo-corrected
14126   // definition.
14127   if (TypoCorrectedFunctionDefinitions.count(Definition))
14128     return;
14129 
14130   // If we don't have a visible definition of the function, and it's inline or
14131   // a template, skip the new definition.
14132   if (SkipBody && !hasVisibleDefinition(Definition) &&
14133       (Definition->getFormalLinkage() == InternalLinkage ||
14134        Definition->isInlined() ||
14135        Definition->getDescribedFunctionTemplate() ||
14136        Definition->getNumTemplateParameterLists())) {
14137     SkipBody->ShouldSkip = true;
14138     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14139     if (auto *TD = Definition->getDescribedFunctionTemplate())
14140       makeMergedDefinitionVisible(TD);
14141     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14142     return;
14143   }
14144 
14145   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14146       Definition->getStorageClass() == SC_Extern)
14147     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14148         << FD << getLangOpts().CPlusPlus;
14149   else
14150     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14151 
14152   Diag(Definition->getLocation(), diag::note_previous_definition);
14153   FD->setInvalidDecl();
14154 }
14155 
14156 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14157                                    Sema &S) {
14158   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14159 
14160   LambdaScopeInfo *LSI = S.PushLambdaScope();
14161   LSI->CallOperator = CallOperator;
14162   LSI->Lambda = LambdaClass;
14163   LSI->ReturnType = CallOperator->getReturnType();
14164   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14165 
14166   if (LCD == LCD_None)
14167     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14168   else if (LCD == LCD_ByCopy)
14169     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14170   else if (LCD == LCD_ByRef)
14171     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14172   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14173 
14174   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14175   LSI->Mutable = !CallOperator->isConst();
14176 
14177   // Add the captures to the LSI so they can be noted as already
14178   // captured within tryCaptureVar.
14179   auto I = LambdaClass->field_begin();
14180   for (const auto &C : LambdaClass->captures()) {
14181     if (C.capturesVariable()) {
14182       VarDecl *VD = C.getCapturedVar();
14183       if (VD->isInitCapture())
14184         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14185       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14186       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14187           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14188           /*EllipsisLoc*/C.isPackExpansion()
14189                          ? C.getEllipsisLoc() : SourceLocation(),
14190           I->getType(), /*Invalid*/false);
14191 
14192     } else if (C.capturesThis()) {
14193       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14194                           C.getCaptureKind() == LCK_StarThis);
14195     } else {
14196       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14197                              I->getType());
14198     }
14199     ++I;
14200   }
14201 }
14202 
14203 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14204                                     SkipBodyInfo *SkipBody) {
14205   if (!D) {
14206     // Parsing the function declaration failed in some way. Push on a fake scope
14207     // anyway so we can try to parse the function body.
14208     PushFunctionScope();
14209     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14210     return D;
14211   }
14212 
14213   FunctionDecl *FD = nullptr;
14214 
14215   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14216     FD = FunTmpl->getTemplatedDecl();
14217   else
14218     FD = cast<FunctionDecl>(D);
14219 
14220   // Do not push if it is a lambda because one is already pushed when building
14221   // the lambda in ActOnStartOfLambdaDefinition().
14222   if (!isLambdaCallOperator(FD))
14223     PushExpressionEvaluationContext(
14224         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14225                           : ExprEvalContexts.back().Context);
14226 
14227   // Check for defining attributes before the check for redefinition.
14228   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14229     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14230     FD->dropAttr<AliasAttr>();
14231     FD->setInvalidDecl();
14232   }
14233   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14234     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14235     FD->dropAttr<IFuncAttr>();
14236     FD->setInvalidDecl();
14237   }
14238 
14239   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14240     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14241         Ctor->isDefaultConstructor() &&
14242         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14243       // If this is an MS ABI dllexport default constructor, instantiate any
14244       // default arguments.
14245       InstantiateDefaultCtorDefaultArgs(Ctor);
14246     }
14247   }
14248 
14249   // See if this is a redefinition. If 'will have body' (or similar) is already
14250   // set, then these checks were already performed when it was set.
14251   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14252       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14253     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14254 
14255     // If we're skipping the body, we're done. Don't enter the scope.
14256     if (SkipBody && SkipBody->ShouldSkip)
14257       return D;
14258   }
14259 
14260   // Mark this function as "will have a body eventually".  This lets users to
14261   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14262   // this function.
14263   FD->setWillHaveBody();
14264 
14265   // If we are instantiating a generic lambda call operator, push
14266   // a LambdaScopeInfo onto the function stack.  But use the information
14267   // that's already been calculated (ActOnLambdaExpr) to prime the current
14268   // LambdaScopeInfo.
14269   // When the template operator is being specialized, the LambdaScopeInfo,
14270   // has to be properly restored so that tryCaptureVariable doesn't try
14271   // and capture any new variables. In addition when calculating potential
14272   // captures during transformation of nested lambdas, it is necessary to
14273   // have the LSI properly restored.
14274   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14275     assert(inTemplateInstantiation() &&
14276            "There should be an active template instantiation on the stack "
14277            "when instantiating a generic lambda!");
14278     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14279   } else {
14280     // Enter a new function scope
14281     PushFunctionScope();
14282   }
14283 
14284   // Builtin functions cannot be defined.
14285   if (unsigned BuiltinID = FD->getBuiltinID()) {
14286     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14287         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14288       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14289       FD->setInvalidDecl();
14290     }
14291   }
14292 
14293   // The return type of a function definition must be complete
14294   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14295   QualType ResultType = FD->getReturnType();
14296   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14297       !FD->isInvalidDecl() &&
14298       RequireCompleteType(FD->getLocation(), ResultType,
14299                           diag::err_func_def_incomplete_result))
14300     FD->setInvalidDecl();
14301 
14302   if (FnBodyScope)
14303     PushDeclContext(FnBodyScope, FD);
14304 
14305   // Check the validity of our function parameters
14306   CheckParmsForFunctionDef(FD->parameters(),
14307                            /*CheckParameterNames=*/true);
14308 
14309   // Add non-parameter declarations already in the function to the current
14310   // scope.
14311   if (FnBodyScope) {
14312     for (Decl *NPD : FD->decls()) {
14313       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14314       if (!NonParmDecl)
14315         continue;
14316       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14317              "parameters should not be in newly created FD yet");
14318 
14319       // If the decl has a name, make it accessible in the current scope.
14320       if (NonParmDecl->getDeclName())
14321         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14322 
14323       // Similarly, dive into enums and fish their constants out, making them
14324       // accessible in this scope.
14325       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14326         for (auto *EI : ED->enumerators())
14327           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14328       }
14329     }
14330   }
14331 
14332   // Introduce our parameters into the function scope
14333   for (auto Param : FD->parameters()) {
14334     Param->setOwningFunction(FD);
14335 
14336     // If this has an identifier, add it to the scope stack.
14337     if (Param->getIdentifier() && FnBodyScope) {
14338       CheckShadow(FnBodyScope, Param);
14339 
14340       PushOnScopeChains(Param, FnBodyScope);
14341     }
14342   }
14343 
14344   // Ensure that the function's exception specification is instantiated.
14345   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14346     ResolveExceptionSpec(D->getLocation(), FPT);
14347 
14348   // dllimport cannot be applied to non-inline function definitions.
14349   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14350       !FD->isTemplateInstantiation()) {
14351     assert(!FD->hasAttr<DLLExportAttr>());
14352     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14353     FD->setInvalidDecl();
14354     return D;
14355   }
14356   // We want to attach documentation to original Decl (which might be
14357   // a function template).
14358   ActOnDocumentableDecl(D);
14359   if (getCurLexicalContext()->isObjCContainer() &&
14360       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14361       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14362     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14363 
14364   return D;
14365 }
14366 
14367 /// Given the set of return statements within a function body,
14368 /// compute the variables that are subject to the named return value
14369 /// optimization.
14370 ///
14371 /// Each of the variables that is subject to the named return value
14372 /// optimization will be marked as NRVO variables in the AST, and any
14373 /// return statement that has a marked NRVO variable as its NRVO candidate can
14374 /// use the named return value optimization.
14375 ///
14376 /// This function applies a very simplistic algorithm for NRVO: if every return
14377 /// statement in the scope of a variable has the same NRVO candidate, that
14378 /// candidate is an NRVO variable.
14379 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14380   ReturnStmt **Returns = Scope->Returns.data();
14381 
14382   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14383     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14384       if (!NRVOCandidate->isNRVOVariable())
14385         Returns[I]->setNRVOCandidate(nullptr);
14386     }
14387   }
14388 }
14389 
14390 bool Sema::canDelayFunctionBody(const Declarator &D) {
14391   // We can't delay parsing the body of a constexpr function template (yet).
14392   if (D.getDeclSpec().hasConstexprSpecifier())
14393     return false;
14394 
14395   // We can't delay parsing the body of a function template with a deduced
14396   // return type (yet).
14397   if (D.getDeclSpec().hasAutoTypeSpec()) {
14398     // If the placeholder introduces a non-deduced trailing return type,
14399     // we can still delay parsing it.
14400     if (D.getNumTypeObjects()) {
14401       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14402       if (Outer.Kind == DeclaratorChunk::Function &&
14403           Outer.Fun.hasTrailingReturnType()) {
14404         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14405         return Ty.isNull() || !Ty->isUndeducedType();
14406       }
14407     }
14408     return false;
14409   }
14410 
14411   return true;
14412 }
14413 
14414 bool Sema::canSkipFunctionBody(Decl *D) {
14415   // We cannot skip the body of a function (or function template) which is
14416   // constexpr, since we may need to evaluate its body in order to parse the
14417   // rest of the file.
14418   // We cannot skip the body of a function with an undeduced return type,
14419   // because any callers of that function need to know the type.
14420   if (const FunctionDecl *FD = D->getAsFunction()) {
14421     if (FD->isConstexpr())
14422       return false;
14423     // We can't simply call Type::isUndeducedType here, because inside template
14424     // auto can be deduced to a dependent type, which is not considered
14425     // "undeduced".
14426     if (FD->getReturnType()->getContainedDeducedType())
14427       return false;
14428   }
14429   return Consumer.shouldSkipFunctionBody(D);
14430 }
14431 
14432 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14433   if (!Decl)
14434     return nullptr;
14435   if (FunctionDecl *FD = Decl->getAsFunction())
14436     FD->setHasSkippedBody();
14437   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14438     MD->setHasSkippedBody();
14439   return Decl;
14440 }
14441 
14442 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14443   return ActOnFinishFunctionBody(D, BodyArg, false);
14444 }
14445 
14446 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14447 /// body.
14448 class ExitFunctionBodyRAII {
14449 public:
14450   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14451   ~ExitFunctionBodyRAII() {
14452     if (!IsLambda)
14453       S.PopExpressionEvaluationContext();
14454   }
14455 
14456 private:
14457   Sema &S;
14458   bool IsLambda = false;
14459 };
14460 
14461 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14462   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14463 
14464   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14465     if (EscapeInfo.count(BD))
14466       return EscapeInfo[BD];
14467 
14468     bool R = false;
14469     const BlockDecl *CurBD = BD;
14470 
14471     do {
14472       R = !CurBD->doesNotEscape();
14473       if (R)
14474         break;
14475       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14476     } while (CurBD);
14477 
14478     return EscapeInfo[BD] = R;
14479   };
14480 
14481   // If the location where 'self' is implicitly retained is inside a escaping
14482   // block, emit a diagnostic.
14483   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14484        S.ImplicitlyRetainedSelfLocs)
14485     if (IsOrNestedInEscapingBlock(P.second))
14486       S.Diag(P.first, diag::warn_implicitly_retains_self)
14487           << FixItHint::CreateInsertion(P.first, "self->");
14488 }
14489 
14490 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14491                                     bool IsInstantiation) {
14492   FunctionScopeInfo *FSI = getCurFunction();
14493   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14494 
14495   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14496     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14497 
14498   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14499   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14500 
14501   if (getLangOpts().Coroutines && FSI->isCoroutine())
14502     CheckCompletedCoroutineBody(FD, Body);
14503 
14504   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14505   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14506   // meant to pop the context added in ActOnStartOfFunctionDef().
14507   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14508 
14509   if (FD) {
14510     FD->setBody(Body);
14511     FD->setWillHaveBody(false);
14512 
14513     if (getLangOpts().CPlusPlus14) {
14514       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14515           FD->getReturnType()->isUndeducedType()) {
14516         // If the function has a deduced result type but contains no 'return'
14517         // statements, the result type as written must be exactly 'auto', and
14518         // the deduced result type is 'void'.
14519         if (!FD->getReturnType()->getAs<AutoType>()) {
14520           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14521               << FD->getReturnType();
14522           FD->setInvalidDecl();
14523         } else {
14524           // Substitute 'void' for the 'auto' in the type.
14525           TypeLoc ResultType = getReturnTypeLoc(FD);
14526           Context.adjustDeducedFunctionResultType(
14527               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14528         }
14529       }
14530     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14531       // In C++11, we don't use 'auto' deduction rules for lambda call
14532       // operators because we don't support return type deduction.
14533       auto *LSI = getCurLambda();
14534       if (LSI->HasImplicitReturnType) {
14535         deduceClosureReturnType(*LSI);
14536 
14537         // C++11 [expr.prim.lambda]p4:
14538         //   [...] if there are no return statements in the compound-statement
14539         //   [the deduced type is] the type void
14540         QualType RetType =
14541             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14542 
14543         // Update the return type to the deduced type.
14544         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14545         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14546                                             Proto->getExtProtoInfo()));
14547       }
14548     }
14549 
14550     // If the function implicitly returns zero (like 'main') or is naked,
14551     // don't complain about missing return statements.
14552     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14553       WP.disableCheckFallThrough();
14554 
14555     // MSVC permits the use of pure specifier (=0) on function definition,
14556     // defined at class scope, warn about this non-standard construct.
14557     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14558       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14559 
14560     if (!FD->isInvalidDecl()) {
14561       // Don't diagnose unused parameters of defaulted or deleted functions.
14562       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14563         DiagnoseUnusedParameters(FD->parameters());
14564       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14565                                              FD->getReturnType(), FD);
14566 
14567       // If this is a structor, we need a vtable.
14568       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14569         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14570       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14571         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14572 
14573       // Try to apply the named return value optimization. We have to check
14574       // if we can do this here because lambdas keep return statements around
14575       // to deduce an implicit return type.
14576       if (FD->getReturnType()->isRecordType() &&
14577           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14578         computeNRVO(Body, FSI);
14579     }
14580 
14581     // GNU warning -Wmissing-prototypes:
14582     //   Warn if a global function is defined without a previous
14583     //   prototype declaration. This warning is issued even if the
14584     //   definition itself provides a prototype. The aim is to detect
14585     //   global functions that fail to be declared in header files.
14586     const FunctionDecl *PossiblePrototype = nullptr;
14587     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14588       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14589 
14590       if (PossiblePrototype) {
14591         // We found a declaration that is not a prototype,
14592         // but that could be a zero-parameter prototype
14593         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14594           TypeLoc TL = TI->getTypeLoc();
14595           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14596             Diag(PossiblePrototype->getLocation(),
14597                  diag::note_declaration_not_a_prototype)
14598                 << (FD->getNumParams() != 0)
14599                 << (FD->getNumParams() == 0
14600                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14601                         : FixItHint{});
14602         }
14603       } else {
14604         // Returns true if the token beginning at this Loc is `const`.
14605         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14606                                 const LangOptions &LangOpts) {
14607           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14608           if (LocInfo.first.isInvalid())
14609             return false;
14610 
14611           bool Invalid = false;
14612           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14613           if (Invalid)
14614             return false;
14615 
14616           if (LocInfo.second > Buffer.size())
14617             return false;
14618 
14619           const char *LexStart = Buffer.data() + LocInfo.second;
14620           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14621 
14622           return StartTok.consume_front("const") &&
14623                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14624                   StartTok.startswith("/*") || StartTok.startswith("//"));
14625         };
14626 
14627         auto findBeginLoc = [&]() {
14628           // If the return type has `const` qualifier, we want to insert
14629           // `static` before `const` (and not before the typename).
14630           if ((FD->getReturnType()->isAnyPointerType() &&
14631                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14632               FD->getReturnType().isConstQualified()) {
14633             // But only do this if we can determine where the `const` is.
14634 
14635             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14636                              getLangOpts()))
14637 
14638               return FD->getBeginLoc();
14639           }
14640           return FD->getTypeSpecStartLoc();
14641         };
14642         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14643             << /* function */ 1
14644             << (FD->getStorageClass() == SC_None
14645                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14646                     : FixItHint{});
14647       }
14648 
14649       // GNU warning -Wstrict-prototypes
14650       //   Warn if K&R function is defined without a previous declaration.
14651       //   This warning is issued only if the definition itself does not provide
14652       //   a prototype. Only K&R definitions do not provide a prototype.
14653       if (!FD->hasWrittenPrototype()) {
14654         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14655         TypeLoc TL = TI->getTypeLoc();
14656         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14657         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14658       }
14659     }
14660 
14661     // Warn on CPUDispatch with an actual body.
14662     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14663       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14664         if (!CmpndBody->body_empty())
14665           Diag(CmpndBody->body_front()->getBeginLoc(),
14666                diag::warn_dispatch_body_ignored);
14667 
14668     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14669       const CXXMethodDecl *KeyFunction;
14670       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14671           MD->isVirtual() &&
14672           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14673           MD == KeyFunction->getCanonicalDecl()) {
14674         // Update the key-function state if necessary for this ABI.
14675         if (FD->isInlined() &&
14676             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14677           Context.setNonKeyFunction(MD);
14678 
14679           // If the newly-chosen key function is already defined, then we
14680           // need to mark the vtable as used retroactively.
14681           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14682           const FunctionDecl *Definition;
14683           if (KeyFunction && KeyFunction->isDefined(Definition))
14684             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14685         } else {
14686           // We just defined they key function; mark the vtable as used.
14687           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14688         }
14689       }
14690     }
14691 
14692     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14693            "Function parsing confused");
14694   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14695     assert(MD == getCurMethodDecl() && "Method parsing confused");
14696     MD->setBody(Body);
14697     if (!MD->isInvalidDecl()) {
14698       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14699                                              MD->getReturnType(), MD);
14700 
14701       if (Body)
14702         computeNRVO(Body, FSI);
14703     }
14704     if (FSI->ObjCShouldCallSuper) {
14705       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14706           << MD->getSelector().getAsString();
14707       FSI->ObjCShouldCallSuper = false;
14708     }
14709     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14710       const ObjCMethodDecl *InitMethod = nullptr;
14711       bool isDesignated =
14712           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14713       assert(isDesignated && InitMethod);
14714       (void)isDesignated;
14715 
14716       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14717         auto IFace = MD->getClassInterface();
14718         if (!IFace)
14719           return false;
14720         auto SuperD = IFace->getSuperClass();
14721         if (!SuperD)
14722           return false;
14723         return SuperD->getIdentifier() ==
14724             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14725       };
14726       // Don't issue this warning for unavailable inits or direct subclasses
14727       // of NSObject.
14728       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14729         Diag(MD->getLocation(),
14730              diag::warn_objc_designated_init_missing_super_call);
14731         Diag(InitMethod->getLocation(),
14732              diag::note_objc_designated_init_marked_here);
14733       }
14734       FSI->ObjCWarnForNoDesignatedInitChain = false;
14735     }
14736     if (FSI->ObjCWarnForNoInitDelegation) {
14737       // Don't issue this warning for unavaialable inits.
14738       if (!MD->isUnavailable())
14739         Diag(MD->getLocation(),
14740              diag::warn_objc_secondary_init_missing_init_call);
14741       FSI->ObjCWarnForNoInitDelegation = false;
14742     }
14743 
14744     diagnoseImplicitlyRetainedSelf(*this);
14745   } else {
14746     // Parsing the function declaration failed in some way. Pop the fake scope
14747     // we pushed on.
14748     PopFunctionScopeInfo(ActivePolicy, dcl);
14749     return nullptr;
14750   }
14751 
14752   if (Body && FSI->HasPotentialAvailabilityViolations)
14753     DiagnoseUnguardedAvailabilityViolations(dcl);
14754 
14755   assert(!FSI->ObjCShouldCallSuper &&
14756          "This should only be set for ObjC methods, which should have been "
14757          "handled in the block above.");
14758 
14759   // Verify and clean out per-function state.
14760   if (Body && (!FD || !FD->isDefaulted())) {
14761     // C++ constructors that have function-try-blocks can't have return
14762     // statements in the handlers of that block. (C++ [except.handle]p14)
14763     // Verify this.
14764     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14765       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14766 
14767     // Verify that gotos and switch cases don't jump into scopes illegally.
14768     if (FSI->NeedsScopeChecking() &&
14769         !PP.isCodeCompletionEnabled())
14770       DiagnoseInvalidJumps(Body);
14771 
14772     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14773       if (!Destructor->getParent()->isDependentType())
14774         CheckDestructor(Destructor);
14775 
14776       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14777                                              Destructor->getParent());
14778     }
14779 
14780     // If any errors have occurred, clear out any temporaries that may have
14781     // been leftover. This ensures that these temporaries won't be picked up for
14782     // deletion in some later function.
14783     if (hasUncompilableErrorOccurred() ||
14784         getDiagnostics().getSuppressAllDiagnostics()) {
14785       DiscardCleanupsInEvaluationContext();
14786     }
14787     if (!hasUncompilableErrorOccurred() &&
14788         !isa<FunctionTemplateDecl>(dcl)) {
14789       // Since the body is valid, issue any analysis-based warnings that are
14790       // enabled.
14791       ActivePolicy = &WP;
14792     }
14793 
14794     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14795         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14796       FD->setInvalidDecl();
14797 
14798     if (FD && FD->hasAttr<NakedAttr>()) {
14799       for (const Stmt *S : Body->children()) {
14800         // Allow local register variables without initializer as they don't
14801         // require prologue.
14802         bool RegisterVariables = false;
14803         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14804           for (const auto *Decl : DS->decls()) {
14805             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14806               RegisterVariables =
14807                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14808               if (!RegisterVariables)
14809                 break;
14810             }
14811           }
14812         }
14813         if (RegisterVariables)
14814           continue;
14815         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14816           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14817           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14818           FD->setInvalidDecl();
14819           break;
14820         }
14821       }
14822     }
14823 
14824     assert(ExprCleanupObjects.size() ==
14825                ExprEvalContexts.back().NumCleanupObjects &&
14826            "Leftover temporaries in function");
14827     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14828     assert(MaybeODRUseExprs.empty() &&
14829            "Leftover expressions for odr-use checking");
14830   }
14831 
14832   if (!IsInstantiation)
14833     PopDeclContext();
14834 
14835   PopFunctionScopeInfo(ActivePolicy, dcl);
14836   // If any errors have occurred, clear out any temporaries that may have
14837   // been leftover. This ensures that these temporaries won't be picked up for
14838   // deletion in some later function.
14839   if (hasUncompilableErrorOccurred()) {
14840     DiscardCleanupsInEvaluationContext();
14841   }
14842 
14843   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14844     auto ES = getEmissionStatus(FD);
14845     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14846         ES == Sema::FunctionEmissionStatus::Unknown)
14847       DeclsToCheckForDeferredDiags.insert(FD);
14848   }
14849 
14850   return dcl;
14851 }
14852 
14853 /// When we finish delayed parsing of an attribute, we must attach it to the
14854 /// relevant Decl.
14855 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14856                                        ParsedAttributes &Attrs) {
14857   // Always attach attributes to the underlying decl.
14858   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14859     D = TD->getTemplatedDecl();
14860   ProcessDeclAttributeList(S, D, Attrs);
14861 
14862   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14863     if (Method->isStatic())
14864       checkThisInStaticMemberFunctionAttributes(Method);
14865 }
14866 
14867 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14868 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14869 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14870                                           IdentifierInfo &II, Scope *S) {
14871   // Find the scope in which the identifier is injected and the corresponding
14872   // DeclContext.
14873   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14874   // In that case, we inject the declaration into the translation unit scope
14875   // instead.
14876   Scope *BlockScope = S;
14877   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14878     BlockScope = BlockScope->getParent();
14879 
14880   Scope *ContextScope = BlockScope;
14881   while (!ContextScope->getEntity())
14882     ContextScope = ContextScope->getParent();
14883   ContextRAII SavedContext(*this, ContextScope->getEntity());
14884 
14885   // Before we produce a declaration for an implicitly defined
14886   // function, see whether there was a locally-scoped declaration of
14887   // this name as a function or variable. If so, use that
14888   // (non-visible) declaration, and complain about it.
14889   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14890   if (ExternCPrev) {
14891     // We still need to inject the function into the enclosing block scope so
14892     // that later (non-call) uses can see it.
14893     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14894 
14895     // C89 footnote 38:
14896     //   If in fact it is not defined as having type "function returning int",
14897     //   the behavior is undefined.
14898     if (!isa<FunctionDecl>(ExternCPrev) ||
14899         !Context.typesAreCompatible(
14900             cast<FunctionDecl>(ExternCPrev)->getType(),
14901             Context.getFunctionNoProtoType(Context.IntTy))) {
14902       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14903           << ExternCPrev << !getLangOpts().C99;
14904       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14905       return ExternCPrev;
14906     }
14907   }
14908 
14909   // Extension in C99.  Legal in C90, but warn about it.
14910   unsigned diag_id;
14911   if (II.getName().startswith("__builtin_"))
14912     diag_id = diag::warn_builtin_unknown;
14913   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14914   else if (getLangOpts().OpenCL)
14915     diag_id = diag::err_opencl_implicit_function_decl;
14916   else if (getLangOpts().C99)
14917     diag_id = diag::ext_implicit_function_decl;
14918   else
14919     diag_id = diag::warn_implicit_function_decl;
14920   Diag(Loc, diag_id) << &II;
14921 
14922   // If we found a prior declaration of this function, don't bother building
14923   // another one. We've already pushed that one into scope, so there's nothing
14924   // more to do.
14925   if (ExternCPrev)
14926     return ExternCPrev;
14927 
14928   // Because typo correction is expensive, only do it if the implicit
14929   // function declaration is going to be treated as an error.
14930   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14931     TypoCorrection Corrected;
14932     DeclFilterCCC<FunctionDecl> CCC{};
14933     if (S && (Corrected =
14934                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14935                               S, nullptr, CCC, CTK_NonError)))
14936       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14937                    /*ErrorRecovery*/false);
14938   }
14939 
14940   // Set a Declarator for the implicit definition: int foo();
14941   const char *Dummy;
14942   AttributeFactory attrFactory;
14943   DeclSpec DS(attrFactory);
14944   unsigned DiagID;
14945   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14946                                   Context.getPrintingPolicy());
14947   (void)Error; // Silence warning.
14948   assert(!Error && "Error setting up implicit decl!");
14949   SourceLocation NoLoc;
14950   Declarator D(DS, DeclaratorContext::Block);
14951   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14952                                              /*IsAmbiguous=*/false,
14953                                              /*LParenLoc=*/NoLoc,
14954                                              /*Params=*/nullptr,
14955                                              /*NumParams=*/0,
14956                                              /*EllipsisLoc=*/NoLoc,
14957                                              /*RParenLoc=*/NoLoc,
14958                                              /*RefQualifierIsLvalueRef=*/true,
14959                                              /*RefQualifierLoc=*/NoLoc,
14960                                              /*MutableLoc=*/NoLoc, EST_None,
14961                                              /*ESpecRange=*/SourceRange(),
14962                                              /*Exceptions=*/nullptr,
14963                                              /*ExceptionRanges=*/nullptr,
14964                                              /*NumExceptions=*/0,
14965                                              /*NoexceptExpr=*/nullptr,
14966                                              /*ExceptionSpecTokens=*/nullptr,
14967                                              /*DeclsInPrototype=*/None, Loc,
14968                                              Loc, D),
14969                 std::move(DS.getAttributes()), SourceLocation());
14970   D.SetIdentifier(&II, Loc);
14971 
14972   // Insert this function into the enclosing block scope.
14973   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14974   FD->setImplicit();
14975 
14976   AddKnownFunctionAttributes(FD);
14977 
14978   return FD;
14979 }
14980 
14981 /// If this function is a C++ replaceable global allocation function
14982 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14983 /// adds any function attributes that we know a priori based on the standard.
14984 ///
14985 /// We need to check for duplicate attributes both here and where user-written
14986 /// attributes are applied to declarations.
14987 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14988     FunctionDecl *FD) {
14989   if (FD->isInvalidDecl())
14990     return;
14991 
14992   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14993       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14994     return;
14995 
14996   Optional<unsigned> AlignmentParam;
14997   bool IsNothrow = false;
14998   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14999     return;
15000 
15001   // C++2a [basic.stc.dynamic.allocation]p4:
15002   //   An allocation function that has a non-throwing exception specification
15003   //   indicates failure by returning a null pointer value. Any other allocation
15004   //   function never returns a null pointer value and indicates failure only by
15005   //   throwing an exception [...]
15006   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15007     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15008 
15009   // C++2a [basic.stc.dynamic.allocation]p2:
15010   //   An allocation function attempts to allocate the requested amount of
15011   //   storage. [...] If the request succeeds, the value returned by a
15012   //   replaceable allocation function is a [...] pointer value p0 different
15013   //   from any previously returned value p1 [...]
15014   //
15015   // However, this particular information is being added in codegen,
15016   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15017 
15018   // C++2a [basic.stc.dynamic.allocation]p2:
15019   //   An allocation function attempts to allocate the requested amount of
15020   //   storage. If it is successful, it returns the address of the start of a
15021   //   block of storage whose length in bytes is at least as large as the
15022   //   requested size.
15023   if (!FD->hasAttr<AllocSizeAttr>()) {
15024     FD->addAttr(AllocSizeAttr::CreateImplicit(
15025         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15026         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15027   }
15028 
15029   // C++2a [basic.stc.dynamic.allocation]p3:
15030   //   For an allocation function [...], the pointer returned on a successful
15031   //   call shall represent the address of storage that is aligned as follows:
15032   //   (3.1) If the allocation function takes an argument of type
15033   //         std​::​align_­val_­t, the storage will have the alignment
15034   //         specified by the value of this argument.
15035   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15036     FD->addAttr(AllocAlignAttr::CreateImplicit(
15037         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15038   }
15039 
15040   // FIXME:
15041   // C++2a [basic.stc.dynamic.allocation]p3:
15042   //   For an allocation function [...], the pointer returned on a successful
15043   //   call shall represent the address of storage that is aligned as follows:
15044   //   (3.2) Otherwise, if the allocation function is named operator new[],
15045   //         the storage is aligned for any object that does not have
15046   //         new-extended alignment ([basic.align]) and is no larger than the
15047   //         requested size.
15048   //   (3.3) Otherwise, the storage is aligned for any object that does not
15049   //         have new-extended alignment and is of the requested size.
15050 }
15051 
15052 /// Adds any function attributes that we know a priori based on
15053 /// the declaration of this function.
15054 ///
15055 /// These attributes can apply both to implicitly-declared builtins
15056 /// (like __builtin___printf_chk) or to library-declared functions
15057 /// like NSLog or printf.
15058 ///
15059 /// We need to check for duplicate attributes both here and where user-written
15060 /// attributes are applied to declarations.
15061 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15062   if (FD->isInvalidDecl())
15063     return;
15064 
15065   // If this is a built-in function, map its builtin attributes to
15066   // actual attributes.
15067   if (unsigned BuiltinID = FD->getBuiltinID()) {
15068     // Handle printf-formatting attributes.
15069     unsigned FormatIdx;
15070     bool HasVAListArg;
15071     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15072       if (!FD->hasAttr<FormatAttr>()) {
15073         const char *fmt = "printf";
15074         unsigned int NumParams = FD->getNumParams();
15075         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15076             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15077           fmt = "NSString";
15078         FD->addAttr(FormatAttr::CreateImplicit(Context,
15079                                                &Context.Idents.get(fmt),
15080                                                FormatIdx+1,
15081                                                HasVAListArg ? 0 : FormatIdx+2,
15082                                                FD->getLocation()));
15083       }
15084     }
15085     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15086                                              HasVAListArg)) {
15087      if (!FD->hasAttr<FormatAttr>())
15088        FD->addAttr(FormatAttr::CreateImplicit(Context,
15089                                               &Context.Idents.get("scanf"),
15090                                               FormatIdx+1,
15091                                               HasVAListArg ? 0 : FormatIdx+2,
15092                                               FD->getLocation()));
15093     }
15094 
15095     // Handle automatically recognized callbacks.
15096     SmallVector<int, 4> Encoding;
15097     if (!FD->hasAttr<CallbackAttr>() &&
15098         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15099       FD->addAttr(CallbackAttr::CreateImplicit(
15100           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15101 
15102     // Mark const if we don't care about errno and that is the only thing
15103     // preventing the function from being const. This allows IRgen to use LLVM
15104     // intrinsics for such functions.
15105     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15106         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15107       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15108 
15109     // We make "fma" on some platforms const because we know it does not set
15110     // errno in those environments even though it could set errno based on the
15111     // C standard.
15112     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15113     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15114         !FD->hasAttr<ConstAttr>()) {
15115       switch (BuiltinID) {
15116       case Builtin::BI__builtin_fma:
15117       case Builtin::BI__builtin_fmaf:
15118       case Builtin::BI__builtin_fmal:
15119       case Builtin::BIfma:
15120       case Builtin::BIfmaf:
15121       case Builtin::BIfmal:
15122         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15123         break;
15124       default:
15125         break;
15126       }
15127     }
15128 
15129     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15130         !FD->hasAttr<ReturnsTwiceAttr>())
15131       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15132                                          FD->getLocation()));
15133     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15134       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15135     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15136       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15137     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15138       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15139     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15140         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15141       // Add the appropriate attribute, depending on the CUDA compilation mode
15142       // and which target the builtin belongs to. For example, during host
15143       // compilation, aux builtins are __device__, while the rest are __host__.
15144       if (getLangOpts().CUDAIsDevice !=
15145           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15146         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15147       else
15148         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15149     }
15150 
15151     // Add known guaranteed alignment for allocation functions.
15152     switch (BuiltinID) {
15153     case Builtin::BIaligned_alloc:
15154       if (!FD->hasAttr<AllocAlignAttr>())
15155         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15156                                                    FD->getLocation()));
15157       LLVM_FALLTHROUGH;
15158     case Builtin::BIcalloc:
15159     case Builtin::BImalloc:
15160     case Builtin::BImemalign:
15161     case Builtin::BIrealloc:
15162     case Builtin::BIstrdup:
15163     case Builtin::BIstrndup: {
15164       if (!FD->hasAttr<AssumeAlignedAttr>()) {
15165         unsigned NewAlign = Context.getTargetInfo().getNewAlign() /
15166                             Context.getTargetInfo().getCharWidth();
15167         IntegerLiteral *Alignment = IntegerLiteral::Create(
15168             Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy),
15169             Context.UnsignedIntTy, FD->getLocation());
15170         FD->addAttr(AssumeAlignedAttr::CreateImplicit(
15171             Context, Alignment, /*Offset=*/nullptr, FD->getLocation()));
15172       }
15173       break;
15174     }
15175     default:
15176       break;
15177     }
15178   }
15179 
15180   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15181 
15182   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15183   // throw, add an implicit nothrow attribute to any extern "C" function we come
15184   // across.
15185   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15186       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15187     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15188     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15189       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15190   }
15191 
15192   IdentifierInfo *Name = FD->getIdentifier();
15193   if (!Name)
15194     return;
15195   if ((!getLangOpts().CPlusPlus &&
15196        FD->getDeclContext()->isTranslationUnit()) ||
15197       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15198        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15199        LinkageSpecDecl::lang_c)) {
15200     // Okay: this could be a libc/libm/Objective-C function we know
15201     // about.
15202   } else
15203     return;
15204 
15205   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15206     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15207     // target-specific builtins, perhaps?
15208     if (!FD->hasAttr<FormatAttr>())
15209       FD->addAttr(FormatAttr::CreateImplicit(Context,
15210                                              &Context.Idents.get("printf"), 2,
15211                                              Name->isStr("vasprintf") ? 0 : 3,
15212                                              FD->getLocation()));
15213   }
15214 
15215   if (Name->isStr("__CFStringMakeConstantString")) {
15216     // We already have a __builtin___CFStringMakeConstantString,
15217     // but builds that use -fno-constant-cfstrings don't go through that.
15218     if (!FD->hasAttr<FormatArgAttr>())
15219       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15220                                                 FD->getLocation()));
15221   }
15222 }
15223 
15224 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15225                                     TypeSourceInfo *TInfo) {
15226   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15227   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15228 
15229   if (!TInfo) {
15230     assert(D.isInvalidType() && "no declarator info for valid type");
15231     TInfo = Context.getTrivialTypeSourceInfo(T);
15232   }
15233 
15234   // Scope manipulation handled by caller.
15235   TypedefDecl *NewTD =
15236       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15237                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15238 
15239   // Bail out immediately if we have an invalid declaration.
15240   if (D.isInvalidType()) {
15241     NewTD->setInvalidDecl();
15242     return NewTD;
15243   }
15244 
15245   if (D.getDeclSpec().isModulePrivateSpecified()) {
15246     if (CurContext->isFunctionOrMethod())
15247       Diag(NewTD->getLocation(), diag::err_module_private_local)
15248           << 2 << NewTD
15249           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15250           << FixItHint::CreateRemoval(
15251                  D.getDeclSpec().getModulePrivateSpecLoc());
15252     else
15253       NewTD->setModulePrivate();
15254   }
15255 
15256   // C++ [dcl.typedef]p8:
15257   //   If the typedef declaration defines an unnamed class (or
15258   //   enum), the first typedef-name declared by the declaration
15259   //   to be that class type (or enum type) is used to denote the
15260   //   class type (or enum type) for linkage purposes only.
15261   // We need to check whether the type was declared in the declaration.
15262   switch (D.getDeclSpec().getTypeSpecType()) {
15263   case TST_enum:
15264   case TST_struct:
15265   case TST_interface:
15266   case TST_union:
15267   case TST_class: {
15268     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15269     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15270     break;
15271   }
15272 
15273   default:
15274     break;
15275   }
15276 
15277   return NewTD;
15278 }
15279 
15280 /// Check that this is a valid underlying type for an enum declaration.
15281 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15282   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15283   QualType T = TI->getType();
15284 
15285   if (T->isDependentType())
15286     return false;
15287 
15288   // This doesn't use 'isIntegralType' despite the error message mentioning
15289   // integral type because isIntegralType would also allow enum types in C.
15290   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15291     if (BT->isInteger())
15292       return false;
15293 
15294   if (T->isExtIntType())
15295     return false;
15296 
15297   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15298 }
15299 
15300 /// Check whether this is a valid redeclaration of a previous enumeration.
15301 /// \return true if the redeclaration was invalid.
15302 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15303                                   QualType EnumUnderlyingTy, bool IsFixed,
15304                                   const EnumDecl *Prev) {
15305   if (IsScoped != Prev->isScoped()) {
15306     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15307       << Prev->isScoped();
15308     Diag(Prev->getLocation(), diag::note_previous_declaration);
15309     return true;
15310   }
15311 
15312   if (IsFixed && Prev->isFixed()) {
15313     if (!EnumUnderlyingTy->isDependentType() &&
15314         !Prev->getIntegerType()->isDependentType() &&
15315         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15316                                         Prev->getIntegerType())) {
15317       // TODO: Highlight the underlying type of the redeclaration.
15318       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15319         << EnumUnderlyingTy << Prev->getIntegerType();
15320       Diag(Prev->getLocation(), diag::note_previous_declaration)
15321           << Prev->getIntegerTypeRange();
15322       return true;
15323     }
15324   } else if (IsFixed != Prev->isFixed()) {
15325     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15326       << Prev->isFixed();
15327     Diag(Prev->getLocation(), diag::note_previous_declaration);
15328     return true;
15329   }
15330 
15331   return false;
15332 }
15333 
15334 /// Get diagnostic %select index for tag kind for
15335 /// redeclaration diagnostic message.
15336 /// WARNING: Indexes apply to particular diagnostics only!
15337 ///
15338 /// \returns diagnostic %select index.
15339 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15340   switch (Tag) {
15341   case TTK_Struct: return 0;
15342   case TTK_Interface: return 1;
15343   case TTK_Class:  return 2;
15344   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15345   }
15346 }
15347 
15348 /// Determine if tag kind is a class-key compatible with
15349 /// class for redeclaration (class, struct, or __interface).
15350 ///
15351 /// \returns true iff the tag kind is compatible.
15352 static bool isClassCompatTagKind(TagTypeKind Tag)
15353 {
15354   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15355 }
15356 
15357 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15358                                              TagTypeKind TTK) {
15359   if (isa<TypedefDecl>(PrevDecl))
15360     return NTK_Typedef;
15361   else if (isa<TypeAliasDecl>(PrevDecl))
15362     return NTK_TypeAlias;
15363   else if (isa<ClassTemplateDecl>(PrevDecl))
15364     return NTK_Template;
15365   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15366     return NTK_TypeAliasTemplate;
15367   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15368     return NTK_TemplateTemplateArgument;
15369   switch (TTK) {
15370   case TTK_Struct:
15371   case TTK_Interface:
15372   case TTK_Class:
15373     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15374   case TTK_Union:
15375     return NTK_NonUnion;
15376   case TTK_Enum:
15377     return NTK_NonEnum;
15378   }
15379   llvm_unreachable("invalid TTK");
15380 }
15381 
15382 /// Determine whether a tag with a given kind is acceptable
15383 /// as a redeclaration of the given tag declaration.
15384 ///
15385 /// \returns true if the new tag kind is acceptable, false otherwise.
15386 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15387                                         TagTypeKind NewTag, bool isDefinition,
15388                                         SourceLocation NewTagLoc,
15389                                         const IdentifierInfo *Name) {
15390   // C++ [dcl.type.elab]p3:
15391   //   The class-key or enum keyword present in the
15392   //   elaborated-type-specifier shall agree in kind with the
15393   //   declaration to which the name in the elaborated-type-specifier
15394   //   refers. This rule also applies to the form of
15395   //   elaborated-type-specifier that declares a class-name or
15396   //   friend class since it can be construed as referring to the
15397   //   definition of the class. Thus, in any
15398   //   elaborated-type-specifier, the enum keyword shall be used to
15399   //   refer to an enumeration (7.2), the union class-key shall be
15400   //   used to refer to a union (clause 9), and either the class or
15401   //   struct class-key shall be used to refer to a class (clause 9)
15402   //   declared using the class or struct class-key.
15403   TagTypeKind OldTag = Previous->getTagKind();
15404   if (OldTag != NewTag &&
15405       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15406     return false;
15407 
15408   // Tags are compatible, but we might still want to warn on mismatched tags.
15409   // Non-class tags can't be mismatched at this point.
15410   if (!isClassCompatTagKind(NewTag))
15411     return true;
15412 
15413   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15414   // by our warning analysis. We don't want to warn about mismatches with (eg)
15415   // declarations in system headers that are designed to be specialized, but if
15416   // a user asks us to warn, we should warn if their code contains mismatched
15417   // declarations.
15418   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15419     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15420                                       Loc);
15421   };
15422   if (IsIgnoredLoc(NewTagLoc))
15423     return true;
15424 
15425   auto IsIgnored = [&](const TagDecl *Tag) {
15426     return IsIgnoredLoc(Tag->getLocation());
15427   };
15428   while (IsIgnored(Previous)) {
15429     Previous = Previous->getPreviousDecl();
15430     if (!Previous)
15431       return true;
15432     OldTag = Previous->getTagKind();
15433   }
15434 
15435   bool isTemplate = false;
15436   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15437     isTemplate = Record->getDescribedClassTemplate();
15438 
15439   if (inTemplateInstantiation()) {
15440     if (OldTag != NewTag) {
15441       // In a template instantiation, do not offer fix-its for tag mismatches
15442       // since they usually mess up the template instead of fixing the problem.
15443       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15444         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15445         << getRedeclDiagFromTagKind(OldTag);
15446       // FIXME: Note previous location?
15447     }
15448     return true;
15449   }
15450 
15451   if (isDefinition) {
15452     // On definitions, check all previous tags and issue a fix-it for each
15453     // one that doesn't match the current tag.
15454     if (Previous->getDefinition()) {
15455       // Don't suggest fix-its for redefinitions.
15456       return true;
15457     }
15458 
15459     bool previousMismatch = false;
15460     for (const TagDecl *I : Previous->redecls()) {
15461       if (I->getTagKind() != NewTag) {
15462         // Ignore previous declarations for which the warning was disabled.
15463         if (IsIgnored(I))
15464           continue;
15465 
15466         if (!previousMismatch) {
15467           previousMismatch = true;
15468           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15469             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15470             << getRedeclDiagFromTagKind(I->getTagKind());
15471         }
15472         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15473           << getRedeclDiagFromTagKind(NewTag)
15474           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15475                TypeWithKeyword::getTagTypeKindName(NewTag));
15476       }
15477     }
15478     return true;
15479   }
15480 
15481   // Identify the prevailing tag kind: this is the kind of the definition (if
15482   // there is a non-ignored definition), or otherwise the kind of the prior
15483   // (non-ignored) declaration.
15484   const TagDecl *PrevDef = Previous->getDefinition();
15485   if (PrevDef && IsIgnored(PrevDef))
15486     PrevDef = nullptr;
15487   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15488   if (Redecl->getTagKind() != NewTag) {
15489     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15490       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15491       << getRedeclDiagFromTagKind(OldTag);
15492     Diag(Redecl->getLocation(), diag::note_previous_use);
15493 
15494     // If there is a previous definition, suggest a fix-it.
15495     if (PrevDef) {
15496       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15497         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15498         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15499              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15500     }
15501   }
15502 
15503   return true;
15504 }
15505 
15506 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15507 /// from an outer enclosing namespace or file scope inside a friend declaration.
15508 /// This should provide the commented out code in the following snippet:
15509 ///   namespace N {
15510 ///     struct X;
15511 ///     namespace M {
15512 ///       struct Y { friend struct /*N::*/ X; };
15513 ///     }
15514 ///   }
15515 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15516                                          SourceLocation NameLoc) {
15517   // While the decl is in a namespace, do repeated lookup of that name and see
15518   // if we get the same namespace back.  If we do not, continue until
15519   // translation unit scope, at which point we have a fully qualified NNS.
15520   SmallVector<IdentifierInfo *, 4> Namespaces;
15521   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15522   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15523     // This tag should be declared in a namespace, which can only be enclosed by
15524     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15525     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15526     if (!Namespace || Namespace->isAnonymousNamespace())
15527       return FixItHint();
15528     IdentifierInfo *II = Namespace->getIdentifier();
15529     Namespaces.push_back(II);
15530     NamedDecl *Lookup = SemaRef.LookupSingleName(
15531         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15532     if (Lookup == Namespace)
15533       break;
15534   }
15535 
15536   // Once we have all the namespaces, reverse them to go outermost first, and
15537   // build an NNS.
15538   SmallString<64> Insertion;
15539   llvm::raw_svector_ostream OS(Insertion);
15540   if (DC->isTranslationUnit())
15541     OS << "::";
15542   std::reverse(Namespaces.begin(), Namespaces.end());
15543   for (auto *II : Namespaces)
15544     OS << II->getName() << "::";
15545   return FixItHint::CreateInsertion(NameLoc, Insertion);
15546 }
15547 
15548 /// Determine whether a tag originally declared in context \p OldDC can
15549 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15550 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15551 /// using-declaration).
15552 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15553                                          DeclContext *NewDC) {
15554   OldDC = OldDC->getRedeclContext();
15555   NewDC = NewDC->getRedeclContext();
15556 
15557   if (OldDC->Equals(NewDC))
15558     return true;
15559 
15560   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15561   // encloses the other).
15562   if (S.getLangOpts().MSVCCompat &&
15563       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15564     return true;
15565 
15566   return false;
15567 }
15568 
15569 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15570 /// former case, Name will be non-null.  In the later case, Name will be null.
15571 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15572 /// reference/declaration/definition of a tag.
15573 ///
15574 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15575 /// trailing-type-specifier) other than one in an alias-declaration.
15576 ///
15577 /// \param SkipBody If non-null, will be set to indicate if the caller should
15578 /// skip the definition of this tag and treat it as if it were a declaration.
15579 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15580                      SourceLocation KWLoc, CXXScopeSpec &SS,
15581                      IdentifierInfo *Name, SourceLocation NameLoc,
15582                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15583                      SourceLocation ModulePrivateLoc,
15584                      MultiTemplateParamsArg TemplateParameterLists,
15585                      bool &OwnedDecl, bool &IsDependent,
15586                      SourceLocation ScopedEnumKWLoc,
15587                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15588                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15589                      SkipBodyInfo *SkipBody) {
15590   // If this is not a definition, it must have a name.
15591   IdentifierInfo *OrigName = Name;
15592   assert((Name != nullptr || TUK == TUK_Definition) &&
15593          "Nameless record must be a definition!");
15594   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15595 
15596   OwnedDecl = false;
15597   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15598   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15599 
15600   // FIXME: Check member specializations more carefully.
15601   bool isMemberSpecialization = false;
15602   bool Invalid = false;
15603 
15604   // We only need to do this matching if we have template parameters
15605   // or a scope specifier, which also conveniently avoids this work
15606   // for non-C++ cases.
15607   if (TemplateParameterLists.size() > 0 ||
15608       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15609     if (TemplateParameterList *TemplateParams =
15610             MatchTemplateParametersToScopeSpecifier(
15611                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15612                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15613       if (Kind == TTK_Enum) {
15614         Diag(KWLoc, diag::err_enum_template);
15615         return nullptr;
15616       }
15617 
15618       if (TemplateParams->size() > 0) {
15619         // This is a declaration or definition of a class template (which may
15620         // be a member of another template).
15621 
15622         if (Invalid)
15623           return nullptr;
15624 
15625         OwnedDecl = false;
15626         DeclResult Result = CheckClassTemplate(
15627             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15628             AS, ModulePrivateLoc,
15629             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15630             TemplateParameterLists.data(), SkipBody);
15631         return Result.get();
15632       } else {
15633         // The "template<>" header is extraneous.
15634         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15635           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15636         isMemberSpecialization = true;
15637       }
15638     }
15639 
15640     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15641         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15642       return nullptr;
15643   }
15644 
15645   // Figure out the underlying type if this a enum declaration. We need to do
15646   // this early, because it's needed to detect if this is an incompatible
15647   // redeclaration.
15648   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15649   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15650 
15651   if (Kind == TTK_Enum) {
15652     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15653       // No underlying type explicitly specified, or we failed to parse the
15654       // type, default to int.
15655       EnumUnderlying = Context.IntTy.getTypePtr();
15656     } else if (UnderlyingType.get()) {
15657       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15658       // integral type; any cv-qualification is ignored.
15659       TypeSourceInfo *TI = nullptr;
15660       GetTypeFromParser(UnderlyingType.get(), &TI);
15661       EnumUnderlying = TI;
15662 
15663       if (CheckEnumUnderlyingType(TI))
15664         // Recover by falling back to int.
15665         EnumUnderlying = Context.IntTy.getTypePtr();
15666 
15667       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15668                                           UPPC_FixedUnderlyingType))
15669         EnumUnderlying = Context.IntTy.getTypePtr();
15670 
15671     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15672       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15673       // of 'int'. However, if this is an unfixed forward declaration, don't set
15674       // the underlying type unless the user enables -fms-compatibility. This
15675       // makes unfixed forward declared enums incomplete and is more conforming.
15676       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15677         EnumUnderlying = Context.IntTy.getTypePtr();
15678     }
15679   }
15680 
15681   DeclContext *SearchDC = CurContext;
15682   DeclContext *DC = CurContext;
15683   bool isStdBadAlloc = false;
15684   bool isStdAlignValT = false;
15685 
15686   RedeclarationKind Redecl = forRedeclarationInCurContext();
15687   if (TUK == TUK_Friend || TUK == TUK_Reference)
15688     Redecl = NotForRedeclaration;
15689 
15690   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15691   /// implemented asks for structural equivalence checking, the returned decl
15692   /// here is passed back to the parser, allowing the tag body to be parsed.
15693   auto createTagFromNewDecl = [&]() -> TagDecl * {
15694     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15695     // If there is an identifier, use the location of the identifier as the
15696     // location of the decl, otherwise use the location of the struct/union
15697     // keyword.
15698     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15699     TagDecl *New = nullptr;
15700 
15701     if (Kind == TTK_Enum) {
15702       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15703                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15704       // If this is an undefined enum, bail.
15705       if (TUK != TUK_Definition && !Invalid)
15706         return nullptr;
15707       if (EnumUnderlying) {
15708         EnumDecl *ED = cast<EnumDecl>(New);
15709         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15710           ED->setIntegerTypeSourceInfo(TI);
15711         else
15712           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15713         ED->setPromotionType(ED->getIntegerType());
15714       }
15715     } else { // struct/union
15716       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15717                                nullptr);
15718     }
15719 
15720     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15721       // Add alignment attributes if necessary; these attributes are checked
15722       // when the ASTContext lays out the structure.
15723       //
15724       // It is important for implementing the correct semantics that this
15725       // happen here (in ActOnTag). The #pragma pack stack is
15726       // maintained as a result of parser callbacks which can occur at
15727       // many points during the parsing of a struct declaration (because
15728       // the #pragma tokens are effectively skipped over during the
15729       // parsing of the struct).
15730       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15731         AddAlignmentAttributesForRecord(RD);
15732         AddMsStructLayoutForRecord(RD);
15733       }
15734     }
15735     New->setLexicalDeclContext(CurContext);
15736     return New;
15737   };
15738 
15739   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15740   if (Name && SS.isNotEmpty()) {
15741     // We have a nested-name tag ('struct foo::bar').
15742 
15743     // Check for invalid 'foo::'.
15744     if (SS.isInvalid()) {
15745       Name = nullptr;
15746       goto CreateNewDecl;
15747     }
15748 
15749     // If this is a friend or a reference to a class in a dependent
15750     // context, don't try to make a decl for it.
15751     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15752       DC = computeDeclContext(SS, false);
15753       if (!DC) {
15754         IsDependent = true;
15755         return nullptr;
15756       }
15757     } else {
15758       DC = computeDeclContext(SS, true);
15759       if (!DC) {
15760         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15761           << SS.getRange();
15762         return nullptr;
15763       }
15764     }
15765 
15766     if (RequireCompleteDeclContext(SS, DC))
15767       return nullptr;
15768 
15769     SearchDC = DC;
15770     // Look-up name inside 'foo::'.
15771     LookupQualifiedName(Previous, DC);
15772 
15773     if (Previous.isAmbiguous())
15774       return nullptr;
15775 
15776     if (Previous.empty()) {
15777       // Name lookup did not find anything. However, if the
15778       // nested-name-specifier refers to the current instantiation,
15779       // and that current instantiation has any dependent base
15780       // classes, we might find something at instantiation time: treat
15781       // this as a dependent elaborated-type-specifier.
15782       // But this only makes any sense for reference-like lookups.
15783       if (Previous.wasNotFoundInCurrentInstantiation() &&
15784           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15785         IsDependent = true;
15786         return nullptr;
15787       }
15788 
15789       // A tag 'foo::bar' must already exist.
15790       Diag(NameLoc, diag::err_not_tag_in_scope)
15791         << Kind << Name << DC << SS.getRange();
15792       Name = nullptr;
15793       Invalid = true;
15794       goto CreateNewDecl;
15795     }
15796   } else if (Name) {
15797     // C++14 [class.mem]p14:
15798     //   If T is the name of a class, then each of the following shall have a
15799     //   name different from T:
15800     //    -- every member of class T that is itself a type
15801     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15802         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15803       return nullptr;
15804 
15805     // If this is a named struct, check to see if there was a previous forward
15806     // declaration or definition.
15807     // FIXME: We're looking into outer scopes here, even when we
15808     // shouldn't be. Doing so can result in ambiguities that we
15809     // shouldn't be diagnosing.
15810     LookupName(Previous, S);
15811 
15812     // When declaring or defining a tag, ignore ambiguities introduced
15813     // by types using'ed into this scope.
15814     if (Previous.isAmbiguous() &&
15815         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15816       LookupResult::Filter F = Previous.makeFilter();
15817       while (F.hasNext()) {
15818         NamedDecl *ND = F.next();
15819         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15820                 SearchDC->getRedeclContext()))
15821           F.erase();
15822       }
15823       F.done();
15824     }
15825 
15826     // C++11 [namespace.memdef]p3:
15827     //   If the name in a friend declaration is neither qualified nor
15828     //   a template-id and the declaration is a function or an
15829     //   elaborated-type-specifier, the lookup to determine whether
15830     //   the entity has been previously declared shall not consider
15831     //   any scopes outside the innermost enclosing namespace.
15832     //
15833     // MSVC doesn't implement the above rule for types, so a friend tag
15834     // declaration may be a redeclaration of a type declared in an enclosing
15835     // scope.  They do implement this rule for friend functions.
15836     //
15837     // Does it matter that this should be by scope instead of by
15838     // semantic context?
15839     if (!Previous.empty() && TUK == TUK_Friend) {
15840       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15841       LookupResult::Filter F = Previous.makeFilter();
15842       bool FriendSawTagOutsideEnclosingNamespace = false;
15843       while (F.hasNext()) {
15844         NamedDecl *ND = F.next();
15845         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15846         if (DC->isFileContext() &&
15847             !EnclosingNS->Encloses(ND->getDeclContext())) {
15848           if (getLangOpts().MSVCCompat)
15849             FriendSawTagOutsideEnclosingNamespace = true;
15850           else
15851             F.erase();
15852         }
15853       }
15854       F.done();
15855 
15856       // Diagnose this MSVC extension in the easy case where lookup would have
15857       // unambiguously found something outside the enclosing namespace.
15858       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15859         NamedDecl *ND = Previous.getFoundDecl();
15860         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15861             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15862       }
15863     }
15864 
15865     // Note:  there used to be some attempt at recovery here.
15866     if (Previous.isAmbiguous())
15867       return nullptr;
15868 
15869     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15870       // FIXME: This makes sure that we ignore the contexts associated
15871       // with C structs, unions, and enums when looking for a matching
15872       // tag declaration or definition. See the similar lookup tweak
15873       // in Sema::LookupName; is there a better way to deal with this?
15874       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15875         SearchDC = SearchDC->getParent();
15876     }
15877   }
15878 
15879   if (Previous.isSingleResult() &&
15880       Previous.getFoundDecl()->isTemplateParameter()) {
15881     // Maybe we will complain about the shadowed template parameter.
15882     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15883     // Just pretend that we didn't see the previous declaration.
15884     Previous.clear();
15885   }
15886 
15887   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15888       DC->Equals(getStdNamespace())) {
15889     if (Name->isStr("bad_alloc")) {
15890       // This is a declaration of or a reference to "std::bad_alloc".
15891       isStdBadAlloc = true;
15892 
15893       // If std::bad_alloc has been implicitly declared (but made invisible to
15894       // name lookup), fill in this implicit declaration as the previous
15895       // declaration, so that the declarations get chained appropriately.
15896       if (Previous.empty() && StdBadAlloc)
15897         Previous.addDecl(getStdBadAlloc());
15898     } else if (Name->isStr("align_val_t")) {
15899       isStdAlignValT = true;
15900       if (Previous.empty() && StdAlignValT)
15901         Previous.addDecl(getStdAlignValT());
15902     }
15903   }
15904 
15905   // If we didn't find a previous declaration, and this is a reference
15906   // (or friend reference), move to the correct scope.  In C++, we
15907   // also need to do a redeclaration lookup there, just in case
15908   // there's a shadow friend decl.
15909   if (Name && Previous.empty() &&
15910       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15911     if (Invalid) goto CreateNewDecl;
15912     assert(SS.isEmpty());
15913 
15914     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15915       // C++ [basic.scope.pdecl]p5:
15916       //   -- for an elaborated-type-specifier of the form
15917       //
15918       //          class-key identifier
15919       //
15920       //      if the elaborated-type-specifier is used in the
15921       //      decl-specifier-seq or parameter-declaration-clause of a
15922       //      function defined in namespace scope, the identifier is
15923       //      declared as a class-name in the namespace that contains
15924       //      the declaration; otherwise, except as a friend
15925       //      declaration, the identifier is declared in the smallest
15926       //      non-class, non-function-prototype scope that contains the
15927       //      declaration.
15928       //
15929       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15930       // C structs and unions.
15931       //
15932       // It is an error in C++ to declare (rather than define) an enum
15933       // type, including via an elaborated type specifier.  We'll
15934       // diagnose that later; for now, declare the enum in the same
15935       // scope as we would have picked for any other tag type.
15936       //
15937       // GNU C also supports this behavior as part of its incomplete
15938       // enum types extension, while GNU C++ does not.
15939       //
15940       // Find the context where we'll be declaring the tag.
15941       // FIXME: We would like to maintain the current DeclContext as the
15942       // lexical context,
15943       SearchDC = getTagInjectionContext(SearchDC);
15944 
15945       // Find the scope where we'll be declaring the tag.
15946       S = getTagInjectionScope(S, getLangOpts());
15947     } else {
15948       assert(TUK == TUK_Friend);
15949       // C++ [namespace.memdef]p3:
15950       //   If a friend declaration in a non-local class first declares a
15951       //   class or function, the friend class or function is a member of
15952       //   the innermost enclosing namespace.
15953       SearchDC = SearchDC->getEnclosingNamespaceContext();
15954     }
15955 
15956     // In C++, we need to do a redeclaration lookup to properly
15957     // diagnose some problems.
15958     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15959     // hidden declaration so that we don't get ambiguity errors when using a
15960     // type declared by an elaborated-type-specifier.  In C that is not correct
15961     // and we should instead merge compatible types found by lookup.
15962     if (getLangOpts().CPlusPlus) {
15963       // FIXME: This can perform qualified lookups into function contexts,
15964       // which are meaningless.
15965       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15966       LookupQualifiedName(Previous, SearchDC);
15967     } else {
15968       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15969       LookupName(Previous, S);
15970     }
15971   }
15972 
15973   // If we have a known previous declaration to use, then use it.
15974   if (Previous.empty() && SkipBody && SkipBody->Previous)
15975     Previous.addDecl(SkipBody->Previous);
15976 
15977   if (!Previous.empty()) {
15978     NamedDecl *PrevDecl = Previous.getFoundDecl();
15979     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15980 
15981     // It's okay to have a tag decl in the same scope as a typedef
15982     // which hides a tag decl in the same scope.  Finding this
15983     // insanity with a redeclaration lookup can only actually happen
15984     // in C++.
15985     //
15986     // This is also okay for elaborated-type-specifiers, which is
15987     // technically forbidden by the current standard but which is
15988     // okay according to the likely resolution of an open issue;
15989     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15990     if (getLangOpts().CPlusPlus) {
15991       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15992         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15993           TagDecl *Tag = TT->getDecl();
15994           if (Tag->getDeclName() == Name &&
15995               Tag->getDeclContext()->getRedeclContext()
15996                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15997             PrevDecl = Tag;
15998             Previous.clear();
15999             Previous.addDecl(Tag);
16000             Previous.resolveKind();
16001           }
16002         }
16003       }
16004     }
16005 
16006     // If this is a redeclaration of a using shadow declaration, it must
16007     // declare a tag in the same context. In MSVC mode, we allow a
16008     // redefinition if either context is within the other.
16009     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16010       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16011       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16012           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16013           !(OldTag && isAcceptableTagRedeclContext(
16014                           *this, OldTag->getDeclContext(), SearchDC))) {
16015         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16016         Diag(Shadow->getTargetDecl()->getLocation(),
16017              diag::note_using_decl_target);
16018         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16019             << 0;
16020         // Recover by ignoring the old declaration.
16021         Previous.clear();
16022         goto CreateNewDecl;
16023       }
16024     }
16025 
16026     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16027       // If this is a use of a previous tag, or if the tag is already declared
16028       // in the same scope (so that the definition/declaration completes or
16029       // rementions the tag), reuse the decl.
16030       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16031           isDeclInScope(DirectPrevDecl, SearchDC, S,
16032                         SS.isNotEmpty() || isMemberSpecialization)) {
16033         // Make sure that this wasn't declared as an enum and now used as a
16034         // struct or something similar.
16035         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16036                                           TUK == TUK_Definition, KWLoc,
16037                                           Name)) {
16038           bool SafeToContinue
16039             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16040                Kind != TTK_Enum);
16041           if (SafeToContinue)
16042             Diag(KWLoc, diag::err_use_with_wrong_tag)
16043               << Name
16044               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16045                                               PrevTagDecl->getKindName());
16046           else
16047             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16048           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16049 
16050           if (SafeToContinue)
16051             Kind = PrevTagDecl->getTagKind();
16052           else {
16053             // Recover by making this an anonymous redefinition.
16054             Name = nullptr;
16055             Previous.clear();
16056             Invalid = true;
16057           }
16058         }
16059 
16060         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16061           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16062           if (TUK == TUK_Reference || TUK == TUK_Friend)
16063             return PrevTagDecl;
16064 
16065           QualType EnumUnderlyingTy;
16066           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16067             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16068           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16069             EnumUnderlyingTy = QualType(T, 0);
16070 
16071           // All conflicts with previous declarations are recovered by
16072           // returning the previous declaration, unless this is a definition,
16073           // in which case we want the caller to bail out.
16074           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16075                                      ScopedEnum, EnumUnderlyingTy,
16076                                      IsFixed, PrevEnum))
16077             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16078         }
16079 
16080         // C++11 [class.mem]p1:
16081         //   A member shall not be declared twice in the member-specification,
16082         //   except that a nested class or member class template can be declared
16083         //   and then later defined.
16084         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16085             S->isDeclScope(PrevDecl)) {
16086           Diag(NameLoc, diag::ext_member_redeclared);
16087           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16088         }
16089 
16090         if (!Invalid) {
16091           // If this is a use, just return the declaration we found, unless
16092           // we have attributes.
16093           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16094             if (!Attrs.empty()) {
16095               // FIXME: Diagnose these attributes. For now, we create a new
16096               // declaration to hold them.
16097             } else if (TUK == TUK_Reference &&
16098                        (PrevTagDecl->getFriendObjectKind() ==
16099                             Decl::FOK_Undeclared ||
16100                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16101                        SS.isEmpty()) {
16102               // This declaration is a reference to an existing entity, but
16103               // has different visibility from that entity: it either makes
16104               // a friend visible or it makes a type visible in a new module.
16105               // In either case, create a new declaration. We only do this if
16106               // the declaration would have meant the same thing if no prior
16107               // declaration were found, that is, if it was found in the same
16108               // scope where we would have injected a declaration.
16109               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16110                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16111                 return PrevTagDecl;
16112               // This is in the injected scope, create a new declaration in
16113               // that scope.
16114               S = getTagInjectionScope(S, getLangOpts());
16115             } else {
16116               return PrevTagDecl;
16117             }
16118           }
16119 
16120           // Diagnose attempts to redefine a tag.
16121           if (TUK == TUK_Definition) {
16122             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16123               // If we're defining a specialization and the previous definition
16124               // is from an implicit instantiation, don't emit an error
16125               // here; we'll catch this in the general case below.
16126               bool IsExplicitSpecializationAfterInstantiation = false;
16127               if (isMemberSpecialization) {
16128                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16129                   IsExplicitSpecializationAfterInstantiation =
16130                     RD->getTemplateSpecializationKind() !=
16131                     TSK_ExplicitSpecialization;
16132                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16133                   IsExplicitSpecializationAfterInstantiation =
16134                     ED->getTemplateSpecializationKind() !=
16135                     TSK_ExplicitSpecialization;
16136               }
16137 
16138               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16139               // not keep more that one definition around (merge them). However,
16140               // ensure the decl passes the structural compatibility check in
16141               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16142               NamedDecl *Hidden = nullptr;
16143               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16144                 // There is a definition of this tag, but it is not visible. We
16145                 // explicitly make use of C++'s one definition rule here, and
16146                 // assume that this definition is identical to the hidden one
16147                 // we already have. Make the existing definition visible and
16148                 // use it in place of this one.
16149                 if (!getLangOpts().CPlusPlus) {
16150                   // Postpone making the old definition visible until after we
16151                   // complete parsing the new one and do the structural
16152                   // comparison.
16153                   SkipBody->CheckSameAsPrevious = true;
16154                   SkipBody->New = createTagFromNewDecl();
16155                   SkipBody->Previous = Def;
16156                   return Def;
16157                 } else {
16158                   SkipBody->ShouldSkip = true;
16159                   SkipBody->Previous = Def;
16160                   makeMergedDefinitionVisible(Hidden);
16161                   // Carry on and handle it like a normal definition. We'll
16162                   // skip starting the definitiion later.
16163                 }
16164               } else if (!IsExplicitSpecializationAfterInstantiation) {
16165                 // A redeclaration in function prototype scope in C isn't
16166                 // visible elsewhere, so merely issue a warning.
16167                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16168                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16169                 else
16170                   Diag(NameLoc, diag::err_redefinition) << Name;
16171                 notePreviousDefinition(Def,
16172                                        NameLoc.isValid() ? NameLoc : KWLoc);
16173                 // If this is a redefinition, recover by making this
16174                 // struct be anonymous, which will make any later
16175                 // references get the previous definition.
16176                 Name = nullptr;
16177                 Previous.clear();
16178                 Invalid = true;
16179               }
16180             } else {
16181               // If the type is currently being defined, complain
16182               // about a nested redefinition.
16183               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16184               if (TD->isBeingDefined()) {
16185                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16186                 Diag(PrevTagDecl->getLocation(),
16187                      diag::note_previous_definition);
16188                 Name = nullptr;
16189                 Previous.clear();
16190                 Invalid = true;
16191               }
16192             }
16193 
16194             // Okay, this is definition of a previously declared or referenced
16195             // tag. We're going to create a new Decl for it.
16196           }
16197 
16198           // Okay, we're going to make a redeclaration.  If this is some kind
16199           // of reference, make sure we build the redeclaration in the same DC
16200           // as the original, and ignore the current access specifier.
16201           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16202             SearchDC = PrevTagDecl->getDeclContext();
16203             AS = AS_none;
16204           }
16205         }
16206         // If we get here we have (another) forward declaration or we
16207         // have a definition.  Just create a new decl.
16208 
16209       } else {
16210         // If we get here, this is a definition of a new tag type in a nested
16211         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16212         // new decl/type.  We set PrevDecl to NULL so that the entities
16213         // have distinct types.
16214         Previous.clear();
16215       }
16216       // If we get here, we're going to create a new Decl. If PrevDecl
16217       // is non-NULL, it's a definition of the tag declared by
16218       // PrevDecl. If it's NULL, we have a new definition.
16219 
16220     // Otherwise, PrevDecl is not a tag, but was found with tag
16221     // lookup.  This is only actually possible in C++, where a few
16222     // things like templates still live in the tag namespace.
16223     } else {
16224       // Use a better diagnostic if an elaborated-type-specifier
16225       // found the wrong kind of type on the first
16226       // (non-redeclaration) lookup.
16227       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16228           !Previous.isForRedeclaration()) {
16229         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16230         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16231                                                        << Kind;
16232         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16233         Invalid = true;
16234 
16235       // Otherwise, only diagnose if the declaration is in scope.
16236       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16237                                 SS.isNotEmpty() || isMemberSpecialization)) {
16238         // do nothing
16239 
16240       // Diagnose implicit declarations introduced by elaborated types.
16241       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16242         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16243         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16244         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16245         Invalid = true;
16246 
16247       // Otherwise it's a declaration.  Call out a particularly common
16248       // case here.
16249       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16250         unsigned Kind = 0;
16251         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16252         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16253           << Name << Kind << TND->getUnderlyingType();
16254         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16255         Invalid = true;
16256 
16257       // Otherwise, diagnose.
16258       } else {
16259         // The tag name clashes with something else in the target scope,
16260         // issue an error and recover by making this tag be anonymous.
16261         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16262         notePreviousDefinition(PrevDecl, NameLoc);
16263         Name = nullptr;
16264         Invalid = true;
16265       }
16266 
16267       // The existing declaration isn't relevant to us; we're in a
16268       // new scope, so clear out the previous declaration.
16269       Previous.clear();
16270     }
16271   }
16272 
16273 CreateNewDecl:
16274 
16275   TagDecl *PrevDecl = nullptr;
16276   if (Previous.isSingleResult())
16277     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16278 
16279   // If there is an identifier, use the location of the identifier as the
16280   // location of the decl, otherwise use the location of the struct/union
16281   // keyword.
16282   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16283 
16284   // Otherwise, create a new declaration. If there is a previous
16285   // declaration of the same entity, the two will be linked via
16286   // PrevDecl.
16287   TagDecl *New;
16288 
16289   if (Kind == TTK_Enum) {
16290     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16291     // enum X { A, B, C } D;    D should chain to X.
16292     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16293                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16294                            ScopedEnumUsesClassTag, IsFixed);
16295 
16296     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16297       StdAlignValT = cast<EnumDecl>(New);
16298 
16299     // If this is an undefined enum, warn.
16300     if (TUK != TUK_Definition && !Invalid) {
16301       TagDecl *Def;
16302       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16303         // C++0x: 7.2p2: opaque-enum-declaration.
16304         // Conflicts are diagnosed above. Do nothing.
16305       }
16306       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16307         Diag(Loc, diag::ext_forward_ref_enum_def)
16308           << New;
16309         Diag(Def->getLocation(), diag::note_previous_definition);
16310       } else {
16311         unsigned DiagID = diag::ext_forward_ref_enum;
16312         if (getLangOpts().MSVCCompat)
16313           DiagID = diag::ext_ms_forward_ref_enum;
16314         else if (getLangOpts().CPlusPlus)
16315           DiagID = diag::err_forward_ref_enum;
16316         Diag(Loc, DiagID);
16317       }
16318     }
16319 
16320     if (EnumUnderlying) {
16321       EnumDecl *ED = cast<EnumDecl>(New);
16322       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16323         ED->setIntegerTypeSourceInfo(TI);
16324       else
16325         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16326       ED->setPromotionType(ED->getIntegerType());
16327       assert(ED->isComplete() && "enum with type should be complete");
16328     }
16329   } else {
16330     // struct/union/class
16331 
16332     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16333     // struct X { int A; } D;    D should chain to X.
16334     if (getLangOpts().CPlusPlus) {
16335       // FIXME: Look for a way to use RecordDecl for simple structs.
16336       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16337                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16338 
16339       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16340         StdBadAlloc = cast<CXXRecordDecl>(New);
16341     } else
16342       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16343                                cast_or_null<RecordDecl>(PrevDecl));
16344   }
16345 
16346   // C++11 [dcl.type]p3:
16347   //   A type-specifier-seq shall not define a class or enumeration [...].
16348   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16349       TUK == TUK_Definition) {
16350     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16351       << Context.getTagDeclType(New);
16352     Invalid = true;
16353   }
16354 
16355   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16356       DC->getDeclKind() == Decl::Enum) {
16357     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16358       << Context.getTagDeclType(New);
16359     Invalid = true;
16360   }
16361 
16362   // Maybe add qualifier info.
16363   if (SS.isNotEmpty()) {
16364     if (SS.isSet()) {
16365       // If this is either a declaration or a definition, check the
16366       // nested-name-specifier against the current context.
16367       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16368           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16369                                        isMemberSpecialization))
16370         Invalid = true;
16371 
16372       New->setQualifierInfo(SS.getWithLocInContext(Context));
16373       if (TemplateParameterLists.size() > 0) {
16374         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16375       }
16376     }
16377     else
16378       Invalid = true;
16379   }
16380 
16381   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16382     // Add alignment attributes if necessary; these attributes are checked when
16383     // the ASTContext lays out the structure.
16384     //
16385     // It is important for implementing the correct semantics that this
16386     // happen here (in ActOnTag). The #pragma pack stack is
16387     // maintained as a result of parser callbacks which can occur at
16388     // many points during the parsing of a struct declaration (because
16389     // the #pragma tokens are effectively skipped over during the
16390     // parsing of the struct).
16391     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16392       AddAlignmentAttributesForRecord(RD);
16393       AddMsStructLayoutForRecord(RD);
16394     }
16395   }
16396 
16397   if (ModulePrivateLoc.isValid()) {
16398     if (isMemberSpecialization)
16399       Diag(New->getLocation(), diag::err_module_private_specialization)
16400         << 2
16401         << FixItHint::CreateRemoval(ModulePrivateLoc);
16402     // __module_private__ does not apply to local classes. However, we only
16403     // diagnose this as an error when the declaration specifiers are
16404     // freestanding. Here, we just ignore the __module_private__.
16405     else if (!SearchDC->isFunctionOrMethod())
16406       New->setModulePrivate();
16407   }
16408 
16409   // If this is a specialization of a member class (of a class template),
16410   // check the specialization.
16411   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16412     Invalid = true;
16413 
16414   // If we're declaring or defining a tag in function prototype scope in C,
16415   // note that this type can only be used within the function and add it to
16416   // the list of decls to inject into the function definition scope.
16417   if ((Name || Kind == TTK_Enum) &&
16418       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16419     if (getLangOpts().CPlusPlus) {
16420       // C++ [dcl.fct]p6:
16421       //   Types shall not be defined in return or parameter types.
16422       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16423         Diag(Loc, diag::err_type_defined_in_param_type)
16424             << Name;
16425         Invalid = true;
16426       }
16427     } else if (!PrevDecl) {
16428       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16429     }
16430   }
16431 
16432   if (Invalid)
16433     New->setInvalidDecl();
16434 
16435   // Set the lexical context. If the tag has a C++ scope specifier, the
16436   // lexical context will be different from the semantic context.
16437   New->setLexicalDeclContext(CurContext);
16438 
16439   // Mark this as a friend decl if applicable.
16440   // In Microsoft mode, a friend declaration also acts as a forward
16441   // declaration so we always pass true to setObjectOfFriendDecl to make
16442   // the tag name visible.
16443   if (TUK == TUK_Friend)
16444     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16445 
16446   // Set the access specifier.
16447   if (!Invalid && SearchDC->isRecord())
16448     SetMemberAccessSpecifier(New, PrevDecl, AS);
16449 
16450   if (PrevDecl)
16451     CheckRedeclarationModuleOwnership(New, PrevDecl);
16452 
16453   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16454     New->startDefinition();
16455 
16456   ProcessDeclAttributeList(S, New, Attrs);
16457   AddPragmaAttributes(S, New);
16458 
16459   // If this has an identifier, add it to the scope stack.
16460   if (TUK == TUK_Friend) {
16461     // We might be replacing an existing declaration in the lookup tables;
16462     // if so, borrow its access specifier.
16463     if (PrevDecl)
16464       New->setAccess(PrevDecl->getAccess());
16465 
16466     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16467     DC->makeDeclVisibleInContext(New);
16468     if (Name) // can be null along some error paths
16469       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16470         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16471   } else if (Name) {
16472     S = getNonFieldDeclScope(S);
16473     PushOnScopeChains(New, S, true);
16474   } else {
16475     CurContext->addDecl(New);
16476   }
16477 
16478   // If this is the C FILE type, notify the AST context.
16479   if (IdentifierInfo *II = New->getIdentifier())
16480     if (!New->isInvalidDecl() &&
16481         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16482         II->isStr("FILE"))
16483       Context.setFILEDecl(New);
16484 
16485   if (PrevDecl)
16486     mergeDeclAttributes(New, PrevDecl);
16487 
16488   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16489     inferGslOwnerPointerAttribute(CXXRD);
16490 
16491   // If there's a #pragma GCC visibility in scope, set the visibility of this
16492   // record.
16493   AddPushedVisibilityAttribute(New);
16494 
16495   if (isMemberSpecialization && !New->isInvalidDecl())
16496     CompleteMemberSpecialization(New, Previous);
16497 
16498   OwnedDecl = true;
16499   // In C++, don't return an invalid declaration. We can't recover well from
16500   // the cases where we make the type anonymous.
16501   if (Invalid && getLangOpts().CPlusPlus) {
16502     if (New->isBeingDefined())
16503       if (auto RD = dyn_cast<RecordDecl>(New))
16504         RD->completeDefinition();
16505     return nullptr;
16506   } else if (SkipBody && SkipBody->ShouldSkip) {
16507     return SkipBody->Previous;
16508   } else {
16509     return New;
16510   }
16511 }
16512 
16513 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16514   AdjustDeclIfTemplate(TagD);
16515   TagDecl *Tag = cast<TagDecl>(TagD);
16516 
16517   // Enter the tag context.
16518   PushDeclContext(S, Tag);
16519 
16520   ActOnDocumentableDecl(TagD);
16521 
16522   // If there's a #pragma GCC visibility in scope, set the visibility of this
16523   // record.
16524   AddPushedVisibilityAttribute(Tag);
16525 }
16526 
16527 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16528                                     SkipBodyInfo &SkipBody) {
16529   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16530     return false;
16531 
16532   // Make the previous decl visible.
16533   makeMergedDefinitionVisible(SkipBody.Previous);
16534   return true;
16535 }
16536 
16537 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16538   assert(isa<ObjCContainerDecl>(IDecl) &&
16539          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16540   DeclContext *OCD = cast<DeclContext>(IDecl);
16541   assert(OCD->getLexicalParent() == CurContext &&
16542       "The next DeclContext should be lexically contained in the current one.");
16543   CurContext = OCD;
16544   return IDecl;
16545 }
16546 
16547 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16548                                            SourceLocation FinalLoc,
16549                                            bool IsFinalSpelledSealed,
16550                                            bool IsAbstract,
16551                                            SourceLocation LBraceLoc) {
16552   AdjustDeclIfTemplate(TagD);
16553   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16554 
16555   FieldCollector->StartClass();
16556 
16557   if (!Record->getIdentifier())
16558     return;
16559 
16560   if (IsAbstract)
16561     Record->markAbstract();
16562 
16563   if (FinalLoc.isValid()) {
16564     Record->addAttr(FinalAttr::Create(
16565         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16566         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16567   }
16568   // C++ [class]p2:
16569   //   [...] The class-name is also inserted into the scope of the
16570   //   class itself; this is known as the injected-class-name. For
16571   //   purposes of access checking, the injected-class-name is treated
16572   //   as if it were a public member name.
16573   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16574       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16575       Record->getLocation(), Record->getIdentifier(),
16576       /*PrevDecl=*/nullptr,
16577       /*DelayTypeCreation=*/true);
16578   Context.getTypeDeclType(InjectedClassName, Record);
16579   InjectedClassName->setImplicit();
16580   InjectedClassName->setAccess(AS_public);
16581   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16582       InjectedClassName->setDescribedClassTemplate(Template);
16583   PushOnScopeChains(InjectedClassName, S);
16584   assert(InjectedClassName->isInjectedClassName() &&
16585          "Broken injected-class-name");
16586 }
16587 
16588 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16589                                     SourceRange BraceRange) {
16590   AdjustDeclIfTemplate(TagD);
16591   TagDecl *Tag = cast<TagDecl>(TagD);
16592   Tag->setBraceRange(BraceRange);
16593 
16594   // Make sure we "complete" the definition even it is invalid.
16595   if (Tag->isBeingDefined()) {
16596     assert(Tag->isInvalidDecl() && "We should already have completed it");
16597     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16598       RD->completeDefinition();
16599   }
16600 
16601   if (isa<CXXRecordDecl>(Tag)) {
16602     FieldCollector->FinishClass();
16603   }
16604 
16605   // Exit this scope of this tag's definition.
16606   PopDeclContext();
16607 
16608   if (getCurLexicalContext()->isObjCContainer() &&
16609       Tag->getDeclContext()->isFileContext())
16610     Tag->setTopLevelDeclInObjCContainer();
16611 
16612   // Notify the consumer that we've defined a tag.
16613   if (!Tag->isInvalidDecl())
16614     Consumer.HandleTagDeclDefinition(Tag);
16615 
16616   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16617   // from XLs and instead matches the XL #pragma pack(1) behavior.
16618   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16619       AlignPackStack.hasValue()) {
16620     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16621     // Only diagnose #pragma align(packed).
16622     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16623       return;
16624     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16625     if (!RD)
16626       return;
16627     // Only warn if there is at least 1 bitfield member.
16628     if (llvm::any_of(RD->fields(),
16629                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16630       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16631   }
16632 }
16633 
16634 void Sema::ActOnObjCContainerFinishDefinition() {
16635   // Exit this scope of this interface definition.
16636   PopDeclContext();
16637 }
16638 
16639 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16640   assert(DC == CurContext && "Mismatch of container contexts");
16641   OriginalLexicalContext = DC;
16642   ActOnObjCContainerFinishDefinition();
16643 }
16644 
16645 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16646   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16647   OriginalLexicalContext = nullptr;
16648 }
16649 
16650 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16651   AdjustDeclIfTemplate(TagD);
16652   TagDecl *Tag = cast<TagDecl>(TagD);
16653   Tag->setInvalidDecl();
16654 
16655   // Make sure we "complete" the definition even it is invalid.
16656   if (Tag->isBeingDefined()) {
16657     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16658       RD->completeDefinition();
16659   }
16660 
16661   // We're undoing ActOnTagStartDefinition here, not
16662   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16663   // the FieldCollector.
16664 
16665   PopDeclContext();
16666 }
16667 
16668 // Note that FieldName may be null for anonymous bitfields.
16669 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16670                                 IdentifierInfo *FieldName,
16671                                 QualType FieldTy, bool IsMsStruct,
16672                                 Expr *BitWidth, bool *ZeroWidth) {
16673   assert(BitWidth);
16674   if (BitWidth->containsErrors())
16675     return ExprError();
16676 
16677   // Default to true; that shouldn't confuse checks for emptiness
16678   if (ZeroWidth)
16679     *ZeroWidth = true;
16680 
16681   // C99 6.7.2.1p4 - verify the field type.
16682   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16683   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16684     // Handle incomplete and sizeless types with a specific error.
16685     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16686                                  diag::err_field_incomplete_or_sizeless))
16687       return ExprError();
16688     if (FieldName)
16689       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16690         << FieldName << FieldTy << BitWidth->getSourceRange();
16691     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16692       << FieldTy << BitWidth->getSourceRange();
16693   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16694                                              UPPC_BitFieldWidth))
16695     return ExprError();
16696 
16697   // If the bit-width is type- or value-dependent, don't try to check
16698   // it now.
16699   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16700     return BitWidth;
16701 
16702   llvm::APSInt Value;
16703   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16704   if (ICE.isInvalid())
16705     return ICE;
16706   BitWidth = ICE.get();
16707 
16708   if (Value != 0 && ZeroWidth)
16709     *ZeroWidth = false;
16710 
16711   // Zero-width bitfield is ok for anonymous field.
16712   if (Value == 0 && FieldName)
16713     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16714 
16715   if (Value.isSigned() && Value.isNegative()) {
16716     if (FieldName)
16717       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16718                << FieldName << toString(Value, 10);
16719     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16720       << toString(Value, 10);
16721   }
16722 
16723   // The size of the bit-field must not exceed our maximum permitted object
16724   // size.
16725   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16726     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16727            << !FieldName << FieldName << toString(Value, 10);
16728   }
16729 
16730   if (!FieldTy->isDependentType()) {
16731     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16732     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16733     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16734 
16735     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16736     // ABI.
16737     bool CStdConstraintViolation =
16738         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16739     bool MSBitfieldViolation =
16740         Value.ugt(TypeStorageSize) &&
16741         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16742     if (CStdConstraintViolation || MSBitfieldViolation) {
16743       unsigned DiagWidth =
16744           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16745       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16746              << (bool)FieldName << FieldName << toString(Value, 10)
16747              << !CStdConstraintViolation << DiagWidth;
16748     }
16749 
16750     // Warn on types where the user might conceivably expect to get all
16751     // specified bits as value bits: that's all integral types other than
16752     // 'bool'.
16753     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16754       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16755           << FieldName << toString(Value, 10)
16756           << (unsigned)TypeWidth;
16757     }
16758   }
16759 
16760   return BitWidth;
16761 }
16762 
16763 /// ActOnField - Each field of a C struct/union is passed into this in order
16764 /// to create a FieldDecl object for it.
16765 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16766                        Declarator &D, Expr *BitfieldWidth) {
16767   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16768                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16769                                /*InitStyle=*/ICIS_NoInit, AS_public);
16770   return Res;
16771 }
16772 
16773 /// HandleField - Analyze a field of a C struct or a C++ data member.
16774 ///
16775 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16776                              SourceLocation DeclStart,
16777                              Declarator &D, Expr *BitWidth,
16778                              InClassInitStyle InitStyle,
16779                              AccessSpecifier AS) {
16780   if (D.isDecompositionDeclarator()) {
16781     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16782     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16783       << Decomp.getSourceRange();
16784     return nullptr;
16785   }
16786 
16787   IdentifierInfo *II = D.getIdentifier();
16788   SourceLocation Loc = DeclStart;
16789   if (II) Loc = D.getIdentifierLoc();
16790 
16791   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16792   QualType T = TInfo->getType();
16793   if (getLangOpts().CPlusPlus) {
16794     CheckExtraCXXDefaultArguments(D);
16795 
16796     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16797                                         UPPC_DataMemberType)) {
16798       D.setInvalidType();
16799       T = Context.IntTy;
16800       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16801     }
16802   }
16803 
16804   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16805 
16806   if (D.getDeclSpec().isInlineSpecified())
16807     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16808         << getLangOpts().CPlusPlus17;
16809   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16810     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16811          diag::err_invalid_thread)
16812       << DeclSpec::getSpecifierName(TSCS);
16813 
16814   // Check to see if this name was declared as a member previously
16815   NamedDecl *PrevDecl = nullptr;
16816   LookupResult Previous(*this, II, Loc, LookupMemberName,
16817                         ForVisibleRedeclaration);
16818   LookupName(Previous, S);
16819   switch (Previous.getResultKind()) {
16820     case LookupResult::Found:
16821     case LookupResult::FoundUnresolvedValue:
16822       PrevDecl = Previous.getAsSingle<NamedDecl>();
16823       break;
16824 
16825     case LookupResult::FoundOverloaded:
16826       PrevDecl = Previous.getRepresentativeDecl();
16827       break;
16828 
16829     case LookupResult::NotFound:
16830     case LookupResult::NotFoundInCurrentInstantiation:
16831     case LookupResult::Ambiguous:
16832       break;
16833   }
16834   Previous.suppressDiagnostics();
16835 
16836   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16837     // Maybe we will complain about the shadowed template parameter.
16838     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16839     // Just pretend that we didn't see the previous declaration.
16840     PrevDecl = nullptr;
16841   }
16842 
16843   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16844     PrevDecl = nullptr;
16845 
16846   bool Mutable
16847     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16848   SourceLocation TSSL = D.getBeginLoc();
16849   FieldDecl *NewFD
16850     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16851                      TSSL, AS, PrevDecl, &D);
16852 
16853   if (NewFD->isInvalidDecl())
16854     Record->setInvalidDecl();
16855 
16856   if (D.getDeclSpec().isModulePrivateSpecified())
16857     NewFD->setModulePrivate();
16858 
16859   if (NewFD->isInvalidDecl() && PrevDecl) {
16860     // Don't introduce NewFD into scope; there's already something
16861     // with the same name in the same scope.
16862   } else if (II) {
16863     PushOnScopeChains(NewFD, S);
16864   } else
16865     Record->addDecl(NewFD);
16866 
16867   return NewFD;
16868 }
16869 
16870 /// Build a new FieldDecl and check its well-formedness.
16871 ///
16872 /// This routine builds a new FieldDecl given the fields name, type,
16873 /// record, etc. \p PrevDecl should refer to any previous declaration
16874 /// with the same name and in the same scope as the field to be
16875 /// created.
16876 ///
16877 /// \returns a new FieldDecl.
16878 ///
16879 /// \todo The Declarator argument is a hack. It will be removed once
16880 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16881                                 TypeSourceInfo *TInfo,
16882                                 RecordDecl *Record, SourceLocation Loc,
16883                                 bool Mutable, Expr *BitWidth,
16884                                 InClassInitStyle InitStyle,
16885                                 SourceLocation TSSL,
16886                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16887                                 Declarator *D) {
16888   IdentifierInfo *II = Name.getAsIdentifierInfo();
16889   bool InvalidDecl = false;
16890   if (D) InvalidDecl = D->isInvalidType();
16891 
16892   // If we receive a broken type, recover by assuming 'int' and
16893   // marking this declaration as invalid.
16894   if (T.isNull() || T->containsErrors()) {
16895     InvalidDecl = true;
16896     T = Context.IntTy;
16897   }
16898 
16899   QualType EltTy = Context.getBaseElementType(T);
16900   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16901     if (RequireCompleteSizedType(Loc, EltTy,
16902                                  diag::err_field_incomplete_or_sizeless)) {
16903       // Fields of incomplete type force their record to be invalid.
16904       Record->setInvalidDecl();
16905       InvalidDecl = true;
16906     } else {
16907       NamedDecl *Def;
16908       EltTy->isIncompleteType(&Def);
16909       if (Def && Def->isInvalidDecl()) {
16910         Record->setInvalidDecl();
16911         InvalidDecl = true;
16912       }
16913     }
16914   }
16915 
16916   // TR 18037 does not allow fields to be declared with address space
16917   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16918       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16919     Diag(Loc, diag::err_field_with_address_space);
16920     Record->setInvalidDecl();
16921     InvalidDecl = true;
16922   }
16923 
16924   if (LangOpts.OpenCL) {
16925     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16926     // used as structure or union field: image, sampler, event or block types.
16927     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16928         T->isBlockPointerType()) {
16929       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16930       Record->setInvalidDecl();
16931       InvalidDecl = true;
16932     }
16933     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
16934     // is enabled.
16935     if (BitWidth && !getOpenCLOptions().isAvailableOption(
16936                         "__cl_clang_bitfields", LangOpts)) {
16937       Diag(Loc, diag::err_opencl_bitfields);
16938       InvalidDecl = true;
16939     }
16940   }
16941 
16942   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16943   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16944       T.hasQualifiers()) {
16945     InvalidDecl = true;
16946     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16947   }
16948 
16949   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16950   // than a variably modified type.
16951   if (!InvalidDecl && T->isVariablyModifiedType()) {
16952     if (!tryToFixVariablyModifiedVarType(
16953             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16954       InvalidDecl = true;
16955   }
16956 
16957   // Fields can not have abstract class types
16958   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16959                                              diag::err_abstract_type_in_decl,
16960                                              AbstractFieldType))
16961     InvalidDecl = true;
16962 
16963   bool ZeroWidth = false;
16964   if (InvalidDecl)
16965     BitWidth = nullptr;
16966   // If this is declared as a bit-field, check the bit-field.
16967   if (BitWidth) {
16968     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16969                               &ZeroWidth).get();
16970     if (!BitWidth) {
16971       InvalidDecl = true;
16972       BitWidth = nullptr;
16973       ZeroWidth = false;
16974     }
16975   }
16976 
16977   // Check that 'mutable' is consistent with the type of the declaration.
16978   if (!InvalidDecl && Mutable) {
16979     unsigned DiagID = 0;
16980     if (T->isReferenceType())
16981       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16982                                         : diag::err_mutable_reference;
16983     else if (T.isConstQualified())
16984       DiagID = diag::err_mutable_const;
16985 
16986     if (DiagID) {
16987       SourceLocation ErrLoc = Loc;
16988       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16989         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16990       Diag(ErrLoc, DiagID);
16991       if (DiagID != diag::ext_mutable_reference) {
16992         Mutable = false;
16993         InvalidDecl = true;
16994       }
16995     }
16996   }
16997 
16998   // C++11 [class.union]p8 (DR1460):
16999   //   At most one variant member of a union may have a
17000   //   brace-or-equal-initializer.
17001   if (InitStyle != ICIS_NoInit)
17002     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17003 
17004   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17005                                        BitWidth, Mutable, InitStyle);
17006   if (InvalidDecl)
17007     NewFD->setInvalidDecl();
17008 
17009   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17010     Diag(Loc, diag::err_duplicate_member) << II;
17011     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17012     NewFD->setInvalidDecl();
17013   }
17014 
17015   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17016     if (Record->isUnion()) {
17017       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17018         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17019         if (RDecl->getDefinition()) {
17020           // C++ [class.union]p1: An object of a class with a non-trivial
17021           // constructor, a non-trivial copy constructor, a non-trivial
17022           // destructor, or a non-trivial copy assignment operator
17023           // cannot be a member of a union, nor can an array of such
17024           // objects.
17025           if (CheckNontrivialField(NewFD))
17026             NewFD->setInvalidDecl();
17027         }
17028       }
17029 
17030       // C++ [class.union]p1: If a union contains a member of reference type,
17031       // the program is ill-formed, except when compiling with MSVC extensions
17032       // enabled.
17033       if (EltTy->isReferenceType()) {
17034         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17035                                     diag::ext_union_member_of_reference_type :
17036                                     diag::err_union_member_of_reference_type)
17037           << NewFD->getDeclName() << EltTy;
17038         if (!getLangOpts().MicrosoftExt)
17039           NewFD->setInvalidDecl();
17040       }
17041     }
17042   }
17043 
17044   // FIXME: We need to pass in the attributes given an AST
17045   // representation, not a parser representation.
17046   if (D) {
17047     // FIXME: The current scope is almost... but not entirely... correct here.
17048     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17049 
17050     if (NewFD->hasAttrs())
17051       CheckAlignasUnderalignment(NewFD);
17052   }
17053 
17054   // In auto-retain/release, infer strong retension for fields of
17055   // retainable type.
17056   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17057     NewFD->setInvalidDecl();
17058 
17059   if (T.isObjCGCWeak())
17060     Diag(Loc, diag::warn_attribute_weak_on_field);
17061 
17062   // PPC MMA non-pointer types are not allowed as field types.
17063   if (Context.getTargetInfo().getTriple().isPPC64() &&
17064       CheckPPCMMAType(T, NewFD->getLocation()))
17065     NewFD->setInvalidDecl();
17066 
17067   NewFD->setAccess(AS);
17068   return NewFD;
17069 }
17070 
17071 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17072   assert(FD);
17073   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17074 
17075   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17076     return false;
17077 
17078   QualType EltTy = Context.getBaseElementType(FD->getType());
17079   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17080     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17081     if (RDecl->getDefinition()) {
17082       // We check for copy constructors before constructors
17083       // because otherwise we'll never get complaints about
17084       // copy constructors.
17085 
17086       CXXSpecialMember member = CXXInvalid;
17087       // We're required to check for any non-trivial constructors. Since the
17088       // implicit default constructor is suppressed if there are any
17089       // user-declared constructors, we just need to check that there is a
17090       // trivial default constructor and a trivial copy constructor. (We don't
17091       // worry about move constructors here, since this is a C++98 check.)
17092       if (RDecl->hasNonTrivialCopyConstructor())
17093         member = CXXCopyConstructor;
17094       else if (!RDecl->hasTrivialDefaultConstructor())
17095         member = CXXDefaultConstructor;
17096       else if (RDecl->hasNonTrivialCopyAssignment())
17097         member = CXXCopyAssignment;
17098       else if (RDecl->hasNonTrivialDestructor())
17099         member = CXXDestructor;
17100 
17101       if (member != CXXInvalid) {
17102         if (!getLangOpts().CPlusPlus11 &&
17103             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17104           // Objective-C++ ARC: it is an error to have a non-trivial field of
17105           // a union. However, system headers in Objective-C programs
17106           // occasionally have Objective-C lifetime objects within unions,
17107           // and rather than cause the program to fail, we make those
17108           // members unavailable.
17109           SourceLocation Loc = FD->getLocation();
17110           if (getSourceManager().isInSystemHeader(Loc)) {
17111             if (!FD->hasAttr<UnavailableAttr>())
17112               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17113                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17114             return false;
17115           }
17116         }
17117 
17118         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17119                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17120                diag::err_illegal_union_or_anon_struct_member)
17121           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17122         DiagnoseNontrivial(RDecl, member);
17123         return !getLangOpts().CPlusPlus11;
17124       }
17125     }
17126   }
17127 
17128   return false;
17129 }
17130 
17131 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17132 ///  AST enum value.
17133 static ObjCIvarDecl::AccessControl
17134 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17135   switch (ivarVisibility) {
17136   default: llvm_unreachable("Unknown visitibility kind");
17137   case tok::objc_private: return ObjCIvarDecl::Private;
17138   case tok::objc_public: return ObjCIvarDecl::Public;
17139   case tok::objc_protected: return ObjCIvarDecl::Protected;
17140   case tok::objc_package: return ObjCIvarDecl::Package;
17141   }
17142 }
17143 
17144 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17145 /// in order to create an IvarDecl object for it.
17146 Decl *Sema::ActOnIvar(Scope *S,
17147                                 SourceLocation DeclStart,
17148                                 Declarator &D, Expr *BitfieldWidth,
17149                                 tok::ObjCKeywordKind Visibility) {
17150 
17151   IdentifierInfo *II = D.getIdentifier();
17152   Expr *BitWidth = (Expr*)BitfieldWidth;
17153   SourceLocation Loc = DeclStart;
17154   if (II) Loc = D.getIdentifierLoc();
17155 
17156   // FIXME: Unnamed fields can be handled in various different ways, for
17157   // example, unnamed unions inject all members into the struct namespace!
17158 
17159   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17160   QualType T = TInfo->getType();
17161 
17162   if (BitWidth) {
17163     // 6.7.2.1p3, 6.7.2.1p4
17164     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17165     if (!BitWidth)
17166       D.setInvalidType();
17167   } else {
17168     // Not a bitfield.
17169 
17170     // validate II.
17171 
17172   }
17173   if (T->isReferenceType()) {
17174     Diag(Loc, diag::err_ivar_reference_type);
17175     D.setInvalidType();
17176   }
17177   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17178   // than a variably modified type.
17179   else if (T->isVariablyModifiedType()) {
17180     if (!tryToFixVariablyModifiedVarType(
17181             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17182       D.setInvalidType();
17183   }
17184 
17185   // Get the visibility (access control) for this ivar.
17186   ObjCIvarDecl::AccessControl ac =
17187     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17188                                         : ObjCIvarDecl::None;
17189   // Must set ivar's DeclContext to its enclosing interface.
17190   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17191   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17192     return nullptr;
17193   ObjCContainerDecl *EnclosingContext;
17194   if (ObjCImplementationDecl *IMPDecl =
17195       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17196     if (LangOpts.ObjCRuntime.isFragile()) {
17197     // Case of ivar declared in an implementation. Context is that of its class.
17198       EnclosingContext = IMPDecl->getClassInterface();
17199       assert(EnclosingContext && "Implementation has no class interface!");
17200     }
17201     else
17202       EnclosingContext = EnclosingDecl;
17203   } else {
17204     if (ObjCCategoryDecl *CDecl =
17205         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17206       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17207         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17208         return nullptr;
17209       }
17210     }
17211     EnclosingContext = EnclosingDecl;
17212   }
17213 
17214   // Construct the decl.
17215   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17216                                              DeclStart, Loc, II, T,
17217                                              TInfo, ac, (Expr *)BitfieldWidth);
17218 
17219   if (II) {
17220     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17221                                            ForVisibleRedeclaration);
17222     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17223         && !isa<TagDecl>(PrevDecl)) {
17224       Diag(Loc, diag::err_duplicate_member) << II;
17225       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17226       NewID->setInvalidDecl();
17227     }
17228   }
17229 
17230   // Process attributes attached to the ivar.
17231   ProcessDeclAttributes(S, NewID, D);
17232 
17233   if (D.isInvalidType())
17234     NewID->setInvalidDecl();
17235 
17236   // In ARC, infer 'retaining' for ivars of retainable type.
17237   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17238     NewID->setInvalidDecl();
17239 
17240   if (D.getDeclSpec().isModulePrivateSpecified())
17241     NewID->setModulePrivate();
17242 
17243   if (II) {
17244     // FIXME: When interfaces are DeclContexts, we'll need to add
17245     // these to the interface.
17246     S->AddDecl(NewID);
17247     IdResolver.AddDecl(NewID);
17248   }
17249 
17250   if (LangOpts.ObjCRuntime.isNonFragile() &&
17251       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17252     Diag(Loc, diag::warn_ivars_in_interface);
17253 
17254   return NewID;
17255 }
17256 
17257 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17258 /// class and class extensions. For every class \@interface and class
17259 /// extension \@interface, if the last ivar is a bitfield of any type,
17260 /// then add an implicit `char :0` ivar to the end of that interface.
17261 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17262                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17263   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17264     return;
17265 
17266   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17267   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17268 
17269   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17270     return;
17271   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17272   if (!ID) {
17273     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17274       if (!CD->IsClassExtension())
17275         return;
17276     }
17277     // No need to add this to end of @implementation.
17278     else
17279       return;
17280   }
17281   // All conditions are met. Add a new bitfield to the tail end of ivars.
17282   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17283   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17284 
17285   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17286                               DeclLoc, DeclLoc, nullptr,
17287                               Context.CharTy,
17288                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17289                                                                DeclLoc),
17290                               ObjCIvarDecl::Private, BW,
17291                               true);
17292   AllIvarDecls.push_back(Ivar);
17293 }
17294 
17295 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17296                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17297                        SourceLocation RBrac,
17298                        const ParsedAttributesView &Attrs) {
17299   assert(EnclosingDecl && "missing record or interface decl");
17300 
17301   // If this is an Objective-C @implementation or category and we have
17302   // new fields here we should reset the layout of the interface since
17303   // it will now change.
17304   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17305     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17306     switch (DC->getKind()) {
17307     default: break;
17308     case Decl::ObjCCategory:
17309       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17310       break;
17311     case Decl::ObjCImplementation:
17312       Context.
17313         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17314       break;
17315     }
17316   }
17317 
17318   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17319   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17320 
17321   // Start counting up the number of named members; make sure to include
17322   // members of anonymous structs and unions in the total.
17323   unsigned NumNamedMembers = 0;
17324   if (Record) {
17325     for (const auto *I : Record->decls()) {
17326       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17327         if (IFD->getDeclName())
17328           ++NumNamedMembers;
17329     }
17330   }
17331 
17332   // Verify that all the fields are okay.
17333   SmallVector<FieldDecl*, 32> RecFields;
17334 
17335   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17336        i != end; ++i) {
17337     FieldDecl *FD = cast<FieldDecl>(*i);
17338 
17339     // Get the type for the field.
17340     const Type *FDTy = FD->getType().getTypePtr();
17341 
17342     if (!FD->isAnonymousStructOrUnion()) {
17343       // Remember all fields written by the user.
17344       RecFields.push_back(FD);
17345     }
17346 
17347     // If the field is already invalid for some reason, don't emit more
17348     // diagnostics about it.
17349     if (FD->isInvalidDecl()) {
17350       EnclosingDecl->setInvalidDecl();
17351       continue;
17352     }
17353 
17354     // C99 6.7.2.1p2:
17355     //   A structure or union shall not contain a member with
17356     //   incomplete or function type (hence, a structure shall not
17357     //   contain an instance of itself, but may contain a pointer to
17358     //   an instance of itself), except that the last member of a
17359     //   structure with more than one named member may have incomplete
17360     //   array type; such a structure (and any union containing,
17361     //   possibly recursively, a member that is such a structure)
17362     //   shall not be a member of a structure or an element of an
17363     //   array.
17364     bool IsLastField = (i + 1 == Fields.end());
17365     if (FDTy->isFunctionType()) {
17366       // Field declared as a function.
17367       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17368         << FD->getDeclName();
17369       FD->setInvalidDecl();
17370       EnclosingDecl->setInvalidDecl();
17371       continue;
17372     } else if (FDTy->isIncompleteArrayType() &&
17373                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17374       if (Record) {
17375         // Flexible array member.
17376         // Microsoft and g++ is more permissive regarding flexible array.
17377         // It will accept flexible array in union and also
17378         // as the sole element of a struct/class.
17379         unsigned DiagID = 0;
17380         if (!Record->isUnion() && !IsLastField) {
17381           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17382             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17383           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17384           FD->setInvalidDecl();
17385           EnclosingDecl->setInvalidDecl();
17386           continue;
17387         } else if (Record->isUnion())
17388           DiagID = getLangOpts().MicrosoftExt
17389                        ? diag::ext_flexible_array_union_ms
17390                        : getLangOpts().CPlusPlus
17391                              ? diag::ext_flexible_array_union_gnu
17392                              : diag::err_flexible_array_union;
17393         else if (NumNamedMembers < 1)
17394           DiagID = getLangOpts().MicrosoftExt
17395                        ? diag::ext_flexible_array_empty_aggregate_ms
17396                        : getLangOpts().CPlusPlus
17397                              ? diag::ext_flexible_array_empty_aggregate_gnu
17398                              : diag::err_flexible_array_empty_aggregate;
17399 
17400         if (DiagID)
17401           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17402                                           << Record->getTagKind();
17403         // While the layout of types that contain virtual bases is not specified
17404         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17405         // virtual bases after the derived members.  This would make a flexible
17406         // array member declared at the end of an object not adjacent to the end
17407         // of the type.
17408         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17409           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17410               << FD->getDeclName() << Record->getTagKind();
17411         if (!getLangOpts().C99)
17412           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17413             << FD->getDeclName() << Record->getTagKind();
17414 
17415         // If the element type has a non-trivial destructor, we would not
17416         // implicitly destroy the elements, so disallow it for now.
17417         //
17418         // FIXME: GCC allows this. We should probably either implicitly delete
17419         // the destructor of the containing class, or just allow this.
17420         QualType BaseElem = Context.getBaseElementType(FD->getType());
17421         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17422           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17423             << FD->getDeclName() << FD->getType();
17424           FD->setInvalidDecl();
17425           EnclosingDecl->setInvalidDecl();
17426           continue;
17427         }
17428         // Okay, we have a legal flexible array member at the end of the struct.
17429         Record->setHasFlexibleArrayMember(true);
17430       } else {
17431         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17432         // unless they are followed by another ivar. That check is done
17433         // elsewhere, after synthesized ivars are known.
17434       }
17435     } else if (!FDTy->isDependentType() &&
17436                RequireCompleteSizedType(
17437                    FD->getLocation(), FD->getType(),
17438                    diag::err_field_incomplete_or_sizeless)) {
17439       // Incomplete type
17440       FD->setInvalidDecl();
17441       EnclosingDecl->setInvalidDecl();
17442       continue;
17443     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17444       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17445         // A type which contains a flexible array member is considered to be a
17446         // flexible array member.
17447         Record->setHasFlexibleArrayMember(true);
17448         if (!Record->isUnion()) {
17449           // If this is a struct/class and this is not the last element, reject
17450           // it.  Note that GCC supports variable sized arrays in the middle of
17451           // structures.
17452           if (!IsLastField)
17453             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17454               << FD->getDeclName() << FD->getType();
17455           else {
17456             // We support flexible arrays at the end of structs in
17457             // other structs as an extension.
17458             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17459               << FD->getDeclName();
17460           }
17461         }
17462       }
17463       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17464           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17465                                  diag::err_abstract_type_in_decl,
17466                                  AbstractIvarType)) {
17467         // Ivars can not have abstract class types
17468         FD->setInvalidDecl();
17469       }
17470       if (Record && FDTTy->getDecl()->hasObjectMember())
17471         Record->setHasObjectMember(true);
17472       if (Record && FDTTy->getDecl()->hasVolatileMember())
17473         Record->setHasVolatileMember(true);
17474     } else if (FDTy->isObjCObjectType()) {
17475       /// A field cannot be an Objective-c object
17476       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17477         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17478       QualType T = Context.getObjCObjectPointerType(FD->getType());
17479       FD->setType(T);
17480     } else if (Record && Record->isUnion() &&
17481                FD->getType().hasNonTrivialObjCLifetime() &&
17482                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17483                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17484                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17485                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17486       // For backward compatibility, fields of C unions declared in system
17487       // headers that have non-trivial ObjC ownership qualifications are marked
17488       // as unavailable unless the qualifier is explicit and __strong. This can
17489       // break ABI compatibility between programs compiled with ARC and MRR, but
17490       // is a better option than rejecting programs using those unions under
17491       // ARC.
17492       FD->addAttr(UnavailableAttr::CreateImplicit(
17493           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17494           FD->getLocation()));
17495     } else if (getLangOpts().ObjC &&
17496                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17497                !Record->hasObjectMember()) {
17498       if (FD->getType()->isObjCObjectPointerType() ||
17499           FD->getType().isObjCGCStrong())
17500         Record->setHasObjectMember(true);
17501       else if (Context.getAsArrayType(FD->getType())) {
17502         QualType BaseType = Context.getBaseElementType(FD->getType());
17503         if (BaseType->isRecordType() &&
17504             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17505           Record->setHasObjectMember(true);
17506         else if (BaseType->isObjCObjectPointerType() ||
17507                  BaseType.isObjCGCStrong())
17508                Record->setHasObjectMember(true);
17509       }
17510     }
17511 
17512     if (Record && !getLangOpts().CPlusPlus &&
17513         !shouldIgnoreForRecordTriviality(FD)) {
17514       QualType FT = FD->getType();
17515       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17516         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17517         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17518             Record->isUnion())
17519           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17520       }
17521       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17522       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17523         Record->setNonTrivialToPrimitiveCopy(true);
17524         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17525           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17526       }
17527       if (FT.isDestructedType()) {
17528         Record->setNonTrivialToPrimitiveDestroy(true);
17529         Record->setParamDestroyedInCallee(true);
17530         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17531           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17532       }
17533 
17534       if (const auto *RT = FT->getAs<RecordType>()) {
17535         if (RT->getDecl()->getArgPassingRestrictions() ==
17536             RecordDecl::APK_CanNeverPassInRegs)
17537           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17538       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17539         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17540     }
17541 
17542     if (Record && FD->getType().isVolatileQualified())
17543       Record->setHasVolatileMember(true);
17544     // Keep track of the number of named members.
17545     if (FD->getIdentifier())
17546       ++NumNamedMembers;
17547   }
17548 
17549   // Okay, we successfully defined 'Record'.
17550   if (Record) {
17551     bool Completed = false;
17552     if (CXXRecord) {
17553       if (!CXXRecord->isInvalidDecl()) {
17554         // Set access bits correctly on the directly-declared conversions.
17555         for (CXXRecordDecl::conversion_iterator
17556                I = CXXRecord->conversion_begin(),
17557                E = CXXRecord->conversion_end(); I != E; ++I)
17558           I.setAccess((*I)->getAccess());
17559       }
17560 
17561       // Add any implicitly-declared members to this class.
17562       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17563 
17564       if (!CXXRecord->isDependentType()) {
17565         if (!CXXRecord->isInvalidDecl()) {
17566           // If we have virtual base classes, we may end up finding multiple
17567           // final overriders for a given virtual function. Check for this
17568           // problem now.
17569           if (CXXRecord->getNumVBases()) {
17570             CXXFinalOverriderMap FinalOverriders;
17571             CXXRecord->getFinalOverriders(FinalOverriders);
17572 
17573             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17574                                              MEnd = FinalOverriders.end();
17575                  M != MEnd; ++M) {
17576               for (OverridingMethods::iterator SO = M->second.begin(),
17577                                             SOEnd = M->second.end();
17578                    SO != SOEnd; ++SO) {
17579                 assert(SO->second.size() > 0 &&
17580                        "Virtual function without overriding functions?");
17581                 if (SO->second.size() == 1)
17582                   continue;
17583 
17584                 // C++ [class.virtual]p2:
17585                 //   In a derived class, if a virtual member function of a base
17586                 //   class subobject has more than one final overrider the
17587                 //   program is ill-formed.
17588                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17589                   << (const NamedDecl *)M->first << Record;
17590                 Diag(M->first->getLocation(),
17591                      diag::note_overridden_virtual_function);
17592                 for (OverridingMethods::overriding_iterator
17593                           OM = SO->second.begin(),
17594                        OMEnd = SO->second.end();
17595                      OM != OMEnd; ++OM)
17596                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17597                     << (const NamedDecl *)M->first << OM->Method->getParent();
17598 
17599                 Record->setInvalidDecl();
17600               }
17601             }
17602             CXXRecord->completeDefinition(&FinalOverriders);
17603             Completed = true;
17604           }
17605         }
17606       }
17607     }
17608 
17609     if (!Completed)
17610       Record->completeDefinition();
17611 
17612     // Handle attributes before checking the layout.
17613     ProcessDeclAttributeList(S, Record, Attrs);
17614 
17615     // We may have deferred checking for a deleted destructor. Check now.
17616     if (CXXRecord) {
17617       auto *Dtor = CXXRecord->getDestructor();
17618       if (Dtor && Dtor->isImplicit() &&
17619           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17620         CXXRecord->setImplicitDestructorIsDeleted();
17621         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17622       }
17623     }
17624 
17625     if (Record->hasAttrs()) {
17626       CheckAlignasUnderalignment(Record);
17627 
17628       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17629         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17630                                            IA->getRange(), IA->getBestCase(),
17631                                            IA->getInheritanceModel());
17632     }
17633 
17634     // Check if the structure/union declaration is a type that can have zero
17635     // size in C. For C this is a language extension, for C++ it may cause
17636     // compatibility problems.
17637     bool CheckForZeroSize;
17638     if (!getLangOpts().CPlusPlus) {
17639       CheckForZeroSize = true;
17640     } else {
17641       // For C++ filter out types that cannot be referenced in C code.
17642       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17643       CheckForZeroSize =
17644           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17645           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17646           CXXRecord->isCLike();
17647     }
17648     if (CheckForZeroSize) {
17649       bool ZeroSize = true;
17650       bool IsEmpty = true;
17651       unsigned NonBitFields = 0;
17652       for (RecordDecl::field_iterator I = Record->field_begin(),
17653                                       E = Record->field_end();
17654            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17655         IsEmpty = false;
17656         if (I->isUnnamedBitfield()) {
17657           if (!I->isZeroLengthBitField(Context))
17658             ZeroSize = false;
17659         } else {
17660           ++NonBitFields;
17661           QualType FieldType = I->getType();
17662           if (FieldType->isIncompleteType() ||
17663               !Context.getTypeSizeInChars(FieldType).isZero())
17664             ZeroSize = false;
17665         }
17666       }
17667 
17668       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17669       // allowed in C++, but warn if its declaration is inside
17670       // extern "C" block.
17671       if (ZeroSize) {
17672         Diag(RecLoc, getLangOpts().CPlusPlus ?
17673                          diag::warn_zero_size_struct_union_in_extern_c :
17674                          diag::warn_zero_size_struct_union_compat)
17675           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17676       }
17677 
17678       // Structs without named members are extension in C (C99 6.7.2.1p7),
17679       // but are accepted by GCC.
17680       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17681         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17682                                diag::ext_no_named_members_in_struct_union)
17683           << Record->isUnion();
17684       }
17685     }
17686   } else {
17687     ObjCIvarDecl **ClsFields =
17688       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17689     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17690       ID->setEndOfDefinitionLoc(RBrac);
17691       // Add ivar's to class's DeclContext.
17692       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17693         ClsFields[i]->setLexicalDeclContext(ID);
17694         ID->addDecl(ClsFields[i]);
17695       }
17696       // Must enforce the rule that ivars in the base classes may not be
17697       // duplicates.
17698       if (ID->getSuperClass())
17699         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17700     } else if (ObjCImplementationDecl *IMPDecl =
17701                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17702       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17703       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17704         // Ivar declared in @implementation never belongs to the implementation.
17705         // Only it is in implementation's lexical context.
17706         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17707       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17708       IMPDecl->setIvarLBraceLoc(LBrac);
17709       IMPDecl->setIvarRBraceLoc(RBrac);
17710     } else if (ObjCCategoryDecl *CDecl =
17711                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17712       // case of ivars in class extension; all other cases have been
17713       // reported as errors elsewhere.
17714       // FIXME. Class extension does not have a LocEnd field.
17715       // CDecl->setLocEnd(RBrac);
17716       // Add ivar's to class extension's DeclContext.
17717       // Diagnose redeclaration of private ivars.
17718       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17719       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17720         if (IDecl) {
17721           if (const ObjCIvarDecl *ClsIvar =
17722               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17723             Diag(ClsFields[i]->getLocation(),
17724                  diag::err_duplicate_ivar_declaration);
17725             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17726             continue;
17727           }
17728           for (const auto *Ext : IDecl->known_extensions()) {
17729             if (const ObjCIvarDecl *ClsExtIvar
17730                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17731               Diag(ClsFields[i]->getLocation(),
17732                    diag::err_duplicate_ivar_declaration);
17733               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17734               continue;
17735             }
17736           }
17737         }
17738         ClsFields[i]->setLexicalDeclContext(CDecl);
17739         CDecl->addDecl(ClsFields[i]);
17740       }
17741       CDecl->setIvarLBraceLoc(LBrac);
17742       CDecl->setIvarRBraceLoc(RBrac);
17743     }
17744   }
17745 }
17746 
17747 /// Determine whether the given integral value is representable within
17748 /// the given type T.
17749 static bool isRepresentableIntegerValue(ASTContext &Context,
17750                                         llvm::APSInt &Value,
17751                                         QualType T) {
17752   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17753          "Integral type required!");
17754   unsigned BitWidth = Context.getIntWidth(T);
17755 
17756   if (Value.isUnsigned() || Value.isNonNegative()) {
17757     if (T->isSignedIntegerOrEnumerationType())
17758       --BitWidth;
17759     return Value.getActiveBits() <= BitWidth;
17760   }
17761   return Value.getMinSignedBits() <= BitWidth;
17762 }
17763 
17764 // Given an integral type, return the next larger integral type
17765 // (or a NULL type of no such type exists).
17766 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17767   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17768   // enum checking below.
17769   assert((T->isIntegralType(Context) ||
17770          T->isEnumeralType()) && "Integral type required!");
17771   const unsigned NumTypes = 4;
17772   QualType SignedIntegralTypes[NumTypes] = {
17773     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17774   };
17775   QualType UnsignedIntegralTypes[NumTypes] = {
17776     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17777     Context.UnsignedLongLongTy
17778   };
17779 
17780   unsigned BitWidth = Context.getTypeSize(T);
17781   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17782                                                         : UnsignedIntegralTypes;
17783   for (unsigned I = 0; I != NumTypes; ++I)
17784     if (Context.getTypeSize(Types[I]) > BitWidth)
17785       return Types[I];
17786 
17787   return QualType();
17788 }
17789 
17790 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17791                                           EnumConstantDecl *LastEnumConst,
17792                                           SourceLocation IdLoc,
17793                                           IdentifierInfo *Id,
17794                                           Expr *Val) {
17795   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17796   llvm::APSInt EnumVal(IntWidth);
17797   QualType EltTy;
17798 
17799   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17800     Val = nullptr;
17801 
17802   if (Val)
17803     Val = DefaultLvalueConversion(Val).get();
17804 
17805   if (Val) {
17806     if (Enum->isDependentType() || Val->isTypeDependent())
17807       EltTy = Context.DependentTy;
17808     else {
17809       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17810       // underlying type, but do allow it in all other contexts.
17811       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17812         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17813         // constant-expression in the enumerator-definition shall be a converted
17814         // constant expression of the underlying type.
17815         EltTy = Enum->getIntegerType();
17816         ExprResult Converted =
17817           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17818                                            CCEK_Enumerator);
17819         if (Converted.isInvalid())
17820           Val = nullptr;
17821         else
17822           Val = Converted.get();
17823       } else if (!Val->isValueDependent() &&
17824                  !(Val =
17825                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17826                            .get())) {
17827         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17828       } else {
17829         if (Enum->isComplete()) {
17830           EltTy = Enum->getIntegerType();
17831 
17832           // In Obj-C and Microsoft mode, require the enumeration value to be
17833           // representable in the underlying type of the enumeration. In C++11,
17834           // we perform a non-narrowing conversion as part of converted constant
17835           // expression checking.
17836           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17837             if (Context.getTargetInfo()
17838                     .getTriple()
17839                     .isWindowsMSVCEnvironment()) {
17840               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17841             } else {
17842               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17843             }
17844           }
17845 
17846           // Cast to the underlying type.
17847           Val = ImpCastExprToType(Val, EltTy,
17848                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17849                                                          : CK_IntegralCast)
17850                     .get();
17851         } else if (getLangOpts().CPlusPlus) {
17852           // C++11 [dcl.enum]p5:
17853           //   If the underlying type is not fixed, the type of each enumerator
17854           //   is the type of its initializing value:
17855           //     - If an initializer is specified for an enumerator, the
17856           //       initializing value has the same type as the expression.
17857           EltTy = Val->getType();
17858         } else {
17859           // C99 6.7.2.2p2:
17860           //   The expression that defines the value of an enumeration constant
17861           //   shall be an integer constant expression that has a value
17862           //   representable as an int.
17863 
17864           // Complain if the value is not representable in an int.
17865           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17866             Diag(IdLoc, diag::ext_enum_value_not_int)
17867               << toString(EnumVal, 10) << Val->getSourceRange()
17868               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17869           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17870             // Force the type of the expression to 'int'.
17871             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17872           }
17873           EltTy = Val->getType();
17874         }
17875       }
17876     }
17877   }
17878 
17879   if (!Val) {
17880     if (Enum->isDependentType())
17881       EltTy = Context.DependentTy;
17882     else if (!LastEnumConst) {
17883       // C++0x [dcl.enum]p5:
17884       //   If the underlying type is not fixed, the type of each enumerator
17885       //   is the type of its initializing value:
17886       //     - If no initializer is specified for the first enumerator, the
17887       //       initializing value has an unspecified integral type.
17888       //
17889       // GCC uses 'int' for its unspecified integral type, as does
17890       // C99 6.7.2.2p3.
17891       if (Enum->isFixed()) {
17892         EltTy = Enum->getIntegerType();
17893       }
17894       else {
17895         EltTy = Context.IntTy;
17896       }
17897     } else {
17898       // Assign the last value + 1.
17899       EnumVal = LastEnumConst->getInitVal();
17900       ++EnumVal;
17901       EltTy = LastEnumConst->getType();
17902 
17903       // Check for overflow on increment.
17904       if (EnumVal < LastEnumConst->getInitVal()) {
17905         // C++0x [dcl.enum]p5:
17906         //   If the underlying type is not fixed, the type of each enumerator
17907         //   is the type of its initializing value:
17908         //
17909         //     - Otherwise the type of the initializing value is the same as
17910         //       the type of the initializing value of the preceding enumerator
17911         //       unless the incremented value is not representable in that type,
17912         //       in which case the type is an unspecified integral type
17913         //       sufficient to contain the incremented value. If no such type
17914         //       exists, the program is ill-formed.
17915         QualType T = getNextLargerIntegralType(Context, EltTy);
17916         if (T.isNull() || Enum->isFixed()) {
17917           // There is no integral type larger enough to represent this
17918           // value. Complain, then allow the value to wrap around.
17919           EnumVal = LastEnumConst->getInitVal();
17920           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17921           ++EnumVal;
17922           if (Enum->isFixed())
17923             // When the underlying type is fixed, this is ill-formed.
17924             Diag(IdLoc, diag::err_enumerator_wrapped)
17925               << toString(EnumVal, 10)
17926               << EltTy;
17927           else
17928             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17929               << toString(EnumVal, 10);
17930         } else {
17931           EltTy = T;
17932         }
17933 
17934         // Retrieve the last enumerator's value, extent that type to the
17935         // type that is supposed to be large enough to represent the incremented
17936         // value, then increment.
17937         EnumVal = LastEnumConst->getInitVal();
17938         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17939         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17940         ++EnumVal;
17941 
17942         // If we're not in C++, diagnose the overflow of enumerator values,
17943         // which in C99 means that the enumerator value is not representable in
17944         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17945         // permits enumerator values that are representable in some larger
17946         // integral type.
17947         if (!getLangOpts().CPlusPlus && !T.isNull())
17948           Diag(IdLoc, diag::warn_enum_value_overflow);
17949       } else if (!getLangOpts().CPlusPlus &&
17950                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17951         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17952         Diag(IdLoc, diag::ext_enum_value_not_int)
17953           << toString(EnumVal, 10) << 1;
17954       }
17955     }
17956   }
17957 
17958   if (!EltTy->isDependentType()) {
17959     // Make the enumerator value match the signedness and size of the
17960     // enumerator's type.
17961     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17962     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17963   }
17964 
17965   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17966                                   Val, EnumVal);
17967 }
17968 
17969 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17970                                                 SourceLocation IILoc) {
17971   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17972       !getLangOpts().CPlusPlus)
17973     return SkipBodyInfo();
17974 
17975   // We have an anonymous enum definition. Look up the first enumerator to
17976   // determine if we should merge the definition with an existing one and
17977   // skip the body.
17978   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17979                                          forRedeclarationInCurContext());
17980   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17981   if (!PrevECD)
17982     return SkipBodyInfo();
17983 
17984   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17985   NamedDecl *Hidden;
17986   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17987     SkipBodyInfo Skip;
17988     Skip.Previous = Hidden;
17989     return Skip;
17990   }
17991 
17992   return SkipBodyInfo();
17993 }
17994 
17995 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17996                               SourceLocation IdLoc, IdentifierInfo *Id,
17997                               const ParsedAttributesView &Attrs,
17998                               SourceLocation EqualLoc, Expr *Val) {
17999   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18000   EnumConstantDecl *LastEnumConst =
18001     cast_or_null<EnumConstantDecl>(lastEnumConst);
18002 
18003   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18004   // we find one that is.
18005   S = getNonFieldDeclScope(S);
18006 
18007   // Verify that there isn't already something declared with this name in this
18008   // scope.
18009   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18010   LookupName(R, S);
18011   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18012 
18013   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18014     // Maybe we will complain about the shadowed template parameter.
18015     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18016     // Just pretend that we didn't see the previous declaration.
18017     PrevDecl = nullptr;
18018   }
18019 
18020   // C++ [class.mem]p15:
18021   // If T is the name of a class, then each of the following shall have a name
18022   // different from T:
18023   // - every enumerator of every member of class T that is an unscoped
18024   // enumerated type
18025   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18026     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18027                             DeclarationNameInfo(Id, IdLoc));
18028 
18029   EnumConstantDecl *New =
18030     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18031   if (!New)
18032     return nullptr;
18033 
18034   if (PrevDecl) {
18035     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18036       // Check for other kinds of shadowing not already handled.
18037       CheckShadow(New, PrevDecl, R);
18038     }
18039 
18040     // When in C++, we may get a TagDecl with the same name; in this case the
18041     // enum constant will 'hide' the tag.
18042     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18043            "Received TagDecl when not in C++!");
18044     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18045       if (isa<EnumConstantDecl>(PrevDecl))
18046         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18047       else
18048         Diag(IdLoc, diag::err_redefinition) << Id;
18049       notePreviousDefinition(PrevDecl, IdLoc);
18050       return nullptr;
18051     }
18052   }
18053 
18054   // Process attributes.
18055   ProcessDeclAttributeList(S, New, Attrs);
18056   AddPragmaAttributes(S, New);
18057 
18058   // Register this decl in the current scope stack.
18059   New->setAccess(TheEnumDecl->getAccess());
18060   PushOnScopeChains(New, S);
18061 
18062   ActOnDocumentableDecl(New);
18063 
18064   return New;
18065 }
18066 
18067 // Returns true when the enum initial expression does not trigger the
18068 // duplicate enum warning.  A few common cases are exempted as follows:
18069 // Element2 = Element1
18070 // Element2 = Element1 + 1
18071 // Element2 = Element1 - 1
18072 // Where Element2 and Element1 are from the same enum.
18073 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18074   Expr *InitExpr = ECD->getInitExpr();
18075   if (!InitExpr)
18076     return true;
18077   InitExpr = InitExpr->IgnoreImpCasts();
18078 
18079   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18080     if (!BO->isAdditiveOp())
18081       return true;
18082     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18083     if (!IL)
18084       return true;
18085     if (IL->getValue() != 1)
18086       return true;
18087 
18088     InitExpr = BO->getLHS();
18089   }
18090 
18091   // This checks if the elements are from the same enum.
18092   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18093   if (!DRE)
18094     return true;
18095 
18096   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18097   if (!EnumConstant)
18098     return true;
18099 
18100   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18101       Enum)
18102     return true;
18103 
18104   return false;
18105 }
18106 
18107 // Emits a warning when an element is implicitly set a value that
18108 // a previous element has already been set to.
18109 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18110                                         EnumDecl *Enum, QualType EnumType) {
18111   // Avoid anonymous enums
18112   if (!Enum->getIdentifier())
18113     return;
18114 
18115   // Only check for small enums.
18116   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18117     return;
18118 
18119   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18120     return;
18121 
18122   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18123   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18124 
18125   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18126 
18127   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18128   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18129 
18130   // Use int64_t as a key to avoid needing special handling for map keys.
18131   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18132     llvm::APSInt Val = D->getInitVal();
18133     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18134   };
18135 
18136   DuplicatesVector DupVector;
18137   ValueToVectorMap EnumMap;
18138 
18139   // Populate the EnumMap with all values represented by enum constants without
18140   // an initializer.
18141   for (auto *Element : Elements) {
18142     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18143 
18144     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18145     // this constant.  Skip this enum since it may be ill-formed.
18146     if (!ECD) {
18147       return;
18148     }
18149 
18150     // Constants with initalizers are handled in the next loop.
18151     if (ECD->getInitExpr())
18152       continue;
18153 
18154     // Duplicate values are handled in the next loop.
18155     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18156   }
18157 
18158   if (EnumMap.size() == 0)
18159     return;
18160 
18161   // Create vectors for any values that has duplicates.
18162   for (auto *Element : Elements) {
18163     // The last loop returned if any constant was null.
18164     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18165     if (!ValidDuplicateEnum(ECD, Enum))
18166       continue;
18167 
18168     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18169     if (Iter == EnumMap.end())
18170       continue;
18171 
18172     DeclOrVector& Entry = Iter->second;
18173     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18174       // Ensure constants are different.
18175       if (D == ECD)
18176         continue;
18177 
18178       // Create new vector and push values onto it.
18179       auto Vec = std::make_unique<ECDVector>();
18180       Vec->push_back(D);
18181       Vec->push_back(ECD);
18182 
18183       // Update entry to point to the duplicates vector.
18184       Entry = Vec.get();
18185 
18186       // Store the vector somewhere we can consult later for quick emission of
18187       // diagnostics.
18188       DupVector.emplace_back(std::move(Vec));
18189       continue;
18190     }
18191 
18192     ECDVector *Vec = Entry.get<ECDVector*>();
18193     // Make sure constants are not added more than once.
18194     if (*Vec->begin() == ECD)
18195       continue;
18196 
18197     Vec->push_back(ECD);
18198   }
18199 
18200   // Emit diagnostics.
18201   for (const auto &Vec : DupVector) {
18202     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18203 
18204     // Emit warning for one enum constant.
18205     auto *FirstECD = Vec->front();
18206     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18207       << FirstECD << toString(FirstECD->getInitVal(), 10)
18208       << FirstECD->getSourceRange();
18209 
18210     // Emit one note for each of the remaining enum constants with
18211     // the same value.
18212     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18213       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18214         << ECD << toString(ECD->getInitVal(), 10)
18215         << ECD->getSourceRange();
18216   }
18217 }
18218 
18219 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18220                              bool AllowMask) const {
18221   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18222   assert(ED->isCompleteDefinition() && "expected enum definition");
18223 
18224   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18225   llvm::APInt &FlagBits = R.first->second;
18226 
18227   if (R.second) {
18228     for (auto *E : ED->enumerators()) {
18229       const auto &EVal = E->getInitVal();
18230       // Only single-bit enumerators introduce new flag values.
18231       if (EVal.isPowerOf2())
18232         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18233     }
18234   }
18235 
18236   // A value is in a flag enum if either its bits are a subset of the enum's
18237   // flag bits (the first condition) or we are allowing masks and the same is
18238   // true of its complement (the second condition). When masks are allowed, we
18239   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18240   //
18241   // While it's true that any value could be used as a mask, the assumption is
18242   // that a mask will have all of the insignificant bits set. Anything else is
18243   // likely a logic error.
18244   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18245   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18246 }
18247 
18248 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18249                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18250                          const ParsedAttributesView &Attrs) {
18251   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18252   QualType EnumType = Context.getTypeDeclType(Enum);
18253 
18254   ProcessDeclAttributeList(S, Enum, Attrs);
18255 
18256   if (Enum->isDependentType()) {
18257     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18258       EnumConstantDecl *ECD =
18259         cast_or_null<EnumConstantDecl>(Elements[i]);
18260       if (!ECD) continue;
18261 
18262       ECD->setType(EnumType);
18263     }
18264 
18265     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18266     return;
18267   }
18268 
18269   // TODO: If the result value doesn't fit in an int, it must be a long or long
18270   // long value.  ISO C does not support this, but GCC does as an extension,
18271   // emit a warning.
18272   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18273   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18274   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18275 
18276   // Verify that all the values are okay, compute the size of the values, and
18277   // reverse the list.
18278   unsigned NumNegativeBits = 0;
18279   unsigned NumPositiveBits = 0;
18280 
18281   // Keep track of whether all elements have type int.
18282   bool AllElementsInt = true;
18283 
18284   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18285     EnumConstantDecl *ECD =
18286       cast_or_null<EnumConstantDecl>(Elements[i]);
18287     if (!ECD) continue;  // Already issued a diagnostic.
18288 
18289     const llvm::APSInt &InitVal = ECD->getInitVal();
18290 
18291     // Keep track of the size of positive and negative values.
18292     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18293       NumPositiveBits = std::max(NumPositiveBits,
18294                                  (unsigned)InitVal.getActiveBits());
18295     else
18296       NumNegativeBits = std::max(NumNegativeBits,
18297                                  (unsigned)InitVal.getMinSignedBits());
18298 
18299     // Keep track of whether every enum element has type int (very common).
18300     if (AllElementsInt)
18301       AllElementsInt = ECD->getType() == Context.IntTy;
18302   }
18303 
18304   // Figure out the type that should be used for this enum.
18305   QualType BestType;
18306   unsigned BestWidth;
18307 
18308   // C++0x N3000 [conv.prom]p3:
18309   //   An rvalue of an unscoped enumeration type whose underlying
18310   //   type is not fixed can be converted to an rvalue of the first
18311   //   of the following types that can represent all the values of
18312   //   the enumeration: int, unsigned int, long int, unsigned long
18313   //   int, long long int, or unsigned long long int.
18314   // C99 6.4.4.3p2:
18315   //   An identifier declared as an enumeration constant has type int.
18316   // The C99 rule is modified by a gcc extension
18317   QualType BestPromotionType;
18318 
18319   bool Packed = Enum->hasAttr<PackedAttr>();
18320   // -fshort-enums is the equivalent to specifying the packed attribute on all
18321   // enum definitions.
18322   if (LangOpts.ShortEnums)
18323     Packed = true;
18324 
18325   // If the enum already has a type because it is fixed or dictated by the
18326   // target, promote that type instead of analyzing the enumerators.
18327   if (Enum->isComplete()) {
18328     BestType = Enum->getIntegerType();
18329     if (BestType->isPromotableIntegerType())
18330       BestPromotionType = Context.getPromotedIntegerType(BestType);
18331     else
18332       BestPromotionType = BestType;
18333 
18334     BestWidth = Context.getIntWidth(BestType);
18335   }
18336   else if (NumNegativeBits) {
18337     // If there is a negative value, figure out the smallest integer type (of
18338     // int/long/longlong) that fits.
18339     // If it's packed, check also if it fits a char or a short.
18340     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18341       BestType = Context.SignedCharTy;
18342       BestWidth = CharWidth;
18343     } else if (Packed && NumNegativeBits <= ShortWidth &&
18344                NumPositiveBits < ShortWidth) {
18345       BestType = Context.ShortTy;
18346       BestWidth = ShortWidth;
18347     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18348       BestType = Context.IntTy;
18349       BestWidth = IntWidth;
18350     } else {
18351       BestWidth = Context.getTargetInfo().getLongWidth();
18352 
18353       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18354         BestType = Context.LongTy;
18355       } else {
18356         BestWidth = Context.getTargetInfo().getLongLongWidth();
18357 
18358         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18359           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18360         BestType = Context.LongLongTy;
18361       }
18362     }
18363     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18364   } else {
18365     // If there is no negative value, figure out the smallest type that fits
18366     // all of the enumerator values.
18367     // If it's packed, check also if it fits a char or a short.
18368     if (Packed && NumPositiveBits <= CharWidth) {
18369       BestType = Context.UnsignedCharTy;
18370       BestPromotionType = Context.IntTy;
18371       BestWidth = CharWidth;
18372     } else if (Packed && NumPositiveBits <= ShortWidth) {
18373       BestType = Context.UnsignedShortTy;
18374       BestPromotionType = Context.IntTy;
18375       BestWidth = ShortWidth;
18376     } else if (NumPositiveBits <= IntWidth) {
18377       BestType = Context.UnsignedIntTy;
18378       BestWidth = IntWidth;
18379       BestPromotionType
18380         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18381                            ? Context.UnsignedIntTy : Context.IntTy;
18382     } else if (NumPositiveBits <=
18383                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18384       BestType = Context.UnsignedLongTy;
18385       BestPromotionType
18386         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18387                            ? Context.UnsignedLongTy : Context.LongTy;
18388     } else {
18389       BestWidth = Context.getTargetInfo().getLongLongWidth();
18390       assert(NumPositiveBits <= BestWidth &&
18391              "How could an initializer get larger than ULL?");
18392       BestType = Context.UnsignedLongLongTy;
18393       BestPromotionType
18394         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18395                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18396     }
18397   }
18398 
18399   // Loop over all of the enumerator constants, changing their types to match
18400   // the type of the enum if needed.
18401   for (auto *D : Elements) {
18402     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18403     if (!ECD) continue;  // Already issued a diagnostic.
18404 
18405     // Standard C says the enumerators have int type, but we allow, as an
18406     // extension, the enumerators to be larger than int size.  If each
18407     // enumerator value fits in an int, type it as an int, otherwise type it the
18408     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18409     // that X has type 'int', not 'unsigned'.
18410 
18411     // Determine whether the value fits into an int.
18412     llvm::APSInt InitVal = ECD->getInitVal();
18413 
18414     // If it fits into an integer type, force it.  Otherwise force it to match
18415     // the enum decl type.
18416     QualType NewTy;
18417     unsigned NewWidth;
18418     bool NewSign;
18419     if (!getLangOpts().CPlusPlus &&
18420         !Enum->isFixed() &&
18421         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18422       NewTy = Context.IntTy;
18423       NewWidth = IntWidth;
18424       NewSign = true;
18425     } else if (ECD->getType() == BestType) {
18426       // Already the right type!
18427       if (getLangOpts().CPlusPlus)
18428         // C++ [dcl.enum]p4: Following the closing brace of an
18429         // enum-specifier, each enumerator has the type of its
18430         // enumeration.
18431         ECD->setType(EnumType);
18432       continue;
18433     } else {
18434       NewTy = BestType;
18435       NewWidth = BestWidth;
18436       NewSign = BestType->isSignedIntegerOrEnumerationType();
18437     }
18438 
18439     // Adjust the APSInt value.
18440     InitVal = InitVal.extOrTrunc(NewWidth);
18441     InitVal.setIsSigned(NewSign);
18442     ECD->setInitVal(InitVal);
18443 
18444     // Adjust the Expr initializer and type.
18445     if (ECD->getInitExpr() &&
18446         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18447       ECD->setInitExpr(ImplicitCastExpr::Create(
18448           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18449           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18450     if (getLangOpts().CPlusPlus)
18451       // C++ [dcl.enum]p4: Following the closing brace of an
18452       // enum-specifier, each enumerator has the type of its
18453       // enumeration.
18454       ECD->setType(EnumType);
18455     else
18456       ECD->setType(NewTy);
18457   }
18458 
18459   Enum->completeDefinition(BestType, BestPromotionType,
18460                            NumPositiveBits, NumNegativeBits);
18461 
18462   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18463 
18464   if (Enum->isClosedFlag()) {
18465     for (Decl *D : Elements) {
18466       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18467       if (!ECD) continue;  // Already issued a diagnostic.
18468 
18469       llvm::APSInt InitVal = ECD->getInitVal();
18470       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18471           !IsValueInFlagEnum(Enum, InitVal, true))
18472         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18473           << ECD << Enum;
18474     }
18475   }
18476 
18477   // Now that the enum type is defined, ensure it's not been underaligned.
18478   if (Enum->hasAttrs())
18479     CheckAlignasUnderalignment(Enum);
18480 }
18481 
18482 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18483                                   SourceLocation StartLoc,
18484                                   SourceLocation EndLoc) {
18485   StringLiteral *AsmString = cast<StringLiteral>(expr);
18486 
18487   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18488                                                    AsmString, StartLoc,
18489                                                    EndLoc);
18490   CurContext->addDecl(New);
18491   return New;
18492 }
18493 
18494 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18495                                       IdentifierInfo* AliasName,
18496                                       SourceLocation PragmaLoc,
18497                                       SourceLocation NameLoc,
18498                                       SourceLocation AliasNameLoc) {
18499   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18500                                          LookupOrdinaryName);
18501   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18502                            AttributeCommonInfo::AS_Pragma);
18503   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18504       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18505 
18506   // If a declaration that:
18507   // 1) declares a function or a variable
18508   // 2) has external linkage
18509   // already exists, add a label attribute to it.
18510   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18511     if (isDeclExternC(PrevDecl))
18512       PrevDecl->addAttr(Attr);
18513     else
18514       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18515           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18516   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18517   } else
18518     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18519 }
18520 
18521 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18522                              SourceLocation PragmaLoc,
18523                              SourceLocation NameLoc) {
18524   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18525 
18526   if (PrevDecl) {
18527     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18528   } else {
18529     (void)WeakUndeclaredIdentifiers.insert(
18530       std::pair<IdentifierInfo*,WeakInfo>
18531         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18532   }
18533 }
18534 
18535 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18536                                 IdentifierInfo* AliasName,
18537                                 SourceLocation PragmaLoc,
18538                                 SourceLocation NameLoc,
18539                                 SourceLocation AliasNameLoc) {
18540   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18541                                     LookupOrdinaryName);
18542   WeakInfo W = WeakInfo(Name, NameLoc);
18543 
18544   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18545     if (!PrevDecl->hasAttr<AliasAttr>())
18546       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18547         DeclApplyPragmaWeak(TUScope, ND, W);
18548   } else {
18549     (void)WeakUndeclaredIdentifiers.insert(
18550       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18551   }
18552 }
18553 
18554 Decl *Sema::getObjCDeclContext() const {
18555   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18556 }
18557 
18558 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18559                                                      bool Final) {
18560   assert(FD && "Expected non-null FunctionDecl");
18561 
18562   // SYCL functions can be template, so we check if they have appropriate
18563   // attribute prior to checking if it is a template.
18564   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18565     return FunctionEmissionStatus::Emitted;
18566 
18567   // Templates are emitted when they're instantiated.
18568   if (FD->isDependentContext())
18569     return FunctionEmissionStatus::TemplateDiscarded;
18570 
18571   // Check whether this function is an externally visible definition.
18572   auto IsEmittedForExternalSymbol = [this, FD]() {
18573     // We have to check the GVA linkage of the function's *definition* -- if we
18574     // only have a declaration, we don't know whether or not the function will
18575     // be emitted, because (say) the definition could include "inline".
18576     FunctionDecl *Def = FD->getDefinition();
18577 
18578     return Def && !isDiscardableGVALinkage(
18579                       getASTContext().GetGVALinkageForFunction(Def));
18580   };
18581 
18582   if (LangOpts.OpenMPIsDevice) {
18583     // In OpenMP device mode we will not emit host only functions, or functions
18584     // we don't need due to their linkage.
18585     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18586         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18587     // DevTy may be changed later by
18588     //  #pragma omp declare target to(*) device_type(*).
18589     // Therefore DevTy having no value does not imply host. The emission status
18590     // will be checked again at the end of compilation unit with Final = true.
18591     if (DevTy.hasValue())
18592       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18593         return FunctionEmissionStatus::OMPDiscarded;
18594     // If we have an explicit value for the device type, or we are in a target
18595     // declare context, we need to emit all extern and used symbols.
18596     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18597       if (IsEmittedForExternalSymbol())
18598         return FunctionEmissionStatus::Emitted;
18599     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18600     // we'll omit it.
18601     if (Final)
18602       return FunctionEmissionStatus::OMPDiscarded;
18603   } else if (LangOpts.OpenMP > 45) {
18604     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18605     // function. In 5.0, no_host was introduced which might cause a function to
18606     // be ommitted.
18607     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18608         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18609     if (DevTy.hasValue())
18610       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18611         return FunctionEmissionStatus::OMPDiscarded;
18612   }
18613 
18614   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18615     return FunctionEmissionStatus::Emitted;
18616 
18617   if (LangOpts.CUDA) {
18618     // When compiling for device, host functions are never emitted.  Similarly,
18619     // when compiling for host, device and global functions are never emitted.
18620     // (Technically, we do emit a host-side stub for global functions, but this
18621     // doesn't count for our purposes here.)
18622     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18623     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18624       return FunctionEmissionStatus::CUDADiscarded;
18625     if (!LangOpts.CUDAIsDevice &&
18626         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18627       return FunctionEmissionStatus::CUDADiscarded;
18628 
18629     if (IsEmittedForExternalSymbol())
18630       return FunctionEmissionStatus::Emitted;
18631   }
18632 
18633   // Otherwise, the function is known-emitted if it's in our set of
18634   // known-emitted functions.
18635   return FunctionEmissionStatus::Unknown;
18636 }
18637 
18638 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18639   // Host-side references to a __global__ function refer to the stub, so the
18640   // function itself is never emitted and therefore should not be marked.
18641   // If we have host fn calls kernel fn calls host+device, the HD function
18642   // does not get instantiated on the host. We model this by omitting at the
18643   // call to the kernel from the callgraph. This ensures that, when compiling
18644   // for host, only HD functions actually called from the host get marked as
18645   // known-emitted.
18646   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18647          IdentifyCUDATarget(Callee) == CFT_Global;
18648 }
18649