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   UsingShadowDecl *FoundUsingShadow = nullptr;
376   switch (Result.getResultKind()) {
377   case LookupResult::NotFound:
378   case LookupResult::NotFoundInCurrentInstantiation:
379     if (CorrectedII) {
380       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
381                                AllowDeducedTemplate);
382       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
383                                               S, SS, CCC, CTK_ErrorRecovery);
384       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
385       TemplateTy Template;
386       bool MemberOfUnknownSpecialization;
387       UnqualifiedId TemplateName;
388       TemplateName.setIdentifier(NewII, NameLoc);
389       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
390       CXXScopeSpec NewSS, *NewSSPtr = SS;
391       if (SS && NNS) {
392         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
393         NewSSPtr = &NewSS;
394       }
395       if (Correction && (NNS || NewII != &II) &&
396           // Ignore a correction to a template type as the to-be-corrected
397           // identifier is not a template (typo correction for template names
398           // is handled elsewhere).
399           !(getLangOpts().CPlusPlus && NewSSPtr &&
400             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
401                            Template, MemberOfUnknownSpecialization))) {
402         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
403                                     isClassName, HasTrailingDot, ObjectTypePtr,
404                                     IsCtorOrDtorName,
405                                     WantNontrivialTypeSourceInfo,
406                                     IsClassTemplateDeductionContext);
407         if (Ty) {
408           diagnoseTypo(Correction,
409                        PDiag(diag::err_unknown_type_or_class_name_suggest)
410                          << Result.getLookupName() << isClassName);
411           if (SS && NNS)
412             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
413           *CorrectedII = NewII;
414           return Ty;
415         }
416       }
417     }
418     // If typo correction failed or was not performed, fall through
419     LLVM_FALLTHROUGH;
420   case LookupResult::FoundOverloaded:
421   case LookupResult::FoundUnresolvedValue:
422     Result.suppressDiagnostics();
423     return nullptr;
424 
425   case LookupResult::Ambiguous:
426     // Recover from type-hiding ambiguities by hiding the type.  We'll
427     // do the lookup again when looking for an object, and we can
428     // diagnose the error then.  If we don't do this, then the error
429     // about hiding the type will be immediately followed by an error
430     // that only makes sense if the identifier was treated like a type.
431     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
432       Result.suppressDiagnostics();
433       return nullptr;
434     }
435 
436     // Look to see if we have a type anywhere in the list of results.
437     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
438          Res != ResEnd; ++Res) {
439       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
440       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
441               RealRes) ||
442           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
443         if (!IIDecl ||
444             // Make the selection of the recovery decl deterministic.
445             RealRes->getLocation() < IIDecl->getLocation()) {
446           IIDecl = RealRes;
447           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
448         }
449       }
450     }
451 
452     if (!IIDecl) {
453       // None of the entities we found is a type, so there is no way
454       // to even assume that the result is a type. In this case, don't
455       // complain about the ambiguity. The parser will either try to
456       // perform this lookup again (e.g., as an object name), which
457       // will produce the ambiguity, or will complain that it expected
458       // a type name.
459       Result.suppressDiagnostics();
460       return nullptr;
461     }
462 
463     // We found a type within the ambiguous lookup; diagnose the
464     // ambiguity and then return that type. This might be the right
465     // answer, or it might not be, but it suppresses any attempt to
466     // perform the name lookup again.
467     break;
468 
469   case LookupResult::Found:
470     IIDecl = Result.getFoundDecl();
471     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
472     break;
473   }
474 
475   assert(IIDecl && "Didn't find decl");
476 
477   QualType T;
478   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
479     // C++ [class.qual]p2: A lookup that would find the injected-class-name
480     // instead names the constructors of the class, except when naming a class.
481     // This is ill-formed when we're not actually forming a ctor or dtor name.
482     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
483     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
484     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
485         FoundRD->isInjectedClassName() &&
486         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
487       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
488           << &II << /*Type*/1;
489 
490     DiagnoseUseOfDecl(IIDecl, NameLoc);
491 
492     T = Context.getTypeDeclType(TD);
493     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
494   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
495     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
496     if (!HasTrailingDot)
497       T = Context.getObjCInterfaceType(IDecl);
498     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
499   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
500     (void)DiagnoseUseOfDecl(UD, NameLoc);
501     // Recover with 'int'
502     T = Context.IntTy;
503     FoundUsingShadow = nullptr;
504   } else if (AllowDeducedTemplate) {
505     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
506       // FIXME: TemplateName should include FoundUsingShadow sugar.
507       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
508                                                        QualType(), false);
509       // Don't wrap in a further UsingType.
510       FoundUsingShadow = nullptr;
511     }
512   }
513 
514   if (T.isNull()) {
515     // If it's not plausibly a type, suppress diagnostics.
516     Result.suppressDiagnostics();
517     return nullptr;
518   }
519 
520   if (FoundUsingShadow)
521     T = Context.getUsingType(FoundUsingShadow, T);
522 
523   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
524   // constructor or destructor name (in such a case, the scope specifier
525   // will be attached to the enclosing Expr or Decl node).
526   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
527       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
528     if (WantNontrivialTypeSourceInfo) {
529       // Construct a type with type-source information.
530       TypeLocBuilder Builder;
531       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
532 
533       T = getElaboratedType(ETK_None, *SS, T);
534       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
535       ElabTL.setElaboratedKeywordLoc(SourceLocation());
536       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
537       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
538     } else {
539       T = getElaboratedType(ETK_None, *SS, T);
540     }
541   }
542 
543   return ParsedType::make(T);
544 }
545 
546 // Builds a fake NNS for the given decl context.
547 static NestedNameSpecifier *
548 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
549   for (;; DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     auto *ND = dyn_cast<NamespaceDecl>(DC);
552     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
553       return NestedNameSpecifier::Create(Context, nullptr, ND);
554     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
555       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
556                                          RD->getTypeForDecl());
557     else if (isa<TranslationUnitDecl>(DC))
558       return NestedNameSpecifier::GlobalSpecifier(Context);
559   }
560   llvm_unreachable("something isn't in TU scope?");
561 }
562 
563 /// Find the parent class with dependent bases of the innermost enclosing method
564 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
565 /// up allowing unqualified dependent type names at class-level, which MSVC
566 /// correctly rejects.
567 static const CXXRecordDecl *
568 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
569   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
570     DC = DC->getPrimaryContext();
571     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
572       if (MD->getParent()->hasAnyDependentBases())
573         return MD->getParent();
574   }
575   return nullptr;
576 }
577 
578 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
579                                           SourceLocation NameLoc,
580                                           bool IsTemplateTypeArg) {
581   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
582 
583   NestedNameSpecifier *NNS = nullptr;
584   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
585     // If we weren't able to parse a default template argument, delay lookup
586     // until instantiation time by making a non-dependent DependentTypeName. We
587     // pretend we saw a NestedNameSpecifier referring to the current scope, and
588     // lookup is retried.
589     // FIXME: This hurts our diagnostic quality, since we get errors like "no
590     // type named 'Foo' in 'current_namespace'" when the user didn't write any
591     // name specifiers.
592     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
593     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
594   } else if (const CXXRecordDecl *RD =
595                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
596     // Build a DependentNameType that will perform lookup into RD at
597     // instantiation time.
598     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599                                       RD->getTypeForDecl());
600 
601     // Diagnose that this identifier was undeclared, and retry the lookup during
602     // template instantiation.
603     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
604                                                                       << RD;
605   } else {
606     // This is not a situation that we should recover from.
607     return ParsedType();
608   }
609 
610   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
611 
612   // Build type location information.  We synthesized the qualifier, so we have
613   // to build a fake NestedNameSpecifierLoc.
614   NestedNameSpecifierLocBuilder NNSLocBuilder;
615   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
616   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
617 
618   TypeLocBuilder Builder;
619   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
620   DepTL.setNameLoc(NameLoc);
621   DepTL.setElaboratedKeywordLoc(SourceLocation());
622   DepTL.setQualifierLoc(QualifierLoc);
623   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
624 }
625 
626 /// isTagName() - This method is called *for error recovery purposes only*
627 /// to determine if the specified name is a valid tag name ("struct foo").  If
628 /// so, this returns the TST for the tag corresponding to it (TST_enum,
629 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
630 /// cases in C where the user forgot to specify the tag.
631 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
632   // Do a tag name lookup in this scope.
633   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
634   LookupName(R, S, false);
635   R.suppressDiagnostics();
636   if (R.getResultKind() == LookupResult::Found)
637     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
638       switch (TD->getTagKind()) {
639       case TTK_Struct: return DeclSpec::TST_struct;
640       case TTK_Interface: return DeclSpec::TST_interface;
641       case TTK_Union:  return DeclSpec::TST_union;
642       case TTK_Class:  return DeclSpec::TST_class;
643       case TTK_Enum:   return DeclSpec::TST_enum;
644       }
645     }
646 
647   return DeclSpec::TST_unspecified;
648 }
649 
650 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
651 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
652 /// then downgrade the missing typename error to a warning.
653 /// This is needed for MSVC compatibility; Example:
654 /// @code
655 /// template<class T> class A {
656 /// public:
657 ///   typedef int TYPE;
658 /// };
659 /// template<class T> class B : public A<T> {
660 /// public:
661 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
662 /// };
663 /// @endcode
664 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
665   if (CurContext->isRecord()) {
666     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
667       return true;
668 
669     const Type *Ty = SS->getScopeRep()->getAsType();
670 
671     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672     for (const auto &Base : RD->bases())
673       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674         return true;
675     return S->isFunctionPrototypeScope();
676   }
677   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678 }
679 
680 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
681                                    SourceLocation IILoc,
682                                    Scope *S,
683                                    CXXScopeSpec *SS,
684                                    ParsedType &SuggestedType,
685                                    bool IsTemplateName) {
686   // Don't report typename errors for editor placeholders.
687   if (II->isEditorPlaceholder())
688     return;
689   // We don't have anything to suggest (yet).
690   SuggestedType = nullptr;
691 
692   // There may have been a typo in the name of the type. Look up typo
693   // results, in case we have something that we can suggest.
694   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695                            /*AllowTemplates=*/IsTemplateName,
696                            /*AllowNonTemplates=*/!IsTemplateName);
697   if (TypoCorrection Corrected =
698           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
699                       CCC, CTK_ErrorRecovery)) {
700     // FIXME: Support error recovery for the template-name case.
701     bool CanRecover = !IsTemplateName;
702     if (Corrected.isKeyword()) {
703       // We corrected to a keyword.
704       diagnoseTypo(Corrected,
705                    PDiag(IsTemplateName ? diag::err_no_template_suggest
706                                         : diag::err_unknown_typename_suggest)
707                        << II);
708       II = Corrected.getCorrectionAsIdentifierInfo();
709     } else {
710       // We found a similarly-named type or interface; suggest that.
711       if (!SS || !SS->isSet()) {
712         diagnoseTypo(Corrected,
713                      PDiag(IsTemplateName ? diag::err_no_template_suggest
714                                           : diag::err_unknown_typename_suggest)
715                          << II, CanRecover);
716       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
719                                 II->getName().equals(CorrectedStr);
720         diagnoseTypo(Corrected,
721                      PDiag(IsTemplateName
722                                ? diag::err_no_member_template_suggest
723                                : diag::err_unknown_nested_typename_suggest)
724                          << II << DC << DroppedSpecifier << SS->getRange(),
725                      CanRecover);
726       } else {
727         llvm_unreachable("could not have corrected a typo here");
728       }
729 
730       if (!CanRecover)
731         return;
732 
733       CXXScopeSpec tmpSS;
734       if (Corrected.getCorrectionSpecifier())
735         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736                           SourceRange(IILoc));
737       // FIXME: Support class template argument deduction here.
738       SuggestedType =
739           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741                       /*IsCtorOrDtorName=*/false,
742                       /*WantNontrivialTypeSourceInfo=*/true);
743     }
744     return;
745   }
746 
747   if (getLangOpts().CPlusPlus && !IsTemplateName) {
748     // See if II is a class template that the user forgot to pass arguments to.
749     UnqualifiedId Name;
750     Name.setIdentifier(II, IILoc);
751     CXXScopeSpec EmptySS;
752     TemplateTy TemplateResult;
753     bool MemberOfUnknownSpecialization;
754     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755                        Name, nullptr, true, TemplateResult,
756                        MemberOfUnknownSpecialization) == TNK_Type_template) {
757       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758       return;
759     }
760   }
761 
762   // FIXME: Should we move the logic that tries to recover from a missing tag
763   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764 
765   if (!SS || (!SS->isSet() && !SS->isInvalid()))
766     Diag(IILoc, IsTemplateName ? diag::err_no_template
767                                : diag::err_unknown_typename)
768         << II;
769   else if (DeclContext *DC = computeDeclContext(*SS, false))
770     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771                                : diag::err_typename_nested_not_found)
772         << II << DC << SS->getRange();
773   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774     SuggestedType =
775         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776   } else if (isDependentScopeSpecifier(*SS)) {
777     unsigned DiagID = diag::err_typename_missing;
778     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779       DiagID = diag::ext_typename_missing;
780 
781     Diag(SS->getRange().getBegin(), DiagID)
782       << SS->getScopeRep() << II->getName()
783       << SourceRange(SS->getRange().getBegin(), IILoc)
784       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785     SuggestedType = ActOnTypenameType(S, SourceLocation(),
786                                       *SS, *II, IILoc).get();
787   } else {
788     assert(SS && SS->isInvalid() &&
789            "Invalid scope specifier has already been diagnosed");
790   }
791 }
792 
793 /// Determine whether the given result set contains either a type name
794 /// or
795 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797                        NextToken.is(tok::less);
798 
799   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801       return true;
802 
803     if (CheckTemplate && isa<TemplateDecl>(*I))
804       return true;
805   }
806 
807   return false;
808 }
809 
810 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
811                                     Scope *S, CXXScopeSpec &SS,
812                                     IdentifierInfo *&Name,
813                                     SourceLocation NameLoc) {
814   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815   SemaRef.LookupParsedName(R, S, &SS);
816   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817     StringRef FixItTagName;
818     switch (Tag->getTagKind()) {
819       case TTK_Class:
820         FixItTagName = "class ";
821         break;
822 
823       case TTK_Enum:
824         FixItTagName = "enum ";
825         break;
826 
827       case TTK_Struct:
828         FixItTagName = "struct ";
829         break;
830 
831       case TTK_Interface:
832         FixItTagName = "__interface ";
833         break;
834 
835       case TTK_Union:
836         FixItTagName = "union ";
837         break;
838     }
839 
840     StringRef TagName = FixItTagName.drop_back();
841     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844 
845     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846          I != IEnd; ++I)
847       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848         << Name << TagName;
849 
850     // Replace lookup results with just the tag decl.
851     Result.clear(Sema::LookupTagName);
852     SemaRef.LookupParsedName(Result, S, &SS);
853     return true;
854   }
855 
856   return false;
857 }
858 
859 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
860                                             IdentifierInfo *&Name,
861                                             SourceLocation NameLoc,
862                                             const Token &NextToken,
863                                             CorrectionCandidateCallback *CCC) {
864   DeclarationNameInfo NameInfo(Name, NameLoc);
865   ObjCMethodDecl *CurMethod = getCurMethodDecl();
866 
867   assert(NextToken.isNot(tok::coloncolon) &&
868          "parse nested name specifiers before calling ClassifyName");
869   if (getLangOpts().CPlusPlus && SS.isSet() &&
870       isCurrentClassName(*Name, S, &SS)) {
871     // Per [class.qual]p2, this names the constructors of SS, not the
872     // injected-class-name. We don't have a classification for that.
873     // There's not much point caching this result, since the parser
874     // will reject it later.
875     return NameClassification::Unknown();
876   }
877 
878   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879   LookupParsedName(Result, S, &SS, !CurMethod);
880 
881   if (SS.isInvalid())
882     return NameClassification::Error();
883 
884   // For unqualified lookup in a class template in MSVC mode, look into
885   // dependent base classes where the primary class template is known.
886   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
887     if (ParsedType TypeInBase =
888             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889       return TypeInBase;
890   }
891 
892   // Perform lookup for Objective-C instance variables (including automatically
893   // synthesized instance variables), if we're in an Objective-C method.
894   // FIXME: This lookup really, really needs to be folded in to the normal
895   // unqualified lookup mechanism.
896   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
897     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
898     if (Ivar.isInvalid())
899       return NameClassification::Error();
900     if (Ivar.isUsable())
901       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902 
903     // We defer builtin creation until after ivar lookup inside ObjC methods.
904     if (Result.empty())
905       LookupBuiltin(Result);
906   }
907 
908   bool SecondTry = false;
909   bool IsFilteredTemplateName = false;
910 
911 Corrected:
912   switch (Result.getResultKind()) {
913   case LookupResult::NotFound:
914     // If an unqualified-id is followed by a '(', then we have a function
915     // call.
916     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
917       // In C++, this is an ADL-only call.
918       // FIXME: Reference?
919       if (getLangOpts().CPlusPlus)
920         return NameClassification::UndeclaredNonType();
921 
922       // C90 6.3.2.2:
923       //   If the expression that precedes the parenthesized argument list in a
924       //   function call consists solely of an identifier, and if no
925       //   declaration is visible for this identifier, the identifier is
926       //   implicitly declared exactly as if, in the innermost block containing
927       //   the function call, the declaration
928       //
929       //     extern int identifier ();
930       //
931       //   appeared.
932       //
933       // We also allow this in C99 as an extension.
934       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
935         return NameClassification::NonType(D);
936     }
937 
938     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
939       // In C++20 onwards, this could be an ADL-only call to a function
940       // template, and we're required to assume that this is a template name.
941       //
942       // FIXME: Find a way to still do typo correction in this case.
943       TemplateName Template =
944           Context.getAssumedTemplateName(NameInfo.getName());
945       return NameClassification::UndeclaredTemplate(Template);
946     }
947 
948     // In C, we first see whether there is a tag type by the same name, in
949     // which case it's likely that the user just forgot to write "enum",
950     // "struct", or "union".
951     if (!getLangOpts().CPlusPlus && !SecondTry &&
952         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
953       break;
954     }
955 
956     // Perform typo correction to determine if there is another name that is
957     // close to this name.
958     if (!SecondTry && CCC) {
959       SecondTry = true;
960       if (TypoCorrection Corrected =
961               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
962                           &SS, *CCC, CTK_ErrorRecovery)) {
963         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
964         unsigned QualifiedDiag = diag::err_no_member_suggest;
965 
966         NamedDecl *FirstDecl = Corrected.getFoundDecl();
967         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
968         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
969             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
970           UnqualifiedDiag = diag::err_no_template_suggest;
971           QualifiedDiag = diag::err_no_member_template_suggest;
972         } else if (UnderlyingFirstDecl &&
973                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
974                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
975                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
976           UnqualifiedDiag = diag::err_unknown_typename_suggest;
977           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
978         }
979 
980         if (SS.isEmpty()) {
981           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
982         } else {// FIXME: is this even reachable? Test it.
983           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
984           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
985                                   Name->getName().equals(CorrectedStr);
986           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
987                                     << Name << computeDeclContext(SS, false)
988                                     << DroppedSpecifier << SS.getRange());
989         }
990 
991         // Update the name, so that the caller has the new name.
992         Name = Corrected.getCorrectionAsIdentifierInfo();
993 
994         // Typo correction corrected to a keyword.
995         if (Corrected.isKeyword())
996           return Name;
997 
998         // Also update the LookupResult...
999         // FIXME: This should probably go away at some point
1000         Result.clear();
1001         Result.setLookupName(Corrected.getCorrection());
1002         if (FirstDecl)
1003           Result.addDecl(FirstDecl);
1004 
1005         // If we found an Objective-C instance variable, let
1006         // LookupInObjCMethod build the appropriate expression to
1007         // reference the ivar.
1008         // FIXME: This is a gross hack.
1009         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1010           DeclResult R =
1011               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1012           if (R.isInvalid())
1013             return NameClassification::Error();
1014           if (R.isUsable())
1015             return NameClassification::NonType(Ivar);
1016         }
1017 
1018         goto Corrected;
1019       }
1020     }
1021 
1022     // We failed to correct; just fall through and let the parser deal with it.
1023     Result.suppressDiagnostics();
1024     return NameClassification::Unknown();
1025 
1026   case LookupResult::NotFoundInCurrentInstantiation: {
1027     // We performed name lookup into the current instantiation, and there were
1028     // dependent bases, so we treat this result the same way as any other
1029     // dependent nested-name-specifier.
1030 
1031     // C++ [temp.res]p2:
1032     //   A name used in a template declaration or definition and that is
1033     //   dependent on a template-parameter is assumed not to name a type
1034     //   unless the applicable name lookup finds a type name or the name is
1035     //   qualified by the keyword typename.
1036     //
1037     // FIXME: If the next token is '<', we might want to ask the parser to
1038     // perform some heroics to see if we actually have a
1039     // template-argument-list, which would indicate a missing 'template'
1040     // keyword here.
1041     return NameClassification::DependentNonType();
1042   }
1043 
1044   case LookupResult::Found:
1045   case LookupResult::FoundOverloaded:
1046   case LookupResult::FoundUnresolvedValue:
1047     break;
1048 
1049   case LookupResult::Ambiguous:
1050     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1051         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1052                                       /*AllowDependent=*/false)) {
1053       // C++ [temp.local]p3:
1054       //   A lookup that finds an injected-class-name (10.2) can result in an
1055       //   ambiguity in certain cases (for example, if it is found in more than
1056       //   one base class). If all of the injected-class-names that are found
1057       //   refer to specializations of the same class template, and if the name
1058       //   is followed by a template-argument-list, the reference refers to the
1059       //   class template itself and not a specialization thereof, and is not
1060       //   ambiguous.
1061       //
1062       // This filtering can make an ambiguous result into an unambiguous one,
1063       // so try again after filtering out template names.
1064       FilterAcceptableTemplateNames(Result);
1065       if (!Result.isAmbiguous()) {
1066         IsFilteredTemplateName = true;
1067         break;
1068       }
1069     }
1070 
1071     // Diagnose the ambiguity and return an error.
1072     return NameClassification::Error();
1073   }
1074 
1075   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1076       (IsFilteredTemplateName ||
1077        hasAnyAcceptableTemplateNames(
1078            Result, /*AllowFunctionTemplates=*/true,
1079            /*AllowDependent=*/false,
1080            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1081                getLangOpts().CPlusPlus20))) {
1082     // C++ [temp.names]p3:
1083     //   After name lookup (3.4) finds that a name is a template-name or that
1084     //   an operator-function-id or a literal- operator-id refers to a set of
1085     //   overloaded functions any member of which is a function template if
1086     //   this is followed by a <, the < is always taken as the delimiter of a
1087     //   template-argument-list and never as the less-than operator.
1088     // C++2a [temp.names]p2:
1089     //   A name is also considered to refer to a template if it is an
1090     //   unqualified-id followed by a < and name lookup finds either one
1091     //   or more functions or finds nothing.
1092     if (!IsFilteredTemplateName)
1093       FilterAcceptableTemplateNames(Result);
1094 
1095     bool IsFunctionTemplate;
1096     bool IsVarTemplate;
1097     TemplateName Template;
1098     if (Result.end() - Result.begin() > 1) {
1099       IsFunctionTemplate = true;
1100       Template = Context.getOverloadedTemplateName(Result.begin(),
1101                                                    Result.end());
1102     } else if (!Result.empty()) {
1103       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1104           *Result.begin(), /*AllowFunctionTemplates=*/true,
1105           /*AllowDependent=*/false));
1106       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1107       IsVarTemplate = isa<VarTemplateDecl>(TD);
1108 
1109       if (SS.isNotEmpty())
1110         Template =
1111             Context.getQualifiedTemplateName(SS.getScopeRep(),
1112                                              /*TemplateKeyword=*/false, TD);
1113       else
1114         Template = TemplateName(TD);
1115     } else {
1116       // All results were non-template functions. This is a function template
1117       // name.
1118       IsFunctionTemplate = true;
1119       Template = Context.getAssumedTemplateName(NameInfo.getName());
1120     }
1121 
1122     if (IsFunctionTemplate) {
1123       // Function templates always go through overload resolution, at which
1124       // point we'll perform the various checks (e.g., accessibility) we need
1125       // to based on which function we selected.
1126       Result.suppressDiagnostics();
1127 
1128       return NameClassification::FunctionTemplate(Template);
1129     }
1130 
1131     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1132                          : NameClassification::TypeTemplate(Template);
1133   }
1134 
1135   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1136     QualType T = Context.getTypeDeclType(Type);
1137     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1138       T = Context.getUsingType(USD, T);
1139 
1140     if (SS.isEmpty()) // No elaborated type, trivial location info
1141       return ParsedType::make(T);
1142 
1143     TypeLocBuilder Builder;
1144     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1145     T = getElaboratedType(ETK_None, SS, T);
1146     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1147     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1148     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1149     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1150   };
1151 
1152   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154     DiagnoseUseOfDecl(Type, NameLoc);
1155     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156     return BuildTypeFor(Type, *Result.begin());
1157   }
1158 
1159   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160   if (!Class) {
1161     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162     if (ObjCCompatibleAliasDecl *Alias =
1163             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164       Class = Alias->getClassInterface();
1165   }
1166 
1167   if (Class) {
1168     DiagnoseUseOfDecl(Class, NameLoc);
1169 
1170     if (NextToken.is(tok::period)) {
1171       // Interface. <something> is parsed as a property reference expression.
1172       // Just return "unknown" as a fall-through for now.
1173       Result.suppressDiagnostics();
1174       return NameClassification::Unknown();
1175     }
1176 
1177     QualType T = Context.getObjCInterfaceType(Class);
1178     return ParsedType::make(T);
1179   }
1180 
1181   if (isa<ConceptDecl>(FirstDecl))
1182     return NameClassification::Concept(
1183         TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 
1185   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1187     return NameClassification::Error();
1188   }
1189 
1190   // We can have a type template here if we're classifying a template argument.
1191   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192       !isa<VarTemplateDecl>(FirstDecl))
1193     return NameClassification::TypeTemplate(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   // Check for a tag type hidden by a non-type decl in a few cases where it
1197   // seems likely a type is wanted instead of the non-type that was found.
1198   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199   if ((NextToken.is(tok::identifier) ||
1200        (NextIsOp &&
1201         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1202       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1203     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204     DiagnoseUseOfDecl(Type, NameLoc);
1205     return BuildTypeFor(Type, *Result.begin());
1206   }
1207 
1208   // If we already know which single declaration is referenced, just annotate
1209   // that declaration directly. Defer resolving even non-overloaded class
1210   // member accesses, as we need to defer certain access checks until we know
1211   // the context.
1212   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1214     return NameClassification::NonType(Result.getRepresentativeDecl());
1215 
1216   // Otherwise, this is an overload set that we will need to resolve later.
1217   Result.suppressDiagnostics();
1218   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1219       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1220       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1221       Result.begin(), Result.end()));
1222 }
1223 
1224 ExprResult
1225 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1226                                              SourceLocation NameLoc) {
1227   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1228   CXXScopeSpec SS;
1229   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1230   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1231 }
1232 
1233 ExprResult
1234 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1235                                             IdentifierInfo *Name,
1236                                             SourceLocation NameLoc,
1237                                             bool IsAddressOfOperand) {
1238   DeclarationNameInfo NameInfo(Name, NameLoc);
1239   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1240                                     NameInfo, IsAddressOfOperand,
1241                                     /*TemplateArgs=*/nullptr);
1242 }
1243 
1244 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1245                                               NamedDecl *Found,
1246                                               SourceLocation NameLoc,
1247                                               const Token &NextToken) {
1248   if (getCurMethodDecl() && SS.isEmpty())
1249     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1250       return BuildIvarRefExpr(S, NameLoc, Ivar);
1251 
1252   // Reconstruct the lookup result.
1253   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1254   Result.addDecl(Found);
1255   Result.resolveKind();
1256 
1257   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1258   return BuildDeclarationNameExpr(SS, Result, ADL);
1259 }
1260 
1261 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1262   // For an implicit class member access, transform the result into a member
1263   // access expression if necessary.
1264   auto *ULE = cast<UnresolvedLookupExpr>(E);
1265   if ((*ULE->decls_begin())->isCXXClassMember()) {
1266     CXXScopeSpec SS;
1267     SS.Adopt(ULE->getQualifierLoc());
1268 
1269     // Reconstruct the lookup result.
1270     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1271                         LookupOrdinaryName);
1272     Result.setNamingClass(ULE->getNamingClass());
1273     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1274       Result.addDecl(*I, I.getAccess());
1275     Result.resolveKind();
1276     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1277                                            nullptr, S);
1278   }
1279 
1280   // Otherwise, this is already in the form we needed, and no further checks
1281   // are necessary.
1282   return ULE;
1283 }
1284 
1285 Sema::TemplateNameKindForDiagnostics
1286 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1287   auto *TD = Name.getAsTemplateDecl();
1288   if (!TD)
1289     return TemplateNameKindForDiagnostics::DependentTemplate;
1290   if (isa<ClassTemplateDecl>(TD))
1291     return TemplateNameKindForDiagnostics::ClassTemplate;
1292   if (isa<FunctionTemplateDecl>(TD))
1293     return TemplateNameKindForDiagnostics::FunctionTemplate;
1294   if (isa<VarTemplateDecl>(TD))
1295     return TemplateNameKindForDiagnostics::VarTemplate;
1296   if (isa<TypeAliasTemplateDecl>(TD))
1297     return TemplateNameKindForDiagnostics::AliasTemplate;
1298   if (isa<TemplateTemplateParmDecl>(TD))
1299     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1300   if (isa<ConceptDecl>(TD))
1301     return TemplateNameKindForDiagnostics::Concept;
1302   return TemplateNameKindForDiagnostics::DependentTemplate;
1303 }
1304 
1305 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1306   assert(DC->getLexicalParent() == CurContext &&
1307       "The next DeclContext should be lexically contained in the current one.");
1308   CurContext = DC;
1309   S->setEntity(DC);
1310 }
1311 
1312 void Sema::PopDeclContext() {
1313   assert(CurContext && "DeclContext imbalance!");
1314 
1315   CurContext = CurContext->getLexicalParent();
1316   assert(CurContext && "Popped translation unit!");
1317 }
1318 
1319 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1320                                                                     Decl *D) {
1321   // Unlike PushDeclContext, the context to which we return is not necessarily
1322   // the containing DC of TD, because the new context will be some pre-existing
1323   // TagDecl definition instead of a fresh one.
1324   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1325   CurContext = cast<TagDecl>(D)->getDefinition();
1326   assert(CurContext && "skipping definition of undefined tag");
1327   // Start lookups from the parent of the current context; we don't want to look
1328   // into the pre-existing complete definition.
1329   S->setEntity(CurContext->getLookupParent());
1330   return Result;
1331 }
1332 
1333 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1334   CurContext = static_cast<decltype(CurContext)>(Context);
1335 }
1336 
1337 /// EnterDeclaratorContext - Used when we must lookup names in the context
1338 /// of a declarator's nested name specifier.
1339 ///
1340 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1341   // C++0x [basic.lookup.unqual]p13:
1342   //   A name used in the definition of a static data member of class
1343   //   X (after the qualified-id of the static member) is looked up as
1344   //   if the name was used in a member function of X.
1345   // C++0x [basic.lookup.unqual]p14:
1346   //   If a variable member of a namespace is defined outside of the
1347   //   scope of its namespace then any name used in the definition of
1348   //   the variable member (after the declarator-id) is looked up as
1349   //   if the definition of the variable member occurred in its
1350   //   namespace.
1351   // Both of these imply that we should push a scope whose context
1352   // is the semantic context of the declaration.  We can't use
1353   // PushDeclContext here because that context is not necessarily
1354   // lexically contained in the current context.  Fortunately,
1355   // the containing scope should have the appropriate information.
1356 
1357   assert(!S->getEntity() && "scope already has entity");
1358 
1359 #ifndef NDEBUG
1360   Scope *Ancestor = S->getParent();
1361   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1362   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1363 #endif
1364 
1365   CurContext = DC;
1366   S->setEntity(DC);
1367 
1368   if (S->getParent()->isTemplateParamScope()) {
1369     // Also set the corresponding entities for all immediately-enclosing
1370     // template parameter scopes.
1371     EnterTemplatedContext(S->getParent(), DC);
1372   }
1373 }
1374 
1375 void Sema::ExitDeclaratorContext(Scope *S) {
1376   assert(S->getEntity() == CurContext && "Context imbalance!");
1377 
1378   // Switch back to the lexical context.  The safety of this is
1379   // enforced by an assert in EnterDeclaratorContext.
1380   Scope *Ancestor = S->getParent();
1381   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1382   CurContext = Ancestor->getEntity();
1383 
1384   // We don't need to do anything with the scope, which is going to
1385   // disappear.
1386 }
1387 
1388 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1389   assert(S->isTemplateParamScope() &&
1390          "expected to be initializing a template parameter scope");
1391 
1392   // C++20 [temp.local]p7:
1393   //   In the definition of a member of a class template that appears outside
1394   //   of the class template definition, the name of a member of the class
1395   //   template hides the name of a template-parameter of any enclosing class
1396   //   templates (but not a template-parameter of the member if the member is a
1397   //   class or function template).
1398   // C++20 [temp.local]p9:
1399   //   In the definition of a class template or in the definition of a member
1400   //   of such a template that appears outside of the template definition, for
1401   //   each non-dependent base class (13.8.2.1), if the name of the base class
1402   //   or the name of a member of the base class is the same as the name of a
1403   //   template-parameter, the base class name or member name hides the
1404   //   template-parameter name (6.4.10).
1405   //
1406   // This means that a template parameter scope should be searched immediately
1407   // after searching the DeclContext for which it is a template parameter
1408   // scope. For example, for
1409   //   template<typename T> template<typename U> template<typename V>
1410   //     void N::A<T>::B<U>::f(...)
1411   // we search V then B<U> (and base classes) then U then A<T> (and base
1412   // classes) then T then N then ::.
1413   unsigned ScopeDepth = getTemplateDepth(S);
1414   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1415     DeclContext *SearchDCAfterScope = DC;
1416     for (; DC; DC = DC->getLookupParent()) {
1417       if (const TemplateParameterList *TPL =
1418               cast<Decl>(DC)->getDescribedTemplateParams()) {
1419         unsigned DCDepth = TPL->getDepth() + 1;
1420         if (DCDepth > ScopeDepth)
1421           continue;
1422         if (ScopeDepth == DCDepth)
1423           SearchDCAfterScope = DC = DC->getLookupParent();
1424         break;
1425       }
1426     }
1427     S->setLookupEntity(SearchDCAfterScope);
1428   }
1429 }
1430 
1431 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1432   // We assume that the caller has already called
1433   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1434   FunctionDecl *FD = D->getAsFunction();
1435   if (!FD)
1436     return;
1437 
1438   // Same implementation as PushDeclContext, but enters the context
1439   // from the lexical parent, rather than the top-level class.
1440   assert(CurContext == FD->getLexicalParent() &&
1441     "The next DeclContext should be lexically contained in the current one.");
1442   CurContext = FD;
1443   S->setEntity(CurContext);
1444 
1445   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1446     ParmVarDecl *Param = FD->getParamDecl(P);
1447     // If the parameter has an identifier, then add it to the scope
1448     if (Param->getIdentifier()) {
1449       S->AddDecl(Param);
1450       IdResolver.AddDecl(Param);
1451     }
1452   }
1453 }
1454 
1455 void Sema::ActOnExitFunctionContext() {
1456   // Same implementation as PopDeclContext, but returns to the lexical parent,
1457   // rather than the top-level class.
1458   assert(CurContext && "DeclContext imbalance!");
1459   CurContext = CurContext->getLexicalParent();
1460   assert(CurContext && "Popped translation unit!");
1461 }
1462 
1463 /// Determine whether we allow overloading of the function
1464 /// PrevDecl with another declaration.
1465 ///
1466 /// This routine determines whether overloading is possible, not
1467 /// whether some new function is actually an overload. It will return
1468 /// true in C++ (where we can always provide overloads) or, as an
1469 /// extension, in C when the previous function is already an
1470 /// overloaded function declaration or has the "overloadable"
1471 /// attribute.
1472 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1473                                        ASTContext &Context,
1474                                        const FunctionDecl *New) {
1475   if (Context.getLangOpts().CPlusPlus)
1476     return true;
1477 
1478   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1479     return true;
1480 
1481   return Previous.getResultKind() == LookupResult::Found &&
1482          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1483           New->hasAttr<OverloadableAttr>());
1484 }
1485 
1486 /// Add this decl to the scope shadowed decl chains.
1487 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1488   // Move up the scope chain until we find the nearest enclosing
1489   // non-transparent context. The declaration will be introduced into this
1490   // scope.
1491   while (S->getEntity() && S->getEntity()->isTransparentContext())
1492     S = S->getParent();
1493 
1494   // Add scoped declarations into their context, so that they can be
1495   // found later. Declarations without a context won't be inserted
1496   // into any context.
1497   if (AddToContext)
1498     CurContext->addDecl(D);
1499 
1500   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1501   // are function-local declarations.
1502   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1503     return;
1504 
1505   // Template instantiations should also not be pushed into scope.
1506   if (isa<FunctionDecl>(D) &&
1507       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1508     return;
1509 
1510   // If this replaces anything in the current scope,
1511   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1512                                IEnd = IdResolver.end();
1513   for (; I != IEnd; ++I) {
1514     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1515       S->RemoveDecl(*I);
1516       IdResolver.RemoveDecl(*I);
1517 
1518       // Should only need to replace one decl.
1519       break;
1520     }
1521   }
1522 
1523   S->AddDecl(D);
1524 
1525   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1526     // Implicitly-generated labels may end up getting generated in an order that
1527     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1528     // the label at the appropriate place in the identifier chain.
1529     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1530       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1531       if (IDC == CurContext) {
1532         if (!S->isDeclScope(*I))
1533           continue;
1534       } else if (IDC->Encloses(CurContext))
1535         break;
1536     }
1537 
1538     IdResolver.InsertDeclAfter(I, D);
1539   } else {
1540     IdResolver.AddDecl(D);
1541   }
1542   warnOnReservedIdentifier(D);
1543 }
1544 
1545 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1546                          bool AllowInlineNamespace) {
1547   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1548 }
1549 
1550 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1551   DeclContext *TargetDC = DC->getPrimaryContext();
1552   do {
1553     if (DeclContext *ScopeDC = S->getEntity())
1554       if (ScopeDC->getPrimaryContext() == TargetDC)
1555         return S;
1556   } while ((S = S->getParent()));
1557 
1558   return nullptr;
1559 }
1560 
1561 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1562                                             DeclContext*,
1563                                             ASTContext&);
1564 
1565 /// Filters out lookup results that don't fall within the given scope
1566 /// as determined by isDeclInScope.
1567 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1568                                 bool ConsiderLinkage,
1569                                 bool AllowInlineNamespace) {
1570   LookupResult::Filter F = R.makeFilter();
1571   while (F.hasNext()) {
1572     NamedDecl *D = F.next();
1573 
1574     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1575       continue;
1576 
1577     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1578       continue;
1579 
1580     F.erase();
1581   }
1582 
1583   F.done();
1584 }
1585 
1586 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1587 /// have compatible owning modules.
1588 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1589   // FIXME: The Modules TS is not clear about how friend declarations are
1590   // to be treated. It's not meaningful to have different owning modules for
1591   // linkage in redeclarations of the same entity, so for now allow the
1592   // redeclaration and change the owning modules to match.
1593   if (New->getFriendObjectKind() &&
1594       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1595     New->setLocalOwningModule(Old->getOwningModule());
1596     makeMergedDefinitionVisible(New);
1597     return false;
1598   }
1599 
1600   Module *NewM = New->getOwningModule();
1601   Module *OldM = Old->getOwningModule();
1602 
1603   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1604     NewM = NewM->Parent;
1605   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1606     OldM = OldM->Parent;
1607 
1608   if (NewM == OldM)
1609     return false;
1610 
1611   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1612   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1613   if (NewIsModuleInterface || OldIsModuleInterface) {
1614     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1615     //   if a declaration of D [...] appears in the purview of a module, all
1616     //   other such declarations shall appear in the purview of the same module
1617     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1618       << New
1619       << NewIsModuleInterface
1620       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1621       << OldIsModuleInterface
1622       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1623     Diag(Old->getLocation(), diag::note_previous_declaration);
1624     New->setInvalidDecl();
1625     return true;
1626   }
1627 
1628   return false;
1629 }
1630 
1631 static bool isUsingDecl(NamedDecl *D) {
1632   return isa<UsingShadowDecl>(D) ||
1633          isa<UnresolvedUsingTypenameDecl>(D) ||
1634          isa<UnresolvedUsingValueDecl>(D);
1635 }
1636 
1637 /// Removes using shadow declarations from the lookup results.
1638 static void RemoveUsingDecls(LookupResult &R) {
1639   LookupResult::Filter F = R.makeFilter();
1640   while (F.hasNext())
1641     if (isUsingDecl(F.next()))
1642       F.erase();
1643 
1644   F.done();
1645 }
1646 
1647 /// Check for this common pattern:
1648 /// @code
1649 /// class S {
1650 ///   S(const S&); // DO NOT IMPLEMENT
1651 ///   void operator=(const S&); // DO NOT IMPLEMENT
1652 /// };
1653 /// @endcode
1654 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1655   // FIXME: Should check for private access too but access is set after we get
1656   // the decl here.
1657   if (D->doesThisDeclarationHaveABody())
1658     return false;
1659 
1660   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1661     return CD->isCopyConstructor();
1662   return D->isCopyAssignmentOperator();
1663 }
1664 
1665 // We need this to handle
1666 //
1667 // typedef struct {
1668 //   void *foo() { return 0; }
1669 // } A;
1670 //
1671 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1672 // for example. If 'A', foo will have external linkage. If we have '*A',
1673 // foo will have no linkage. Since we can't know until we get to the end
1674 // of the typedef, this function finds out if D might have non-external linkage.
1675 // Callers should verify at the end of the TU if it D has external linkage or
1676 // not.
1677 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1678   const DeclContext *DC = D->getDeclContext();
1679   while (!DC->isTranslationUnit()) {
1680     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1681       if (!RD->hasNameForLinkage())
1682         return true;
1683     }
1684     DC = DC->getParent();
1685   }
1686 
1687   return !D->isExternallyVisible();
1688 }
1689 
1690 // FIXME: This needs to be refactored; some other isInMainFile users want
1691 // these semantics.
1692 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1693   if (S.TUKind != TU_Complete)
1694     return false;
1695   return S.SourceMgr.isInMainFile(Loc);
1696 }
1697 
1698 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1699   assert(D);
1700 
1701   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1702     return false;
1703 
1704   // Ignore all entities declared within templates, and out-of-line definitions
1705   // of members of class templates.
1706   if (D->getDeclContext()->isDependentContext() ||
1707       D->getLexicalDeclContext()->isDependentContext())
1708     return false;
1709 
1710   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1711     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1712       return false;
1713     // A non-out-of-line declaration of a member specialization was implicitly
1714     // instantiated; it's the out-of-line declaration that we're interested in.
1715     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1716         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1717       return false;
1718 
1719     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1720       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1721         return false;
1722     } else {
1723       // 'static inline' functions are defined in headers; don't warn.
1724       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1725         return false;
1726     }
1727 
1728     if (FD->doesThisDeclarationHaveABody() &&
1729         Context.DeclMustBeEmitted(FD))
1730       return false;
1731   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1732     // Constants and utility variables are defined in headers with internal
1733     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1734     // like "inline".)
1735     if (!isMainFileLoc(*this, VD->getLocation()))
1736       return false;
1737 
1738     if (Context.DeclMustBeEmitted(VD))
1739       return false;
1740 
1741     if (VD->isStaticDataMember() &&
1742         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1743       return false;
1744     if (VD->isStaticDataMember() &&
1745         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1746         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1747       return false;
1748 
1749     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1750       return false;
1751   } else {
1752     return false;
1753   }
1754 
1755   // Only warn for unused decls internal to the translation unit.
1756   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1757   // for inline functions defined in the main source file, for instance.
1758   return mightHaveNonExternalLinkage(D);
1759 }
1760 
1761 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1762   if (!D)
1763     return;
1764 
1765   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1766     const FunctionDecl *First = FD->getFirstDecl();
1767     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1768       return; // First should already be in the vector.
1769   }
1770 
1771   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1772     const VarDecl *First = VD->getFirstDecl();
1773     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1774       return; // First should already be in the vector.
1775   }
1776 
1777   if (ShouldWarnIfUnusedFileScopedDecl(D))
1778     UnusedFileScopedDecls.push_back(D);
1779 }
1780 
1781 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1782   if (D->isInvalidDecl())
1783     return false;
1784 
1785   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1786     // For a decomposition declaration, warn if none of the bindings are
1787     // referenced, instead of if the variable itself is referenced (which
1788     // it is, by the bindings' expressions).
1789     for (auto *BD : DD->bindings())
1790       if (BD->isReferenced())
1791         return false;
1792   } else if (!D->getDeclName()) {
1793     return false;
1794   } else if (D->isReferenced() || D->isUsed()) {
1795     return false;
1796   }
1797 
1798   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1799     return false;
1800 
1801   if (isa<LabelDecl>(D))
1802     return true;
1803 
1804   // Except for labels, we only care about unused decls that are local to
1805   // functions.
1806   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1807   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1808     // For dependent types, the diagnostic is deferred.
1809     WithinFunction =
1810         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1811   if (!WithinFunction)
1812     return false;
1813 
1814   if (isa<TypedefNameDecl>(D))
1815     return true;
1816 
1817   // White-list anything that isn't a local variable.
1818   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1819     return false;
1820 
1821   // Types of valid local variables should be complete, so this should succeed.
1822   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1823 
1824     // White-list anything with an __attribute__((unused)) type.
1825     const auto *Ty = VD->getType().getTypePtr();
1826 
1827     // Only look at the outermost level of typedef.
1828     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1829       if (TT->getDecl()->hasAttr<UnusedAttr>())
1830         return false;
1831     }
1832 
1833     // If we failed to complete the type for some reason, or if the type is
1834     // dependent, don't diagnose the variable.
1835     if (Ty->isIncompleteType() || Ty->isDependentType())
1836       return false;
1837 
1838     // Look at the element type to ensure that the warning behaviour is
1839     // consistent for both scalars and arrays.
1840     Ty = Ty->getBaseElementTypeUnsafe();
1841 
1842     if (const TagType *TT = Ty->getAs<TagType>()) {
1843       const TagDecl *Tag = TT->getDecl();
1844       if (Tag->hasAttr<UnusedAttr>())
1845         return false;
1846 
1847       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1848         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1849           return false;
1850 
1851         if (const Expr *Init = VD->getInit()) {
1852           if (const ExprWithCleanups *Cleanups =
1853                   dyn_cast<ExprWithCleanups>(Init))
1854             Init = Cleanups->getSubExpr();
1855           const CXXConstructExpr *Construct =
1856             dyn_cast<CXXConstructExpr>(Init);
1857           if (Construct && !Construct->isElidable()) {
1858             CXXConstructorDecl *CD = Construct->getConstructor();
1859             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1860                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1861               return false;
1862           }
1863 
1864           // Suppress the warning if we don't know how this is constructed, and
1865           // it could possibly be non-trivial constructor.
1866           if (Init->isTypeDependent())
1867             for (const CXXConstructorDecl *Ctor : RD->ctors())
1868               if (!Ctor->isTrivial())
1869                 return false;
1870         }
1871       }
1872     }
1873 
1874     // TODO: __attribute__((unused)) templates?
1875   }
1876 
1877   return true;
1878 }
1879 
1880 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1881                                      FixItHint &Hint) {
1882   if (isa<LabelDecl>(D)) {
1883     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1884         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1885         true);
1886     if (AfterColon.isInvalid())
1887       return;
1888     Hint = FixItHint::CreateRemoval(
1889         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1890   }
1891 }
1892 
1893 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1894   if (D->getTypeForDecl()->isDependentType())
1895     return;
1896 
1897   for (auto *TmpD : D->decls()) {
1898     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1899       DiagnoseUnusedDecl(T);
1900     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1901       DiagnoseUnusedNestedTypedefs(R);
1902   }
1903 }
1904 
1905 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1906 /// unless they are marked attr(unused).
1907 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1908   if (!ShouldDiagnoseUnusedDecl(D))
1909     return;
1910 
1911   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1912     // typedefs can be referenced later on, so the diagnostics are emitted
1913     // at end-of-translation-unit.
1914     UnusedLocalTypedefNameCandidates.insert(TD);
1915     return;
1916   }
1917 
1918   FixItHint Hint;
1919   GenerateFixForUnusedDecl(D, Context, Hint);
1920 
1921   unsigned DiagID;
1922   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1923     DiagID = diag::warn_unused_exception_param;
1924   else if (isa<LabelDecl>(D))
1925     DiagID = diag::warn_unused_label;
1926   else
1927     DiagID = diag::warn_unused_variable;
1928 
1929   Diag(D->getLocation(), DiagID) << D << Hint;
1930 }
1931 
1932 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1933   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
1934   // it's not really unused.
1935   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
1936       VD->hasAttr<CleanupAttr>())
1937     return;
1938 
1939   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1940 
1941   if (Ty->isReferenceType() || Ty->isDependentType())
1942     return;
1943 
1944   if (const TagType *TT = Ty->getAs<TagType>()) {
1945     const TagDecl *Tag = TT->getDecl();
1946     if (Tag->hasAttr<UnusedAttr>())
1947       return;
1948     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1949     // mimic gcc's behavior.
1950     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1951       if (!RD->hasAttr<WarnUnusedAttr>())
1952         return;
1953     }
1954   }
1955 
1956   // Don't warn about __block Objective-C pointer variables, as they might
1957   // be assigned in the block but not used elsewhere for the purpose of lifetime
1958   // extension.
1959   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
1960     return;
1961 
1962   auto iter = RefsMinusAssignments.find(VD);
1963   if (iter == RefsMinusAssignments.end())
1964     return;
1965 
1966   assert(iter->getSecond() >= 0 &&
1967          "Found a negative number of references to a VarDecl");
1968   if (iter->getSecond() != 0)
1969     return;
1970   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1971                                          : diag::warn_unused_but_set_variable;
1972   Diag(VD->getLocation(), DiagID) << VD;
1973 }
1974 
1975 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1976   // Verify that we have no forward references left.  If so, there was a goto
1977   // or address of a label taken, but no definition of it.  Label fwd
1978   // definitions are indicated with a null substmt which is also not a resolved
1979   // MS inline assembly label name.
1980   bool Diagnose = false;
1981   if (L->isMSAsmLabel())
1982     Diagnose = !L->isResolvedMSAsmLabel();
1983   else
1984     Diagnose = L->getStmt() == nullptr;
1985   if (Diagnose)
1986     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1987 }
1988 
1989 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1990   S->mergeNRVOIntoParent();
1991 
1992   if (S->decl_empty()) return;
1993   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1994          "Scope shouldn't contain decls!");
1995 
1996   for (auto *TmpD : S->decls()) {
1997     assert(TmpD && "This decl didn't get pushed??");
1998 
1999     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2000     NamedDecl *D = cast<NamedDecl>(TmpD);
2001 
2002     // Diagnose unused variables in this scope.
2003     if (!S->hasUnrecoverableErrorOccurred()) {
2004       DiagnoseUnusedDecl(D);
2005       if (const auto *RD = dyn_cast<RecordDecl>(D))
2006         DiagnoseUnusedNestedTypedefs(RD);
2007       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2008         DiagnoseUnusedButSetDecl(VD);
2009         RefsMinusAssignments.erase(VD);
2010       }
2011     }
2012 
2013     if (!D->getDeclName()) continue;
2014 
2015     // If this was a forward reference to a label, verify it was defined.
2016     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2017       CheckPoppedLabel(LD, *this);
2018 
2019     // Remove this name from our lexical scope, and warn on it if we haven't
2020     // already.
2021     IdResolver.RemoveDecl(D);
2022     auto ShadowI = ShadowingDecls.find(D);
2023     if (ShadowI != ShadowingDecls.end()) {
2024       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2025         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2026             << D << FD << FD->getParent();
2027         Diag(FD->getLocation(), diag::note_previous_declaration);
2028       }
2029       ShadowingDecls.erase(ShadowI);
2030     }
2031   }
2032 }
2033 
2034 /// Look for an Objective-C class in the translation unit.
2035 ///
2036 /// \param Id The name of the Objective-C class we're looking for. If
2037 /// typo-correction fixes this name, the Id will be updated
2038 /// to the fixed name.
2039 ///
2040 /// \param IdLoc The location of the name in the translation unit.
2041 ///
2042 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2043 /// if there is no class with the given name.
2044 ///
2045 /// \returns The declaration of the named Objective-C class, or NULL if the
2046 /// class could not be found.
2047 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2048                                               SourceLocation IdLoc,
2049                                               bool DoTypoCorrection) {
2050   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2051   // creation from this context.
2052   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2053 
2054   if (!IDecl && DoTypoCorrection) {
2055     // Perform typo correction at the given location, but only if we
2056     // find an Objective-C class name.
2057     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2058     if (TypoCorrection C =
2059             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2060                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2061       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2062       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2063       Id = IDecl->getIdentifier();
2064     }
2065   }
2066   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2067   // This routine must always return a class definition, if any.
2068   if (Def && Def->getDefinition())
2069       Def = Def->getDefinition();
2070   return Def;
2071 }
2072 
2073 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2074 /// from S, where a non-field would be declared. This routine copes
2075 /// with the difference between C and C++ scoping rules in structs and
2076 /// unions. For example, the following code is well-formed in C but
2077 /// ill-formed in C++:
2078 /// @code
2079 /// struct S6 {
2080 ///   enum { BAR } e;
2081 /// };
2082 ///
2083 /// void test_S6() {
2084 ///   struct S6 a;
2085 ///   a.e = BAR;
2086 /// }
2087 /// @endcode
2088 /// For the declaration of BAR, this routine will return a different
2089 /// scope. The scope S will be the scope of the unnamed enumeration
2090 /// within S6. In C++, this routine will return the scope associated
2091 /// with S6, because the enumeration's scope is a transparent
2092 /// context but structures can contain non-field names. In C, this
2093 /// routine will return the translation unit scope, since the
2094 /// enumeration's scope is a transparent context and structures cannot
2095 /// contain non-field names.
2096 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2097   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2098          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2099          (S->isClassScope() && !getLangOpts().CPlusPlus))
2100     S = S->getParent();
2101   return S;
2102 }
2103 
2104 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2105                                ASTContext::GetBuiltinTypeError Error) {
2106   switch (Error) {
2107   case ASTContext::GE_None:
2108     return "";
2109   case ASTContext::GE_Missing_type:
2110     return BuiltinInfo.getHeaderName(ID);
2111   case ASTContext::GE_Missing_stdio:
2112     return "stdio.h";
2113   case ASTContext::GE_Missing_setjmp:
2114     return "setjmp.h";
2115   case ASTContext::GE_Missing_ucontext:
2116     return "ucontext.h";
2117   }
2118   llvm_unreachable("unhandled error kind");
2119 }
2120 
2121 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2122                                   unsigned ID, SourceLocation Loc) {
2123   DeclContext *Parent = Context.getTranslationUnitDecl();
2124 
2125   if (getLangOpts().CPlusPlus) {
2126     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2127         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2128     CLinkageDecl->setImplicit();
2129     Parent->addDecl(CLinkageDecl);
2130     Parent = CLinkageDecl;
2131   }
2132 
2133   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2134                                            /*TInfo=*/nullptr, SC_Extern,
2135                                            getCurFPFeatures().isFPConstrained(),
2136                                            false, Type->isFunctionProtoType());
2137   New->setImplicit();
2138   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2139 
2140   // Create Decl objects for each parameter, adding them to the
2141   // FunctionDecl.
2142   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2143     SmallVector<ParmVarDecl *, 16> Params;
2144     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2145       ParmVarDecl *parm = ParmVarDecl::Create(
2146           Context, New, SourceLocation(), SourceLocation(), nullptr,
2147           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2148       parm->setScopeInfo(0, i);
2149       Params.push_back(parm);
2150     }
2151     New->setParams(Params);
2152   }
2153 
2154   AddKnownFunctionAttributes(New);
2155   return New;
2156 }
2157 
2158 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2159 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2160 /// if we're creating this built-in in anticipation of redeclaring the
2161 /// built-in.
2162 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2163                                      Scope *S, bool ForRedeclaration,
2164                                      SourceLocation Loc) {
2165   LookupNecessaryTypesForBuiltin(S, ID);
2166 
2167   ASTContext::GetBuiltinTypeError Error;
2168   QualType R = Context.GetBuiltinType(ID, Error);
2169   if (Error) {
2170     if (!ForRedeclaration)
2171       return nullptr;
2172 
2173     // If we have a builtin without an associated type we should not emit a
2174     // warning when we were not able to find a type for it.
2175     if (Error == ASTContext::GE_Missing_type ||
2176         Context.BuiltinInfo.allowTypeMismatch(ID))
2177       return nullptr;
2178 
2179     // If we could not find a type for setjmp it is because the jmp_buf type was
2180     // not defined prior to the setjmp declaration.
2181     if (Error == ASTContext::GE_Missing_setjmp) {
2182       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2183           << Context.BuiltinInfo.getName(ID);
2184       return nullptr;
2185     }
2186 
2187     // Generally, we emit a warning that the declaration requires the
2188     // appropriate header.
2189     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2190         << getHeaderName(Context.BuiltinInfo, ID, Error)
2191         << Context.BuiltinInfo.getName(ID);
2192     return nullptr;
2193   }
2194 
2195   if (!ForRedeclaration &&
2196       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2197        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2198     Diag(Loc, diag::ext_implicit_lib_function_decl)
2199         << Context.BuiltinInfo.getName(ID) << R;
2200     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2201       Diag(Loc, diag::note_include_header_or_declare)
2202           << Header << Context.BuiltinInfo.getName(ID);
2203   }
2204 
2205   if (R.isNull())
2206     return nullptr;
2207 
2208   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2209   RegisterLocallyScopedExternCDecl(New, S);
2210 
2211   // TUScope is the translation-unit scope to insert this function into.
2212   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2213   // relate Scopes to DeclContexts, and probably eliminate CurContext
2214   // entirely, but we're not there yet.
2215   DeclContext *SavedContext = CurContext;
2216   CurContext = New->getDeclContext();
2217   PushOnScopeChains(New, TUScope);
2218   CurContext = SavedContext;
2219   return New;
2220 }
2221 
2222 /// Typedef declarations don't have linkage, but they still denote the same
2223 /// entity if their types are the same.
2224 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2225 /// isSameEntity.
2226 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2227                                                      TypedefNameDecl *Decl,
2228                                                      LookupResult &Previous) {
2229   // This is only interesting when modules are enabled.
2230   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2231     return;
2232 
2233   // Empty sets are uninteresting.
2234   if (Previous.empty())
2235     return;
2236 
2237   LookupResult::Filter Filter = Previous.makeFilter();
2238   while (Filter.hasNext()) {
2239     NamedDecl *Old = Filter.next();
2240 
2241     // Non-hidden declarations are never ignored.
2242     if (S.isVisible(Old))
2243       continue;
2244 
2245     // Declarations of the same entity are not ignored, even if they have
2246     // different linkages.
2247     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2248       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2249                                 Decl->getUnderlyingType()))
2250         continue;
2251 
2252       // If both declarations give a tag declaration a typedef name for linkage
2253       // purposes, then they declare the same entity.
2254       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2255           Decl->getAnonDeclWithTypedefName())
2256         continue;
2257     }
2258 
2259     Filter.erase();
2260   }
2261 
2262   Filter.done();
2263 }
2264 
2265 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2266   QualType OldType;
2267   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2268     OldType = OldTypedef->getUnderlyingType();
2269   else
2270     OldType = Context.getTypeDeclType(Old);
2271   QualType NewType = New->getUnderlyingType();
2272 
2273   if (NewType->isVariablyModifiedType()) {
2274     // Must not redefine a typedef with a variably-modified type.
2275     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2276     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2277       << Kind << NewType;
2278     if (Old->getLocation().isValid())
2279       notePreviousDefinition(Old, New->getLocation());
2280     New->setInvalidDecl();
2281     return true;
2282   }
2283 
2284   if (OldType != NewType &&
2285       !OldType->isDependentType() &&
2286       !NewType->isDependentType() &&
2287       !Context.hasSameType(OldType, NewType)) {
2288     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2289     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2290       << Kind << NewType << OldType;
2291     if (Old->getLocation().isValid())
2292       notePreviousDefinition(Old, New->getLocation());
2293     New->setInvalidDecl();
2294     return true;
2295   }
2296   return false;
2297 }
2298 
2299 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2300 /// same name and scope as a previous declaration 'Old'.  Figure out
2301 /// how to resolve this situation, merging decls or emitting
2302 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2303 ///
2304 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2305                                 LookupResult &OldDecls) {
2306   // If the new decl is known invalid already, don't bother doing any
2307   // merging checks.
2308   if (New->isInvalidDecl()) return;
2309 
2310   // Allow multiple definitions for ObjC built-in typedefs.
2311   // FIXME: Verify the underlying types are equivalent!
2312   if (getLangOpts().ObjC) {
2313     const IdentifierInfo *TypeID = New->getIdentifier();
2314     switch (TypeID->getLength()) {
2315     default: break;
2316     case 2:
2317       {
2318         if (!TypeID->isStr("id"))
2319           break;
2320         QualType T = New->getUnderlyingType();
2321         if (!T->isPointerType())
2322           break;
2323         if (!T->isVoidPointerType()) {
2324           QualType PT = T->castAs<PointerType>()->getPointeeType();
2325           if (!PT->isStructureType())
2326             break;
2327         }
2328         Context.setObjCIdRedefinitionType(T);
2329         // Install the built-in type for 'id', ignoring the current definition.
2330         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2331         return;
2332       }
2333     case 5:
2334       if (!TypeID->isStr("Class"))
2335         break;
2336       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2337       // Install the built-in type for 'Class', ignoring the current definition.
2338       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2339       return;
2340     case 3:
2341       if (!TypeID->isStr("SEL"))
2342         break;
2343       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2344       // Install the built-in type for 'SEL', ignoring the current definition.
2345       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2346       return;
2347     }
2348     // Fall through - the typedef name was not a builtin type.
2349   }
2350 
2351   // Verify the old decl was also a type.
2352   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2353   if (!Old) {
2354     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2355       << New->getDeclName();
2356 
2357     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2358     if (OldD->getLocation().isValid())
2359       notePreviousDefinition(OldD, New->getLocation());
2360 
2361     return New->setInvalidDecl();
2362   }
2363 
2364   // If the old declaration is invalid, just give up here.
2365   if (Old->isInvalidDecl())
2366     return New->setInvalidDecl();
2367 
2368   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2369     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2370     auto *NewTag = New->getAnonDeclWithTypedefName();
2371     NamedDecl *Hidden = nullptr;
2372     if (OldTag && NewTag &&
2373         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2374         !hasVisibleDefinition(OldTag, &Hidden)) {
2375       // There is a definition of this tag, but it is not visible. Use it
2376       // instead of our tag.
2377       New->setTypeForDecl(OldTD->getTypeForDecl());
2378       if (OldTD->isModed())
2379         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2380                                     OldTD->getUnderlyingType());
2381       else
2382         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2383 
2384       // Make the old tag definition visible.
2385       makeMergedDefinitionVisible(Hidden);
2386 
2387       // If this was an unscoped enumeration, yank all of its enumerators
2388       // out of the scope.
2389       if (isa<EnumDecl>(NewTag)) {
2390         Scope *EnumScope = getNonFieldDeclScope(S);
2391         for (auto *D : NewTag->decls()) {
2392           auto *ED = cast<EnumConstantDecl>(D);
2393           assert(EnumScope->isDeclScope(ED));
2394           EnumScope->RemoveDecl(ED);
2395           IdResolver.RemoveDecl(ED);
2396           ED->getLexicalDeclContext()->removeDecl(ED);
2397         }
2398       }
2399     }
2400   }
2401 
2402   // If the typedef types are not identical, reject them in all languages and
2403   // with any extensions enabled.
2404   if (isIncompatibleTypedef(Old, New))
2405     return;
2406 
2407   // The types match.  Link up the redeclaration chain and merge attributes if
2408   // the old declaration was a typedef.
2409   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2410     New->setPreviousDecl(Typedef);
2411     mergeDeclAttributes(New, Old);
2412   }
2413 
2414   if (getLangOpts().MicrosoftExt)
2415     return;
2416 
2417   if (getLangOpts().CPlusPlus) {
2418     // C++ [dcl.typedef]p2:
2419     //   In a given non-class scope, a typedef specifier can be used to
2420     //   redefine the name of any type declared in that scope to refer
2421     //   to the type to which it already refers.
2422     if (!isa<CXXRecordDecl>(CurContext))
2423       return;
2424 
2425     // C++0x [dcl.typedef]p4:
2426     //   In a given class scope, a typedef specifier can be used to redefine
2427     //   any class-name declared in that scope that is not also a typedef-name
2428     //   to refer to the type to which it already refers.
2429     //
2430     // This wording came in via DR424, which was a correction to the
2431     // wording in DR56, which accidentally banned code like:
2432     //
2433     //   struct S {
2434     //     typedef struct A { } A;
2435     //   };
2436     //
2437     // in the C++03 standard. We implement the C++0x semantics, which
2438     // allow the above but disallow
2439     //
2440     //   struct S {
2441     //     typedef int I;
2442     //     typedef int I;
2443     //   };
2444     //
2445     // since that was the intent of DR56.
2446     if (!isa<TypedefNameDecl>(Old))
2447       return;
2448 
2449     Diag(New->getLocation(), diag::err_redefinition)
2450       << New->getDeclName();
2451     notePreviousDefinition(Old, New->getLocation());
2452     return New->setInvalidDecl();
2453   }
2454 
2455   // Modules always permit redefinition of typedefs, as does C11.
2456   if (getLangOpts().Modules || getLangOpts().C11)
2457     return;
2458 
2459   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2460   // is normally mapped to an error, but can be controlled with
2461   // -Wtypedef-redefinition.  If either the original or the redefinition is
2462   // in a system header, don't emit this for compatibility with GCC.
2463   if (getDiagnostics().getSuppressSystemWarnings() &&
2464       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2465       (Old->isImplicit() ||
2466        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2467        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2468     return;
2469 
2470   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2471     << New->getDeclName();
2472   notePreviousDefinition(Old, New->getLocation());
2473 }
2474 
2475 /// DeclhasAttr - returns true if decl Declaration already has the target
2476 /// attribute.
2477 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2478   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2479   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2480   for (const auto *i : D->attrs())
2481     if (i->getKind() == A->getKind()) {
2482       if (Ann) {
2483         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2484           return true;
2485         continue;
2486       }
2487       // FIXME: Don't hardcode this check
2488       if (OA && isa<OwnershipAttr>(i))
2489         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2490       return true;
2491     }
2492 
2493   return false;
2494 }
2495 
2496 static bool isAttributeTargetADefinition(Decl *D) {
2497   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2498     return VD->isThisDeclarationADefinition();
2499   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2500     return TD->isCompleteDefinition() || TD->isBeingDefined();
2501   return true;
2502 }
2503 
2504 /// Merge alignment attributes from \p Old to \p New, taking into account the
2505 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2506 ///
2507 /// \return \c true if any attributes were added to \p New.
2508 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2509   // Look for alignas attributes on Old, and pick out whichever attribute
2510   // specifies the strictest alignment requirement.
2511   AlignedAttr *OldAlignasAttr = nullptr;
2512   AlignedAttr *OldStrictestAlignAttr = nullptr;
2513   unsigned OldAlign = 0;
2514   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2515     // FIXME: We have no way of representing inherited dependent alignments
2516     // in a case like:
2517     //   template<int A, int B> struct alignas(A) X;
2518     //   template<int A, int B> struct alignas(B) X {};
2519     // For now, we just ignore any alignas attributes which are not on the
2520     // definition in such a case.
2521     if (I->isAlignmentDependent())
2522       return false;
2523 
2524     if (I->isAlignas())
2525       OldAlignasAttr = I;
2526 
2527     unsigned Align = I->getAlignment(S.Context);
2528     if (Align > OldAlign) {
2529       OldAlign = Align;
2530       OldStrictestAlignAttr = I;
2531     }
2532   }
2533 
2534   // Look for alignas attributes on New.
2535   AlignedAttr *NewAlignasAttr = nullptr;
2536   unsigned NewAlign = 0;
2537   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2538     if (I->isAlignmentDependent())
2539       return false;
2540 
2541     if (I->isAlignas())
2542       NewAlignasAttr = I;
2543 
2544     unsigned Align = I->getAlignment(S.Context);
2545     if (Align > NewAlign)
2546       NewAlign = Align;
2547   }
2548 
2549   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2550     // Both declarations have 'alignas' attributes. We require them to match.
2551     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2552     // fall short. (If two declarations both have alignas, they must both match
2553     // every definition, and so must match each other if there is a definition.)
2554 
2555     // If either declaration only contains 'alignas(0)' specifiers, then it
2556     // specifies the natural alignment for the type.
2557     if (OldAlign == 0 || NewAlign == 0) {
2558       QualType Ty;
2559       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2560         Ty = VD->getType();
2561       else
2562         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2563 
2564       if (OldAlign == 0)
2565         OldAlign = S.Context.getTypeAlign(Ty);
2566       if (NewAlign == 0)
2567         NewAlign = S.Context.getTypeAlign(Ty);
2568     }
2569 
2570     if (OldAlign != NewAlign) {
2571       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2572         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2573         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2574       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2575     }
2576   }
2577 
2578   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2579     // C++11 [dcl.align]p6:
2580     //   if any declaration of an entity has an alignment-specifier,
2581     //   every defining declaration of that entity shall specify an
2582     //   equivalent alignment.
2583     // C11 6.7.5/7:
2584     //   If the definition of an object does not have an alignment
2585     //   specifier, any other declaration of that object shall also
2586     //   have no alignment specifier.
2587     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2588       << OldAlignasAttr;
2589     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2590       << OldAlignasAttr;
2591   }
2592 
2593   bool AnyAdded = false;
2594 
2595   // Ensure we have an attribute representing the strictest alignment.
2596   if (OldAlign > NewAlign) {
2597     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2598     Clone->setInherited(true);
2599     New->addAttr(Clone);
2600     AnyAdded = true;
2601   }
2602 
2603   // Ensure we have an alignas attribute if the old declaration had one.
2604   if (OldAlignasAttr && !NewAlignasAttr &&
2605       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2606     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2607     Clone->setInherited(true);
2608     New->addAttr(Clone);
2609     AnyAdded = true;
2610   }
2611 
2612   return AnyAdded;
2613 }
2614 
2615 #define WANT_DECL_MERGE_LOGIC
2616 #include "clang/Sema/AttrParsedAttrImpl.inc"
2617 #undef WANT_DECL_MERGE_LOGIC
2618 
2619 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2620                                const InheritableAttr *Attr,
2621                                Sema::AvailabilityMergeKind AMK) {
2622   // Diagnose any mutual exclusions between the attribute that we want to add
2623   // and attributes that already exist on the declaration.
2624   if (!DiagnoseMutualExclusions(S, D, Attr))
2625     return false;
2626 
2627   // This function copies an attribute Attr from a previous declaration to the
2628   // new declaration D if the new declaration doesn't itself have that attribute
2629   // yet or if that attribute allows duplicates.
2630   // If you're adding a new attribute that requires logic different from
2631   // "use explicit attribute on decl if present, else use attribute from
2632   // previous decl", for example if the attribute needs to be consistent
2633   // between redeclarations, you need to call a custom merge function here.
2634   InheritableAttr *NewAttr = nullptr;
2635   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2636     NewAttr = S.mergeAvailabilityAttr(
2637         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2638         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2639         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2640         AA->getPriority());
2641   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2642     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2643   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2644     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2645   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2646     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2647   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2648     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2649   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2650     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2651   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2652     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2653                                 FA->getFirstArg());
2654   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2655     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2656   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2657     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2658   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2659     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2660                                        IA->getInheritanceModel());
2661   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2662     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2663                                       &S.Context.Idents.get(AA->getSpelling()));
2664   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2665            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2666             isa<CUDAGlobalAttr>(Attr))) {
2667     // CUDA target attributes are part of function signature for
2668     // overloading purposes and must not be merged.
2669     return false;
2670   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2671     NewAttr = S.mergeMinSizeAttr(D, *MA);
2672   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2673     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2674   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2675     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2676   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2677     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2678   else if (isa<AlignedAttr>(Attr))
2679     // AlignedAttrs are handled separately, because we need to handle all
2680     // such attributes on a declaration at the same time.
2681     NewAttr = nullptr;
2682   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2683            (AMK == Sema::AMK_Override ||
2684             AMK == Sema::AMK_ProtocolImplementation ||
2685             AMK == Sema::AMK_OptionalProtocolImplementation))
2686     NewAttr = nullptr;
2687   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2688     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2689   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2690     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2691   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2692     NewAttr = S.mergeImportNameAttr(D, *INA);
2693   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2694     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2695   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2696     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2697   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2698     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2699   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2700     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2701 
2702   if (NewAttr) {
2703     NewAttr->setInherited(true);
2704     D->addAttr(NewAttr);
2705     if (isa<MSInheritanceAttr>(NewAttr))
2706       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2707     return true;
2708   }
2709 
2710   return false;
2711 }
2712 
2713 static const NamedDecl *getDefinition(const Decl *D) {
2714   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2715     return TD->getDefinition();
2716   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2717     const VarDecl *Def = VD->getDefinition();
2718     if (Def)
2719       return Def;
2720     return VD->getActingDefinition();
2721   }
2722   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2723     const FunctionDecl *Def = nullptr;
2724     if (FD->isDefined(Def, true))
2725       return Def;
2726   }
2727   return nullptr;
2728 }
2729 
2730 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2731   for (const auto *Attribute : D->attrs())
2732     if (Attribute->getKind() == Kind)
2733       return true;
2734   return false;
2735 }
2736 
2737 /// checkNewAttributesAfterDef - If we already have a definition, check that
2738 /// there are no new attributes in this declaration.
2739 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2740   if (!New->hasAttrs())
2741     return;
2742 
2743   const NamedDecl *Def = getDefinition(Old);
2744   if (!Def || Def == New)
2745     return;
2746 
2747   AttrVec &NewAttributes = New->getAttrs();
2748   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2749     const Attr *NewAttribute = NewAttributes[I];
2750 
2751     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2752       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2753         Sema::SkipBodyInfo SkipBody;
2754         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2755 
2756         // If we're skipping this definition, drop the "alias" attribute.
2757         if (SkipBody.ShouldSkip) {
2758           NewAttributes.erase(NewAttributes.begin() + I);
2759           --E;
2760           continue;
2761         }
2762       } else {
2763         VarDecl *VD = cast<VarDecl>(New);
2764         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2765                                 VarDecl::TentativeDefinition
2766                             ? diag::err_alias_after_tentative
2767                             : diag::err_redefinition;
2768         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2769         if (Diag == diag::err_redefinition)
2770           S.notePreviousDefinition(Def, VD->getLocation());
2771         else
2772           S.Diag(Def->getLocation(), diag::note_previous_definition);
2773         VD->setInvalidDecl();
2774       }
2775       ++I;
2776       continue;
2777     }
2778 
2779     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2780       // Tentative definitions are only interesting for the alias check above.
2781       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2782         ++I;
2783         continue;
2784       }
2785     }
2786 
2787     if (hasAttribute(Def, NewAttribute->getKind())) {
2788       ++I;
2789       continue; // regular attr merging will take care of validating this.
2790     }
2791 
2792     if (isa<C11NoReturnAttr>(NewAttribute)) {
2793       // C's _Noreturn is allowed to be added to a function after it is defined.
2794       ++I;
2795       continue;
2796     } else if (isa<UuidAttr>(NewAttribute)) {
2797       // msvc will allow a subsequent definition to add an uuid to a class
2798       ++I;
2799       continue;
2800     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2801       if (AA->isAlignas()) {
2802         // C++11 [dcl.align]p6:
2803         //   if any declaration of an entity has an alignment-specifier,
2804         //   every defining declaration of that entity shall specify an
2805         //   equivalent alignment.
2806         // C11 6.7.5/7:
2807         //   If the definition of an object does not have an alignment
2808         //   specifier, any other declaration of that object shall also
2809         //   have no alignment specifier.
2810         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2811           << AA;
2812         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2813           << AA;
2814         NewAttributes.erase(NewAttributes.begin() + I);
2815         --E;
2816         continue;
2817       }
2818     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2819       // If there is a C definition followed by a redeclaration with this
2820       // attribute then there are two different definitions. In C++, prefer the
2821       // standard diagnostics.
2822       if (!S.getLangOpts().CPlusPlus) {
2823         S.Diag(NewAttribute->getLocation(),
2824                diag::err_loader_uninitialized_redeclaration);
2825         S.Diag(Def->getLocation(), diag::note_previous_definition);
2826         NewAttributes.erase(NewAttributes.begin() + I);
2827         --E;
2828         continue;
2829       }
2830     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2831                cast<VarDecl>(New)->isInline() &&
2832                !cast<VarDecl>(New)->isInlineSpecified()) {
2833       // Don't warn about applying selectany to implicitly inline variables.
2834       // Older compilers and language modes would require the use of selectany
2835       // to make such variables inline, and it would have no effect if we
2836       // honored it.
2837       ++I;
2838       continue;
2839     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2840       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2841       // declarations after defintions.
2842       ++I;
2843       continue;
2844     }
2845 
2846     S.Diag(NewAttribute->getLocation(),
2847            diag::warn_attribute_precede_definition);
2848     S.Diag(Def->getLocation(), diag::note_previous_definition);
2849     NewAttributes.erase(NewAttributes.begin() + I);
2850     --E;
2851   }
2852 }
2853 
2854 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2855                                      const ConstInitAttr *CIAttr,
2856                                      bool AttrBeforeInit) {
2857   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2858 
2859   // Figure out a good way to write this specifier on the old declaration.
2860   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2861   // enough of the attribute list spelling information to extract that without
2862   // heroics.
2863   std::string SuitableSpelling;
2864   if (S.getLangOpts().CPlusPlus20)
2865     SuitableSpelling = std::string(
2866         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2867   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2868     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2869         InsertLoc, {tok::l_square, tok::l_square,
2870                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2871                     S.PP.getIdentifierInfo("require_constant_initialization"),
2872                     tok::r_square, tok::r_square}));
2873   if (SuitableSpelling.empty())
2874     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2875         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2876                     S.PP.getIdentifierInfo("require_constant_initialization"),
2877                     tok::r_paren, tok::r_paren}));
2878   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2879     SuitableSpelling = "constinit";
2880   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2881     SuitableSpelling = "[[clang::require_constant_initialization]]";
2882   if (SuitableSpelling.empty())
2883     SuitableSpelling = "__attribute__((require_constant_initialization))";
2884   SuitableSpelling += " ";
2885 
2886   if (AttrBeforeInit) {
2887     // extern constinit int a;
2888     // int a = 0; // error (missing 'constinit'), accepted as extension
2889     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2890     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2891         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2892     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2893   } else {
2894     // int a = 0;
2895     // constinit extern int a; // error (missing 'constinit')
2896     S.Diag(CIAttr->getLocation(),
2897            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2898                                  : diag::warn_require_const_init_added_too_late)
2899         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2900     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2901         << CIAttr->isConstinit()
2902         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2903   }
2904 }
2905 
2906 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2907 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2908                                AvailabilityMergeKind AMK) {
2909   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2910     UsedAttr *NewAttr = OldAttr->clone(Context);
2911     NewAttr->setInherited(true);
2912     New->addAttr(NewAttr);
2913   }
2914   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2915     RetainAttr *NewAttr = OldAttr->clone(Context);
2916     NewAttr->setInherited(true);
2917     New->addAttr(NewAttr);
2918   }
2919 
2920   if (!Old->hasAttrs() && !New->hasAttrs())
2921     return;
2922 
2923   // [dcl.constinit]p1:
2924   //   If the [constinit] specifier is applied to any declaration of a
2925   //   variable, it shall be applied to the initializing declaration.
2926   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2927   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2928   if (bool(OldConstInit) != bool(NewConstInit)) {
2929     const auto *OldVD = cast<VarDecl>(Old);
2930     auto *NewVD = cast<VarDecl>(New);
2931 
2932     // Find the initializing declaration. Note that we might not have linked
2933     // the new declaration into the redeclaration chain yet.
2934     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2935     if (!InitDecl &&
2936         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2937       InitDecl = NewVD;
2938 
2939     if (InitDecl == NewVD) {
2940       // This is the initializing declaration. If it would inherit 'constinit',
2941       // that's ill-formed. (Note that we do not apply this to the attribute
2942       // form).
2943       if (OldConstInit && OldConstInit->isConstinit())
2944         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2945                                  /*AttrBeforeInit=*/true);
2946     } else if (NewConstInit) {
2947       // This is the first time we've been told that this declaration should
2948       // have a constant initializer. If we already saw the initializing
2949       // declaration, this is too late.
2950       if (InitDecl && InitDecl != NewVD) {
2951         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2952                                  /*AttrBeforeInit=*/false);
2953         NewVD->dropAttr<ConstInitAttr>();
2954       }
2955     }
2956   }
2957 
2958   // Attributes declared post-definition are currently ignored.
2959   checkNewAttributesAfterDef(*this, New, Old);
2960 
2961   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2962     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2963       if (!OldA->isEquivalent(NewA)) {
2964         // This redeclaration changes __asm__ label.
2965         Diag(New->getLocation(), diag::err_different_asm_label);
2966         Diag(OldA->getLocation(), diag::note_previous_declaration);
2967       }
2968     } else if (Old->isUsed()) {
2969       // This redeclaration adds an __asm__ label to a declaration that has
2970       // already been ODR-used.
2971       Diag(New->getLocation(), diag::err_late_asm_label_name)
2972         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2973     }
2974   }
2975 
2976   // Re-declaration cannot add abi_tag's.
2977   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2978     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2979       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2980         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
2981           Diag(NewAbiTagAttr->getLocation(),
2982                diag::err_new_abi_tag_on_redeclaration)
2983               << NewTag;
2984           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2985         }
2986       }
2987     } else {
2988       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2989       Diag(Old->getLocation(), diag::note_previous_declaration);
2990     }
2991   }
2992 
2993   // This redeclaration adds a section attribute.
2994   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2995     if (auto *VD = dyn_cast<VarDecl>(New)) {
2996       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2997         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2998         Diag(Old->getLocation(), diag::note_previous_declaration);
2999       }
3000     }
3001   }
3002 
3003   // Redeclaration adds code-seg attribute.
3004   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3005   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3006       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3007     Diag(New->getLocation(), diag::warn_mismatched_section)
3008          << 0 /*codeseg*/;
3009     Diag(Old->getLocation(), diag::note_previous_declaration);
3010   }
3011 
3012   if (!Old->hasAttrs())
3013     return;
3014 
3015   bool foundAny = New->hasAttrs();
3016 
3017   // Ensure that any moving of objects within the allocated map is done before
3018   // we process them.
3019   if (!foundAny) New->setAttrs(AttrVec());
3020 
3021   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3022     // Ignore deprecated/unavailable/availability attributes if requested.
3023     AvailabilityMergeKind LocalAMK = AMK_None;
3024     if (isa<DeprecatedAttr>(I) ||
3025         isa<UnavailableAttr>(I) ||
3026         isa<AvailabilityAttr>(I)) {
3027       switch (AMK) {
3028       case AMK_None:
3029         continue;
3030 
3031       case AMK_Redeclaration:
3032       case AMK_Override:
3033       case AMK_ProtocolImplementation:
3034       case AMK_OptionalProtocolImplementation:
3035         LocalAMK = AMK;
3036         break;
3037       }
3038     }
3039 
3040     // Already handled.
3041     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3042       continue;
3043 
3044     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3045       foundAny = true;
3046   }
3047 
3048   if (mergeAlignedAttrs(*this, New, Old))
3049     foundAny = true;
3050 
3051   if (!foundAny) New->dropAttrs();
3052 }
3053 
3054 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3055 /// to the new one.
3056 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3057                                      const ParmVarDecl *oldDecl,
3058                                      Sema &S) {
3059   // C++11 [dcl.attr.depend]p2:
3060   //   The first declaration of a function shall specify the
3061   //   carries_dependency attribute for its declarator-id if any declaration
3062   //   of the function specifies the carries_dependency attribute.
3063   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3064   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3065     S.Diag(CDA->getLocation(),
3066            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3067     // Find the first declaration of the parameter.
3068     // FIXME: Should we build redeclaration chains for function parameters?
3069     const FunctionDecl *FirstFD =
3070       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3071     const ParmVarDecl *FirstVD =
3072       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3073     S.Diag(FirstVD->getLocation(),
3074            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3075   }
3076 
3077   if (!oldDecl->hasAttrs())
3078     return;
3079 
3080   bool foundAny = newDecl->hasAttrs();
3081 
3082   // Ensure that any moving of objects within the allocated map is
3083   // done before we process them.
3084   if (!foundAny) newDecl->setAttrs(AttrVec());
3085 
3086   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3087     if (!DeclHasAttr(newDecl, I)) {
3088       InheritableAttr *newAttr =
3089         cast<InheritableParamAttr>(I->clone(S.Context));
3090       newAttr->setInherited(true);
3091       newDecl->addAttr(newAttr);
3092       foundAny = true;
3093     }
3094   }
3095 
3096   if (!foundAny) newDecl->dropAttrs();
3097 }
3098 
3099 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3100                                 const ParmVarDecl *OldParam,
3101                                 Sema &S) {
3102   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3103     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3104       if (*Oldnullability != *Newnullability) {
3105         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3106           << DiagNullabilityKind(
3107                *Newnullability,
3108                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3109                 != 0))
3110           << DiagNullabilityKind(
3111                *Oldnullability,
3112                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3113                 != 0));
3114         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3115       }
3116     } else {
3117       QualType NewT = NewParam->getType();
3118       NewT = S.Context.getAttributedType(
3119                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3120                          NewT, NewT);
3121       NewParam->setType(NewT);
3122     }
3123   }
3124 }
3125 
3126 namespace {
3127 
3128 /// Used in MergeFunctionDecl to keep track of function parameters in
3129 /// C.
3130 struct GNUCompatibleParamWarning {
3131   ParmVarDecl *OldParm;
3132   ParmVarDecl *NewParm;
3133   QualType PromotedType;
3134 };
3135 
3136 } // end anonymous namespace
3137 
3138 // Determine whether the previous declaration was a definition, implicit
3139 // declaration, or a declaration.
3140 template <typename T>
3141 static std::pair<diag::kind, SourceLocation>
3142 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3143   diag::kind PrevDiag;
3144   SourceLocation OldLocation = Old->getLocation();
3145   if (Old->isThisDeclarationADefinition())
3146     PrevDiag = diag::note_previous_definition;
3147   else if (Old->isImplicit()) {
3148     PrevDiag = diag::note_previous_implicit_declaration;
3149     if (OldLocation.isInvalid())
3150       OldLocation = New->getLocation();
3151   } else
3152     PrevDiag = diag::note_previous_declaration;
3153   return std::make_pair(PrevDiag, OldLocation);
3154 }
3155 
3156 /// canRedefineFunction - checks if a function can be redefined. Currently,
3157 /// only extern inline functions can be redefined, and even then only in
3158 /// GNU89 mode.
3159 static bool canRedefineFunction(const FunctionDecl *FD,
3160                                 const LangOptions& LangOpts) {
3161   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3162           !LangOpts.CPlusPlus &&
3163           FD->isInlineSpecified() &&
3164           FD->getStorageClass() == SC_Extern);
3165 }
3166 
3167 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3168   const AttributedType *AT = T->getAs<AttributedType>();
3169   while (AT && !AT->isCallingConv())
3170     AT = AT->getModifiedType()->getAs<AttributedType>();
3171   return AT;
3172 }
3173 
3174 template <typename T>
3175 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3176   const DeclContext *DC = Old->getDeclContext();
3177   if (DC->isRecord())
3178     return false;
3179 
3180   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3181   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3182     return true;
3183   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3184     return true;
3185   return false;
3186 }
3187 
3188 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3189 static bool isExternC(VarTemplateDecl *) { return false; }
3190 static bool isExternC(FunctionTemplateDecl *) { return false; }
3191 
3192 /// Check whether a redeclaration of an entity introduced by a
3193 /// using-declaration is valid, given that we know it's not an overload
3194 /// (nor a hidden tag declaration).
3195 template<typename ExpectedDecl>
3196 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3197                                    ExpectedDecl *New) {
3198   // C++11 [basic.scope.declarative]p4:
3199   //   Given a set of declarations in a single declarative region, each of
3200   //   which specifies the same unqualified name,
3201   //   -- they shall all refer to the same entity, or all refer to functions
3202   //      and function templates; or
3203   //   -- exactly one declaration shall declare a class name or enumeration
3204   //      name that is not a typedef name and the other declarations shall all
3205   //      refer to the same variable or enumerator, or all refer to functions
3206   //      and function templates; in this case the class name or enumeration
3207   //      name is hidden (3.3.10).
3208 
3209   // C++11 [namespace.udecl]p14:
3210   //   If a function declaration in namespace scope or block scope has the
3211   //   same name and the same parameter-type-list as a function introduced
3212   //   by a using-declaration, and the declarations do not declare the same
3213   //   function, the program is ill-formed.
3214 
3215   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3216   if (Old &&
3217       !Old->getDeclContext()->getRedeclContext()->Equals(
3218           New->getDeclContext()->getRedeclContext()) &&
3219       !(isExternC(Old) && isExternC(New)))
3220     Old = nullptr;
3221 
3222   if (!Old) {
3223     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3224     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3225     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3226     return true;
3227   }
3228   return false;
3229 }
3230 
3231 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3232                                             const FunctionDecl *B) {
3233   assert(A->getNumParams() == B->getNumParams());
3234 
3235   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3236     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3237     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3238     if (AttrA == AttrB)
3239       return true;
3240     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3241            AttrA->isDynamic() == AttrB->isDynamic();
3242   };
3243 
3244   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3245 }
3246 
3247 /// If necessary, adjust the semantic declaration context for a qualified
3248 /// declaration to name the correct inline namespace within the qualifier.
3249 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3250                                                DeclaratorDecl *OldD) {
3251   // The only case where we need to update the DeclContext is when
3252   // redeclaration lookup for a qualified name finds a declaration
3253   // in an inline namespace within the context named by the qualifier:
3254   //
3255   //   inline namespace N { int f(); }
3256   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3257   //
3258   // For unqualified declarations, the semantic context *can* change
3259   // along the redeclaration chain (for local extern declarations,
3260   // extern "C" declarations, and friend declarations in particular).
3261   if (!NewD->getQualifier())
3262     return;
3263 
3264   // NewD is probably already in the right context.
3265   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3266   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3267   if (NamedDC->Equals(SemaDC))
3268     return;
3269 
3270   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3271           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3272          "unexpected context for redeclaration");
3273 
3274   auto *LexDC = NewD->getLexicalDeclContext();
3275   auto FixSemaDC = [=](NamedDecl *D) {
3276     if (!D)
3277       return;
3278     D->setDeclContext(SemaDC);
3279     D->setLexicalDeclContext(LexDC);
3280   };
3281 
3282   FixSemaDC(NewD);
3283   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3284     FixSemaDC(FD->getDescribedFunctionTemplate());
3285   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3286     FixSemaDC(VD->getDescribedVarTemplate());
3287 }
3288 
3289 /// MergeFunctionDecl - We just parsed a function 'New' from
3290 /// declarator D which has the same name and scope as a previous
3291 /// declaration 'Old'.  Figure out how to resolve this situation,
3292 /// merging decls or emitting diagnostics as appropriate.
3293 ///
3294 /// In C++, New and Old must be declarations that are not
3295 /// overloaded. Use IsOverload to determine whether New and Old are
3296 /// overloaded, and to select the Old declaration that New should be
3297 /// merged with.
3298 ///
3299 /// Returns true if there was an error, false otherwise.
3300 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3301                              Scope *S, bool MergeTypeWithOld) {
3302   // Verify the old decl was also a function.
3303   FunctionDecl *Old = OldD->getAsFunction();
3304   if (!Old) {
3305     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3306       if (New->getFriendObjectKind()) {
3307         Diag(New->getLocation(), diag::err_using_decl_friend);
3308         Diag(Shadow->getTargetDecl()->getLocation(),
3309              diag::note_using_decl_target);
3310         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3311             << 0;
3312         return true;
3313       }
3314 
3315       // Check whether the two declarations might declare the same function or
3316       // function template.
3317       if (FunctionTemplateDecl *NewTemplate =
3318               New->getDescribedFunctionTemplate()) {
3319         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3320                                                          NewTemplate))
3321           return true;
3322         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3323                          ->getAsFunction();
3324       } else {
3325         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3326           return true;
3327         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3328       }
3329     } else {
3330       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3331         << New->getDeclName();
3332       notePreviousDefinition(OldD, New->getLocation());
3333       return true;
3334     }
3335   }
3336 
3337   // If the old declaration was found in an inline namespace and the new
3338   // declaration was qualified, update the DeclContext to match.
3339   adjustDeclContextForDeclaratorDecl(New, Old);
3340 
3341   // If the old declaration is invalid, just give up here.
3342   if (Old->isInvalidDecl())
3343     return true;
3344 
3345   // Disallow redeclaration of some builtins.
3346   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3347     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3348     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3349         << Old << Old->getType();
3350     return true;
3351   }
3352 
3353   diag::kind PrevDiag;
3354   SourceLocation OldLocation;
3355   std::tie(PrevDiag, OldLocation) =
3356       getNoteDiagForInvalidRedeclaration(Old, New);
3357 
3358   // Don't complain about this if we're in GNU89 mode and the old function
3359   // is an extern inline function.
3360   // Don't complain about specializations. They are not supposed to have
3361   // storage classes.
3362   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3363       New->getStorageClass() == SC_Static &&
3364       Old->hasExternalFormalLinkage() &&
3365       !New->getTemplateSpecializationInfo() &&
3366       !canRedefineFunction(Old, getLangOpts())) {
3367     if (getLangOpts().MicrosoftExt) {
3368       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3369       Diag(OldLocation, PrevDiag);
3370     } else {
3371       Diag(New->getLocation(), diag::err_static_non_static) << New;
3372       Diag(OldLocation, PrevDiag);
3373       return true;
3374     }
3375   }
3376 
3377   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3378     if (!Old->hasAttr<InternalLinkageAttr>()) {
3379       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3380           << ILA;
3381       Diag(Old->getLocation(), diag::note_previous_declaration);
3382       New->dropAttr<InternalLinkageAttr>();
3383     }
3384 
3385   if (auto *EA = New->getAttr<ErrorAttr>()) {
3386     if (!Old->hasAttr<ErrorAttr>()) {
3387       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3388       Diag(Old->getLocation(), diag::note_previous_declaration);
3389       New->dropAttr<ErrorAttr>();
3390     }
3391   }
3392 
3393   if (CheckRedeclarationModuleOwnership(New, Old))
3394     return true;
3395 
3396   if (!getLangOpts().CPlusPlus) {
3397     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3398     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3399       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3400         << New << OldOvl;
3401 
3402       // Try our best to find a decl that actually has the overloadable
3403       // attribute for the note. In most cases (e.g. programs with only one
3404       // broken declaration/definition), this won't matter.
3405       //
3406       // FIXME: We could do this if we juggled some extra state in
3407       // OverloadableAttr, rather than just removing it.
3408       const Decl *DiagOld = Old;
3409       if (OldOvl) {
3410         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3411           const auto *A = D->getAttr<OverloadableAttr>();
3412           return A && !A->isImplicit();
3413         });
3414         // If we've implicitly added *all* of the overloadable attrs to this
3415         // chain, emitting a "previous redecl" note is pointless.
3416         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3417       }
3418 
3419       if (DiagOld)
3420         Diag(DiagOld->getLocation(),
3421              diag::note_attribute_overloadable_prev_overload)
3422           << OldOvl;
3423 
3424       if (OldOvl)
3425         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3426       else
3427         New->dropAttr<OverloadableAttr>();
3428     }
3429   }
3430 
3431   // If a function is first declared with a calling convention, but is later
3432   // declared or defined without one, all following decls assume the calling
3433   // convention of the first.
3434   //
3435   // It's OK if a function is first declared without a calling convention,
3436   // but is later declared or defined with the default calling convention.
3437   //
3438   // To test if either decl has an explicit calling convention, we look for
3439   // AttributedType sugar nodes on the type as written.  If they are missing or
3440   // were canonicalized away, we assume the calling convention was implicit.
3441   //
3442   // Note also that we DO NOT return at this point, because we still have
3443   // other tests to run.
3444   QualType OldQType = Context.getCanonicalType(Old->getType());
3445   QualType NewQType = Context.getCanonicalType(New->getType());
3446   const FunctionType *OldType = cast<FunctionType>(OldQType);
3447   const FunctionType *NewType = cast<FunctionType>(NewQType);
3448   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3449   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3450   bool RequiresAdjustment = false;
3451 
3452   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3453     FunctionDecl *First = Old->getFirstDecl();
3454     const FunctionType *FT =
3455         First->getType().getCanonicalType()->castAs<FunctionType>();
3456     FunctionType::ExtInfo FI = FT->getExtInfo();
3457     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3458     if (!NewCCExplicit) {
3459       // Inherit the CC from the previous declaration if it was specified
3460       // there but not here.
3461       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3462       RequiresAdjustment = true;
3463     } else if (Old->getBuiltinID()) {
3464       // Builtin attribute isn't propagated to the new one yet at this point,
3465       // so we check if the old one is a builtin.
3466 
3467       // Calling Conventions on a Builtin aren't really useful and setting a
3468       // default calling convention and cdecl'ing some builtin redeclarations is
3469       // common, so warn and ignore the calling convention on the redeclaration.
3470       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3471           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3472           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3473       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3474       RequiresAdjustment = true;
3475     } else {
3476       // Calling conventions aren't compatible, so complain.
3477       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3478       Diag(New->getLocation(), diag::err_cconv_change)
3479         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3480         << !FirstCCExplicit
3481         << (!FirstCCExplicit ? "" :
3482             FunctionType::getNameForCallConv(FI.getCC()));
3483 
3484       // Put the note on the first decl, since it is the one that matters.
3485       Diag(First->getLocation(), diag::note_previous_declaration);
3486       return true;
3487     }
3488   }
3489 
3490   // FIXME: diagnose the other way around?
3491   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3492     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3493     RequiresAdjustment = true;
3494   }
3495 
3496   // Merge regparm attribute.
3497   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3498       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3499     if (NewTypeInfo.getHasRegParm()) {
3500       Diag(New->getLocation(), diag::err_regparm_mismatch)
3501         << NewType->getRegParmType()
3502         << OldType->getRegParmType();
3503       Diag(OldLocation, diag::note_previous_declaration);
3504       return true;
3505     }
3506 
3507     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3508     RequiresAdjustment = true;
3509   }
3510 
3511   // Merge ns_returns_retained attribute.
3512   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3513     if (NewTypeInfo.getProducesResult()) {
3514       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3515           << "'ns_returns_retained'";
3516       Diag(OldLocation, diag::note_previous_declaration);
3517       return true;
3518     }
3519 
3520     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3521     RequiresAdjustment = true;
3522   }
3523 
3524   if (OldTypeInfo.getNoCallerSavedRegs() !=
3525       NewTypeInfo.getNoCallerSavedRegs()) {
3526     if (NewTypeInfo.getNoCallerSavedRegs()) {
3527       AnyX86NoCallerSavedRegistersAttr *Attr =
3528         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3529       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3530       Diag(OldLocation, diag::note_previous_declaration);
3531       return true;
3532     }
3533 
3534     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3535     RequiresAdjustment = true;
3536   }
3537 
3538   if (RequiresAdjustment) {
3539     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3540     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3541     New->setType(QualType(AdjustedType, 0));
3542     NewQType = Context.getCanonicalType(New->getType());
3543   }
3544 
3545   // If this redeclaration makes the function inline, we may need to add it to
3546   // UndefinedButUsed.
3547   if (!Old->isInlined() && New->isInlined() &&
3548       !New->hasAttr<GNUInlineAttr>() &&
3549       !getLangOpts().GNUInline &&
3550       Old->isUsed(false) &&
3551       !Old->isDefined() && !New->isThisDeclarationADefinition())
3552     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3553                                            SourceLocation()));
3554 
3555   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3556   // about it.
3557   if (New->hasAttr<GNUInlineAttr>() &&
3558       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3559     UndefinedButUsed.erase(Old->getCanonicalDecl());
3560   }
3561 
3562   // If pass_object_size params don't match up perfectly, this isn't a valid
3563   // redeclaration.
3564   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3565       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3566     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3567         << New->getDeclName();
3568     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3569     return true;
3570   }
3571 
3572   if (getLangOpts().CPlusPlus) {
3573     // C++1z [over.load]p2
3574     //   Certain function declarations cannot be overloaded:
3575     //     -- Function declarations that differ only in the return type,
3576     //        the exception specification, or both cannot be overloaded.
3577 
3578     // Check the exception specifications match. This may recompute the type of
3579     // both Old and New if it resolved exception specifications, so grab the
3580     // types again after this. Because this updates the type, we do this before
3581     // any of the other checks below, which may update the "de facto" NewQType
3582     // but do not necessarily update the type of New.
3583     if (CheckEquivalentExceptionSpec(Old, New))
3584       return true;
3585     OldQType = Context.getCanonicalType(Old->getType());
3586     NewQType = Context.getCanonicalType(New->getType());
3587 
3588     // Go back to the type source info to compare the declared return types,
3589     // per C++1y [dcl.type.auto]p13:
3590     //   Redeclarations or specializations of a function or function template
3591     //   with a declared return type that uses a placeholder type shall also
3592     //   use that placeholder, not a deduced type.
3593     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3594     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3595     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3596         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3597                                        OldDeclaredReturnType)) {
3598       QualType ResQT;
3599       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3600           OldDeclaredReturnType->isObjCObjectPointerType())
3601         // FIXME: This does the wrong thing for a deduced return type.
3602         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3603       if (ResQT.isNull()) {
3604         if (New->isCXXClassMember() && New->isOutOfLine())
3605           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3606               << New << New->getReturnTypeSourceRange();
3607         else
3608           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3609               << New->getReturnTypeSourceRange();
3610         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3611                                     << Old->getReturnTypeSourceRange();
3612         return true;
3613       }
3614       else
3615         NewQType = ResQT;
3616     }
3617 
3618     QualType OldReturnType = OldType->getReturnType();
3619     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3620     if (OldReturnType != NewReturnType) {
3621       // If this function has a deduced return type and has already been
3622       // defined, copy the deduced value from the old declaration.
3623       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3624       if (OldAT && OldAT->isDeduced()) {
3625         QualType DT = OldAT->getDeducedType();
3626         if (DT.isNull()) {
3627           New->setType(SubstAutoTypeDependent(New->getType()));
3628           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3629         } else {
3630           New->setType(SubstAutoType(New->getType(), DT));
3631           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3632         }
3633       }
3634     }
3635 
3636     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3637     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3638     if (OldMethod && NewMethod) {
3639       // Preserve triviality.
3640       NewMethod->setTrivial(OldMethod->isTrivial());
3641 
3642       // MSVC allows explicit template specialization at class scope:
3643       // 2 CXXMethodDecls referring to the same function will be injected.
3644       // We don't want a redeclaration error.
3645       bool IsClassScopeExplicitSpecialization =
3646                               OldMethod->isFunctionTemplateSpecialization() &&
3647                               NewMethod->isFunctionTemplateSpecialization();
3648       bool isFriend = NewMethod->getFriendObjectKind();
3649 
3650       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3651           !IsClassScopeExplicitSpecialization) {
3652         //    -- Member function declarations with the same name and the
3653         //       same parameter types cannot be overloaded if any of them
3654         //       is a static member function declaration.
3655         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3656           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3657           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3658           return true;
3659         }
3660 
3661         // C++ [class.mem]p1:
3662         //   [...] A member shall not be declared twice in the
3663         //   member-specification, except that a nested class or member
3664         //   class template can be declared and then later defined.
3665         if (!inTemplateInstantiation()) {
3666           unsigned NewDiag;
3667           if (isa<CXXConstructorDecl>(OldMethod))
3668             NewDiag = diag::err_constructor_redeclared;
3669           else if (isa<CXXDestructorDecl>(NewMethod))
3670             NewDiag = diag::err_destructor_redeclared;
3671           else if (isa<CXXConversionDecl>(NewMethod))
3672             NewDiag = diag::err_conv_function_redeclared;
3673           else
3674             NewDiag = diag::err_member_redeclared;
3675 
3676           Diag(New->getLocation(), NewDiag);
3677         } else {
3678           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3679             << New << New->getType();
3680         }
3681         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3682         return true;
3683 
3684       // Complain if this is an explicit declaration of a special
3685       // member that was initially declared implicitly.
3686       //
3687       // As an exception, it's okay to befriend such methods in order
3688       // to permit the implicit constructor/destructor/operator calls.
3689       } else if (OldMethod->isImplicit()) {
3690         if (isFriend) {
3691           NewMethod->setImplicit();
3692         } else {
3693           Diag(NewMethod->getLocation(),
3694                diag::err_definition_of_implicitly_declared_member)
3695             << New << getSpecialMember(OldMethod);
3696           return true;
3697         }
3698       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3699         Diag(NewMethod->getLocation(),
3700              diag::err_definition_of_explicitly_defaulted_member)
3701           << getSpecialMember(OldMethod);
3702         return true;
3703       }
3704     }
3705 
3706     // C++11 [dcl.attr.noreturn]p1:
3707     //   The first declaration of a function shall specify the noreturn
3708     //   attribute if any declaration of that function specifies the noreturn
3709     //   attribute.
3710     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3711       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3712         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3713             << NRA;
3714         Diag(Old->getLocation(), diag::note_previous_declaration);
3715       }
3716 
3717     // C++11 [dcl.attr.depend]p2:
3718     //   The first declaration of a function shall specify the
3719     //   carries_dependency attribute for its declarator-id if any declaration
3720     //   of the function specifies the carries_dependency attribute.
3721     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3722     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3723       Diag(CDA->getLocation(),
3724            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3725       Diag(Old->getFirstDecl()->getLocation(),
3726            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3727     }
3728 
3729     // (C++98 8.3.5p3):
3730     //   All declarations for a function shall agree exactly in both the
3731     //   return type and the parameter-type-list.
3732     // We also want to respect all the extended bits except noreturn.
3733 
3734     // noreturn should now match unless the old type info didn't have it.
3735     QualType OldQTypeForComparison = OldQType;
3736     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3737       auto *OldType = OldQType->castAs<FunctionProtoType>();
3738       const FunctionType *OldTypeForComparison
3739         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3740       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3741       assert(OldQTypeForComparison.isCanonical());
3742     }
3743 
3744     if (haveIncompatibleLanguageLinkages(Old, New)) {
3745       // As a special case, retain the language linkage from previous
3746       // declarations of a friend function as an extension.
3747       //
3748       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3749       // and is useful because there's otherwise no way to specify language
3750       // linkage within class scope.
3751       //
3752       // Check cautiously as the friend object kind isn't yet complete.
3753       if (New->getFriendObjectKind() != Decl::FOK_None) {
3754         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3755         Diag(OldLocation, PrevDiag);
3756       } else {
3757         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3758         Diag(OldLocation, PrevDiag);
3759         return true;
3760       }
3761     }
3762 
3763     // If the function types are compatible, merge the declarations. Ignore the
3764     // exception specifier because it was already checked above in
3765     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3766     // about incompatible types under -fms-compatibility.
3767     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3768                                                          NewQType))
3769       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3770 
3771     // If the types are imprecise (due to dependent constructs in friends or
3772     // local extern declarations), it's OK if they differ. We'll check again
3773     // during instantiation.
3774     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3775       return false;
3776 
3777     // Fall through for conflicting redeclarations and redefinitions.
3778   }
3779 
3780   // C: Function types need to be compatible, not identical. This handles
3781   // duplicate function decls like "void f(int); void f(enum X);" properly.
3782   if (!getLangOpts().CPlusPlus &&
3783       Context.typesAreCompatible(OldQType, NewQType)) {
3784     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3785     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3786     const FunctionProtoType *OldProto = nullptr;
3787     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3788         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3789       // The old declaration provided a function prototype, but the
3790       // new declaration does not. Merge in the prototype.
3791       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3792       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3793       NewQType =
3794           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3795                                   OldProto->getExtProtoInfo());
3796       New->setType(NewQType);
3797       New->setHasInheritedPrototype();
3798 
3799       // Synthesize parameters with the same types.
3800       SmallVector<ParmVarDecl*, 16> Params;
3801       for (const auto &ParamType : OldProto->param_types()) {
3802         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3803                                                  SourceLocation(), nullptr,
3804                                                  ParamType, /*TInfo=*/nullptr,
3805                                                  SC_None, nullptr);
3806         Param->setScopeInfo(0, Params.size());
3807         Param->setImplicit();
3808         Params.push_back(Param);
3809       }
3810 
3811       New->setParams(Params);
3812     }
3813 
3814     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3815   }
3816 
3817   // Check if the function types are compatible when pointer size address
3818   // spaces are ignored.
3819   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3820     return false;
3821 
3822   // GNU C permits a K&R definition to follow a prototype declaration
3823   // if the declared types of the parameters in the K&R definition
3824   // match the types in the prototype declaration, even when the
3825   // promoted types of the parameters from the K&R definition differ
3826   // from the types in the prototype. GCC then keeps the types from
3827   // the prototype.
3828   //
3829   // If a variadic prototype is followed by a non-variadic K&R definition,
3830   // the K&R definition becomes variadic.  This is sort of an edge case, but
3831   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3832   // C99 6.9.1p8.
3833   if (!getLangOpts().CPlusPlus &&
3834       Old->hasPrototype() && !New->hasPrototype() &&
3835       New->getType()->getAs<FunctionProtoType>() &&
3836       Old->getNumParams() == New->getNumParams()) {
3837     SmallVector<QualType, 16> ArgTypes;
3838     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3839     const FunctionProtoType *OldProto
3840       = Old->getType()->getAs<FunctionProtoType>();
3841     const FunctionProtoType *NewProto
3842       = New->getType()->getAs<FunctionProtoType>();
3843 
3844     // Determine whether this is the GNU C extension.
3845     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3846                                                NewProto->getReturnType());
3847     bool LooseCompatible = !MergedReturn.isNull();
3848     for (unsigned Idx = 0, End = Old->getNumParams();
3849          LooseCompatible && Idx != End; ++Idx) {
3850       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3851       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3852       if (Context.typesAreCompatible(OldParm->getType(),
3853                                      NewProto->getParamType(Idx))) {
3854         ArgTypes.push_back(NewParm->getType());
3855       } else if (Context.typesAreCompatible(OldParm->getType(),
3856                                             NewParm->getType(),
3857                                             /*CompareUnqualified=*/true)) {
3858         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3859                                            NewProto->getParamType(Idx) };
3860         Warnings.push_back(Warn);
3861         ArgTypes.push_back(NewParm->getType());
3862       } else
3863         LooseCompatible = false;
3864     }
3865 
3866     if (LooseCompatible) {
3867       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3868         Diag(Warnings[Warn].NewParm->getLocation(),
3869              diag::ext_param_promoted_not_compatible_with_prototype)
3870           << Warnings[Warn].PromotedType
3871           << Warnings[Warn].OldParm->getType();
3872         if (Warnings[Warn].OldParm->getLocation().isValid())
3873           Diag(Warnings[Warn].OldParm->getLocation(),
3874                diag::note_previous_declaration);
3875       }
3876 
3877       if (MergeTypeWithOld)
3878         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3879                                              OldProto->getExtProtoInfo()));
3880       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3881     }
3882 
3883     // Fall through to diagnose conflicting types.
3884   }
3885 
3886   // A function that has already been declared has been redeclared or
3887   // defined with a different type; show an appropriate diagnostic.
3888 
3889   // If the previous declaration was an implicitly-generated builtin
3890   // declaration, then at the very least we should use a specialized note.
3891   unsigned BuiltinID;
3892   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3893     // If it's actually a library-defined builtin function like 'malloc'
3894     // or 'printf', just warn about the incompatible redeclaration.
3895     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3896       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3897       Diag(OldLocation, diag::note_previous_builtin_declaration)
3898         << Old << Old->getType();
3899       return false;
3900     }
3901 
3902     PrevDiag = diag::note_previous_builtin_declaration;
3903   }
3904 
3905   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3906   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3907   return true;
3908 }
3909 
3910 /// Completes the merge of two function declarations that are
3911 /// known to be compatible.
3912 ///
3913 /// This routine handles the merging of attributes and other
3914 /// properties of function declarations from the old declaration to
3915 /// the new declaration, once we know that New is in fact a
3916 /// redeclaration of Old.
3917 ///
3918 /// \returns false
3919 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3920                                         Scope *S, bool MergeTypeWithOld) {
3921   // Merge the attributes
3922   mergeDeclAttributes(New, Old);
3923 
3924   // Merge "pure" flag.
3925   if (Old->isPure())
3926     New->setPure();
3927 
3928   // Merge "used" flag.
3929   if (Old->getMostRecentDecl()->isUsed(false))
3930     New->setIsUsed();
3931 
3932   // Merge attributes from the parameters.  These can mismatch with K&R
3933   // declarations.
3934   if (New->getNumParams() == Old->getNumParams())
3935       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3936         ParmVarDecl *NewParam = New->getParamDecl(i);
3937         ParmVarDecl *OldParam = Old->getParamDecl(i);
3938         mergeParamDeclAttributes(NewParam, OldParam, *this);
3939         mergeParamDeclTypes(NewParam, OldParam, *this);
3940       }
3941 
3942   if (getLangOpts().CPlusPlus)
3943     return MergeCXXFunctionDecl(New, Old, S);
3944 
3945   // Merge the function types so the we get the composite types for the return
3946   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3947   // was visible.
3948   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3949   if (!Merged.isNull() && MergeTypeWithOld)
3950     New->setType(Merged);
3951 
3952   return false;
3953 }
3954 
3955 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3956                                 ObjCMethodDecl *oldMethod) {
3957   // Merge the attributes, including deprecated/unavailable
3958   AvailabilityMergeKind MergeKind =
3959       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3960           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3961                                      : AMK_ProtocolImplementation)
3962           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3963                                                            : AMK_Override;
3964 
3965   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3966 
3967   // Merge attributes from the parameters.
3968   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3969                                        oe = oldMethod->param_end();
3970   for (ObjCMethodDecl::param_iterator
3971          ni = newMethod->param_begin(), ne = newMethod->param_end();
3972        ni != ne && oi != oe; ++ni, ++oi)
3973     mergeParamDeclAttributes(*ni, *oi, *this);
3974 
3975   CheckObjCMethodOverride(newMethod, oldMethod);
3976 }
3977 
3978 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3979   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3980 
3981   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3982          ? diag::err_redefinition_different_type
3983          : diag::err_redeclaration_different_type)
3984     << New->getDeclName() << New->getType() << Old->getType();
3985 
3986   diag::kind PrevDiag;
3987   SourceLocation OldLocation;
3988   std::tie(PrevDiag, OldLocation)
3989     = getNoteDiagForInvalidRedeclaration(Old, New);
3990   S.Diag(OldLocation, PrevDiag);
3991   New->setInvalidDecl();
3992 }
3993 
3994 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3995 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3996 /// emitting diagnostics as appropriate.
3997 ///
3998 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3999 /// to here in AddInitializerToDecl. We can't check them before the initializer
4000 /// is attached.
4001 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4002                              bool MergeTypeWithOld) {
4003   if (New->isInvalidDecl() || Old->isInvalidDecl())
4004     return;
4005 
4006   QualType MergedT;
4007   if (getLangOpts().CPlusPlus) {
4008     if (New->getType()->isUndeducedType()) {
4009       // We don't know what the new type is until the initializer is attached.
4010       return;
4011     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4012       // These could still be something that needs exception specs checked.
4013       return MergeVarDeclExceptionSpecs(New, Old);
4014     }
4015     // C++ [basic.link]p10:
4016     //   [...] the types specified by all declarations referring to a given
4017     //   object or function shall be identical, except that declarations for an
4018     //   array object can specify array types that differ by the presence or
4019     //   absence of a major array bound (8.3.4).
4020     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4021       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4022       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4023 
4024       // We are merging a variable declaration New into Old. If it has an array
4025       // bound, and that bound differs from Old's bound, we should diagnose the
4026       // mismatch.
4027       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4028         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4029              PrevVD = PrevVD->getPreviousDecl()) {
4030           QualType PrevVDTy = PrevVD->getType();
4031           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4032             continue;
4033 
4034           if (!Context.hasSameType(New->getType(), PrevVDTy))
4035             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4036         }
4037       }
4038 
4039       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4040         if (Context.hasSameType(OldArray->getElementType(),
4041                                 NewArray->getElementType()))
4042           MergedT = New->getType();
4043       }
4044       // FIXME: Check visibility. New is hidden but has a complete type. If New
4045       // has no array bound, it should not inherit one from Old, if Old is not
4046       // visible.
4047       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4048         if (Context.hasSameType(OldArray->getElementType(),
4049                                 NewArray->getElementType()))
4050           MergedT = Old->getType();
4051       }
4052     }
4053     else if (New->getType()->isObjCObjectPointerType() &&
4054                Old->getType()->isObjCObjectPointerType()) {
4055       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4056                                               Old->getType());
4057     }
4058   } else {
4059     // C 6.2.7p2:
4060     //   All declarations that refer to the same object or function shall have
4061     //   compatible type.
4062     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4063   }
4064   if (MergedT.isNull()) {
4065     // It's OK if we couldn't merge types if either type is dependent, for a
4066     // block-scope variable. In other cases (static data members of class
4067     // templates, variable templates, ...), we require the types to be
4068     // equivalent.
4069     // FIXME: The C++ standard doesn't say anything about this.
4070     if ((New->getType()->isDependentType() ||
4071          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4072       // If the old type was dependent, we can't merge with it, so the new type
4073       // becomes dependent for now. We'll reproduce the original type when we
4074       // instantiate the TypeSourceInfo for the variable.
4075       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4076         New->setType(Context.DependentTy);
4077       return;
4078     }
4079     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4080   }
4081 
4082   // Don't actually update the type on the new declaration if the old
4083   // declaration was an extern declaration in a different scope.
4084   if (MergeTypeWithOld)
4085     New->setType(MergedT);
4086 }
4087 
4088 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4089                                   LookupResult &Previous) {
4090   // C11 6.2.7p4:
4091   //   For an identifier with internal or external linkage declared
4092   //   in a scope in which a prior declaration of that identifier is
4093   //   visible, if the prior declaration specifies internal or
4094   //   external linkage, the type of the identifier at the later
4095   //   declaration becomes the composite type.
4096   //
4097   // If the variable isn't visible, we do not merge with its type.
4098   if (Previous.isShadowed())
4099     return false;
4100 
4101   if (S.getLangOpts().CPlusPlus) {
4102     // C++11 [dcl.array]p3:
4103     //   If there is a preceding declaration of the entity in the same
4104     //   scope in which the bound was specified, an omitted array bound
4105     //   is taken to be the same as in that earlier declaration.
4106     return NewVD->isPreviousDeclInSameBlockScope() ||
4107            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4108             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4109   } else {
4110     // If the old declaration was function-local, don't merge with its
4111     // type unless we're in the same function.
4112     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4113            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4114   }
4115 }
4116 
4117 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4118 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4119 /// situation, merging decls or emitting diagnostics as appropriate.
4120 ///
4121 /// Tentative definition rules (C99 6.9.2p2) are checked by
4122 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4123 /// definitions here, since the initializer hasn't been attached.
4124 ///
4125 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4126   // If the new decl is already invalid, don't do any other checking.
4127   if (New->isInvalidDecl())
4128     return;
4129 
4130   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4131     return;
4132 
4133   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4134 
4135   // Verify the old decl was also a variable or variable template.
4136   VarDecl *Old = nullptr;
4137   VarTemplateDecl *OldTemplate = nullptr;
4138   if (Previous.isSingleResult()) {
4139     if (NewTemplate) {
4140       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4141       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4142 
4143       if (auto *Shadow =
4144               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4145         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4146           return New->setInvalidDecl();
4147     } else {
4148       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4149 
4150       if (auto *Shadow =
4151               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4152         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4153           return New->setInvalidDecl();
4154     }
4155   }
4156   if (!Old) {
4157     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4158         << New->getDeclName();
4159     notePreviousDefinition(Previous.getRepresentativeDecl(),
4160                            New->getLocation());
4161     return New->setInvalidDecl();
4162   }
4163 
4164   // If the old declaration was found in an inline namespace and the new
4165   // declaration was qualified, update the DeclContext to match.
4166   adjustDeclContextForDeclaratorDecl(New, Old);
4167 
4168   // Ensure the template parameters are compatible.
4169   if (NewTemplate &&
4170       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4171                                       OldTemplate->getTemplateParameters(),
4172                                       /*Complain=*/true, TPL_TemplateMatch))
4173     return New->setInvalidDecl();
4174 
4175   // C++ [class.mem]p1:
4176   //   A member shall not be declared twice in the member-specification [...]
4177   //
4178   // Here, we need only consider static data members.
4179   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4180     Diag(New->getLocation(), diag::err_duplicate_member)
4181       << New->getIdentifier();
4182     Diag(Old->getLocation(), diag::note_previous_declaration);
4183     New->setInvalidDecl();
4184   }
4185 
4186   mergeDeclAttributes(New, Old);
4187   // Warn if an already-declared variable is made a weak_import in a subsequent
4188   // declaration
4189   if (New->hasAttr<WeakImportAttr>() &&
4190       Old->getStorageClass() == SC_None &&
4191       !Old->hasAttr<WeakImportAttr>()) {
4192     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4193     Diag(Old->getLocation(), diag::note_previous_declaration);
4194     // Remove weak_import attribute on new declaration.
4195     New->dropAttr<WeakImportAttr>();
4196   }
4197 
4198   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4199     if (!Old->hasAttr<InternalLinkageAttr>()) {
4200       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4201           << ILA;
4202       Diag(Old->getLocation(), diag::note_previous_declaration);
4203       New->dropAttr<InternalLinkageAttr>();
4204     }
4205 
4206   // Merge the types.
4207   VarDecl *MostRecent = Old->getMostRecentDecl();
4208   if (MostRecent != Old) {
4209     MergeVarDeclTypes(New, MostRecent,
4210                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4211     if (New->isInvalidDecl())
4212       return;
4213   }
4214 
4215   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4216   if (New->isInvalidDecl())
4217     return;
4218 
4219   diag::kind PrevDiag;
4220   SourceLocation OldLocation;
4221   std::tie(PrevDiag, OldLocation) =
4222       getNoteDiagForInvalidRedeclaration(Old, New);
4223 
4224   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4225   if (New->getStorageClass() == SC_Static &&
4226       !New->isStaticDataMember() &&
4227       Old->hasExternalFormalLinkage()) {
4228     if (getLangOpts().MicrosoftExt) {
4229       Diag(New->getLocation(), diag::ext_static_non_static)
4230           << New->getDeclName();
4231       Diag(OldLocation, PrevDiag);
4232     } else {
4233       Diag(New->getLocation(), diag::err_static_non_static)
4234           << New->getDeclName();
4235       Diag(OldLocation, PrevDiag);
4236       return New->setInvalidDecl();
4237     }
4238   }
4239   // C99 6.2.2p4:
4240   //   For an identifier declared with the storage-class specifier
4241   //   extern in a scope in which a prior declaration of that
4242   //   identifier is visible,23) if the prior declaration specifies
4243   //   internal or external linkage, the linkage of the identifier at
4244   //   the later declaration is the same as the linkage specified at
4245   //   the prior declaration. If no prior declaration is visible, or
4246   //   if the prior declaration specifies no linkage, then the
4247   //   identifier has external linkage.
4248   if (New->hasExternalStorage() && Old->hasLinkage())
4249     /* Okay */;
4250   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4251            !New->isStaticDataMember() &&
4252            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4253     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4254     Diag(OldLocation, PrevDiag);
4255     return New->setInvalidDecl();
4256   }
4257 
4258   // Check if extern is followed by non-extern and vice-versa.
4259   if (New->hasExternalStorage() &&
4260       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4261     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4262     Diag(OldLocation, PrevDiag);
4263     return New->setInvalidDecl();
4264   }
4265   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4266       !New->hasExternalStorage()) {
4267     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4268     Diag(OldLocation, PrevDiag);
4269     return New->setInvalidDecl();
4270   }
4271 
4272   if (CheckRedeclarationModuleOwnership(New, Old))
4273     return;
4274 
4275   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4276 
4277   // FIXME: The test for external storage here seems wrong? We still
4278   // need to check for mismatches.
4279   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4280       // Don't complain about out-of-line definitions of static members.
4281       !(Old->getLexicalDeclContext()->isRecord() &&
4282         !New->getLexicalDeclContext()->isRecord())) {
4283     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4284     Diag(OldLocation, PrevDiag);
4285     return New->setInvalidDecl();
4286   }
4287 
4288   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4289     if (VarDecl *Def = Old->getDefinition()) {
4290       // C++1z [dcl.fcn.spec]p4:
4291       //   If the definition of a variable appears in a translation unit before
4292       //   its first declaration as inline, the program is ill-formed.
4293       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4294       Diag(Def->getLocation(), diag::note_previous_definition);
4295     }
4296   }
4297 
4298   // If this redeclaration makes the variable inline, we may need to add it to
4299   // UndefinedButUsed.
4300   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4301       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4302     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4303                                            SourceLocation()));
4304 
4305   if (New->getTLSKind() != Old->getTLSKind()) {
4306     if (!Old->getTLSKind()) {
4307       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4308       Diag(OldLocation, PrevDiag);
4309     } else if (!New->getTLSKind()) {
4310       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4311       Diag(OldLocation, PrevDiag);
4312     } else {
4313       // Do not allow redeclaration to change the variable between requiring
4314       // static and dynamic initialization.
4315       // FIXME: GCC allows this, but uses the TLS keyword on the first
4316       // declaration to determine the kind. Do we need to be compatible here?
4317       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4318         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4319       Diag(OldLocation, PrevDiag);
4320     }
4321   }
4322 
4323   // C++ doesn't have tentative definitions, so go right ahead and check here.
4324   if (getLangOpts().CPlusPlus &&
4325       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4326     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4327         Old->getCanonicalDecl()->isConstexpr()) {
4328       // This definition won't be a definition any more once it's been merged.
4329       Diag(New->getLocation(),
4330            diag::warn_deprecated_redundant_constexpr_static_def);
4331     } else if (VarDecl *Def = Old->getDefinition()) {
4332       if (checkVarDeclRedefinition(Def, New))
4333         return;
4334     }
4335   }
4336 
4337   if (haveIncompatibleLanguageLinkages(Old, New)) {
4338     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4339     Diag(OldLocation, PrevDiag);
4340     New->setInvalidDecl();
4341     return;
4342   }
4343 
4344   // Merge "used" flag.
4345   if (Old->getMostRecentDecl()->isUsed(false))
4346     New->setIsUsed();
4347 
4348   // Keep a chain of previous declarations.
4349   New->setPreviousDecl(Old);
4350   if (NewTemplate)
4351     NewTemplate->setPreviousDecl(OldTemplate);
4352 
4353   // Inherit access appropriately.
4354   New->setAccess(Old->getAccess());
4355   if (NewTemplate)
4356     NewTemplate->setAccess(New->getAccess());
4357 
4358   if (Old->isInline())
4359     New->setImplicitlyInline();
4360 }
4361 
4362 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4363   SourceManager &SrcMgr = getSourceManager();
4364   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4365   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4366   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4367   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4368   auto &HSI = PP.getHeaderSearchInfo();
4369   StringRef HdrFilename =
4370       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4371 
4372   auto noteFromModuleOrInclude = [&](Module *Mod,
4373                                      SourceLocation IncLoc) -> bool {
4374     // Redefinition errors with modules are common with non modular mapped
4375     // headers, example: a non-modular header H in module A that also gets
4376     // included directly in a TU. Pointing twice to the same header/definition
4377     // is confusing, try to get better diagnostics when modules is on.
4378     if (IncLoc.isValid()) {
4379       if (Mod) {
4380         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4381             << HdrFilename.str() << Mod->getFullModuleName();
4382         if (!Mod->DefinitionLoc.isInvalid())
4383           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4384               << Mod->getFullModuleName();
4385       } else {
4386         Diag(IncLoc, diag::note_redefinition_include_same_file)
4387             << HdrFilename.str();
4388       }
4389       return true;
4390     }
4391 
4392     return false;
4393   };
4394 
4395   // Is it the same file and same offset? Provide more information on why
4396   // this leads to a redefinition error.
4397   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4398     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4399     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4400     bool EmittedDiag =
4401         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4402     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4403 
4404     // If the header has no guards, emit a note suggesting one.
4405     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4406       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4407 
4408     if (EmittedDiag)
4409       return;
4410   }
4411 
4412   // Redefinition coming from different files or couldn't do better above.
4413   if (Old->getLocation().isValid())
4414     Diag(Old->getLocation(), diag::note_previous_definition);
4415 }
4416 
4417 /// We've just determined that \p Old and \p New both appear to be definitions
4418 /// of the same variable. Either diagnose or fix the problem.
4419 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4420   if (!hasVisibleDefinition(Old) &&
4421       (New->getFormalLinkage() == InternalLinkage ||
4422        New->isInline() ||
4423        New->getDescribedVarTemplate() ||
4424        New->getNumTemplateParameterLists() ||
4425        New->getDeclContext()->isDependentContext())) {
4426     // The previous definition is hidden, and multiple definitions are
4427     // permitted (in separate TUs). Demote this to a declaration.
4428     New->demoteThisDefinitionToDeclaration();
4429 
4430     // Make the canonical definition visible.
4431     if (auto *OldTD = Old->getDescribedVarTemplate())
4432       makeMergedDefinitionVisible(OldTD);
4433     makeMergedDefinitionVisible(Old);
4434     return false;
4435   } else {
4436     Diag(New->getLocation(), diag::err_redefinition) << New;
4437     notePreviousDefinition(Old, New->getLocation());
4438     New->setInvalidDecl();
4439     return true;
4440   }
4441 }
4442 
4443 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4444 /// no declarator (e.g. "struct foo;") is parsed.
4445 Decl *
4446 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4447                                  RecordDecl *&AnonRecord) {
4448   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4449                                     AnonRecord);
4450 }
4451 
4452 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4453 // disambiguate entities defined in different scopes.
4454 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4455 // compatibility.
4456 // We will pick our mangling number depending on which version of MSVC is being
4457 // targeted.
4458 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4459   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4460              ? S->getMSCurManglingNumber()
4461              : S->getMSLastManglingNumber();
4462 }
4463 
4464 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4465   if (!Context.getLangOpts().CPlusPlus)
4466     return;
4467 
4468   if (isa<CXXRecordDecl>(Tag->getParent())) {
4469     // If this tag is the direct child of a class, number it if
4470     // it is anonymous.
4471     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4472       return;
4473     MangleNumberingContext &MCtx =
4474         Context.getManglingNumberContext(Tag->getParent());
4475     Context.setManglingNumber(
4476         Tag, MCtx.getManglingNumber(
4477                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4478     return;
4479   }
4480 
4481   // If this tag isn't a direct child of a class, number it if it is local.
4482   MangleNumberingContext *MCtx;
4483   Decl *ManglingContextDecl;
4484   std::tie(MCtx, ManglingContextDecl) =
4485       getCurrentMangleNumberContext(Tag->getDeclContext());
4486   if (MCtx) {
4487     Context.setManglingNumber(
4488         Tag, MCtx->getManglingNumber(
4489                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4490   }
4491 }
4492 
4493 namespace {
4494 struct NonCLikeKind {
4495   enum {
4496     None,
4497     BaseClass,
4498     DefaultMemberInit,
4499     Lambda,
4500     Friend,
4501     OtherMember,
4502     Invalid,
4503   } Kind = None;
4504   SourceRange Range;
4505 
4506   explicit operator bool() { return Kind != None; }
4507 };
4508 }
4509 
4510 /// Determine whether a class is C-like, according to the rules of C++
4511 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4512 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4513   if (RD->isInvalidDecl())
4514     return {NonCLikeKind::Invalid, {}};
4515 
4516   // C++ [dcl.typedef]p9: [P1766R1]
4517   //   An unnamed class with a typedef name for linkage purposes shall not
4518   //
4519   //    -- have any base classes
4520   if (RD->getNumBases())
4521     return {NonCLikeKind::BaseClass,
4522             SourceRange(RD->bases_begin()->getBeginLoc(),
4523                         RD->bases_end()[-1].getEndLoc())};
4524   bool Invalid = false;
4525   for (Decl *D : RD->decls()) {
4526     // Don't complain about things we already diagnosed.
4527     if (D->isInvalidDecl()) {
4528       Invalid = true;
4529       continue;
4530     }
4531 
4532     //  -- have any [...] default member initializers
4533     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4534       if (FD->hasInClassInitializer()) {
4535         auto *Init = FD->getInClassInitializer();
4536         return {NonCLikeKind::DefaultMemberInit,
4537                 Init ? Init->getSourceRange() : D->getSourceRange()};
4538       }
4539       continue;
4540     }
4541 
4542     // FIXME: We don't allow friend declarations. This violates the wording of
4543     // P1766, but not the intent.
4544     if (isa<FriendDecl>(D))
4545       return {NonCLikeKind::Friend, D->getSourceRange()};
4546 
4547     //  -- declare any members other than non-static data members, member
4548     //     enumerations, or member classes,
4549     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4550         isa<EnumDecl>(D))
4551       continue;
4552     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4553     if (!MemberRD) {
4554       if (D->isImplicit())
4555         continue;
4556       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4557     }
4558 
4559     //  -- contain a lambda-expression,
4560     if (MemberRD->isLambda())
4561       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4562 
4563     //  and all member classes shall also satisfy these requirements
4564     //  (recursively).
4565     if (MemberRD->isThisDeclarationADefinition()) {
4566       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4567         return Kind;
4568     }
4569   }
4570 
4571   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4572 }
4573 
4574 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4575                                         TypedefNameDecl *NewTD) {
4576   if (TagFromDeclSpec->isInvalidDecl())
4577     return;
4578 
4579   // Do nothing if the tag already has a name for linkage purposes.
4580   if (TagFromDeclSpec->hasNameForLinkage())
4581     return;
4582 
4583   // A well-formed anonymous tag must always be a TUK_Definition.
4584   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4585 
4586   // The type must match the tag exactly;  no qualifiers allowed.
4587   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4588                            Context.getTagDeclType(TagFromDeclSpec))) {
4589     if (getLangOpts().CPlusPlus)
4590       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4591     return;
4592   }
4593 
4594   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4595   //   An unnamed class with a typedef name for linkage purposes shall [be
4596   //   C-like].
4597   //
4598   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4599   // shouldn't happen, but there are constructs that the language rule doesn't
4600   // disallow for which we can't reasonably avoid computing linkage early.
4601   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4602   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4603                              : NonCLikeKind();
4604   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4605   if (NonCLike || ChangesLinkage) {
4606     if (NonCLike.Kind == NonCLikeKind::Invalid)
4607       return;
4608 
4609     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4610     if (ChangesLinkage) {
4611       // If the linkage changes, we can't accept this as an extension.
4612       if (NonCLike.Kind == NonCLikeKind::None)
4613         DiagID = diag::err_typedef_changes_linkage;
4614       else
4615         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4616     }
4617 
4618     SourceLocation FixitLoc =
4619         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4620     llvm::SmallString<40> TextToInsert;
4621     TextToInsert += ' ';
4622     TextToInsert += NewTD->getIdentifier()->getName();
4623 
4624     Diag(FixitLoc, DiagID)
4625       << isa<TypeAliasDecl>(NewTD)
4626       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4627     if (NonCLike.Kind != NonCLikeKind::None) {
4628       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4629         << NonCLike.Kind - 1 << NonCLike.Range;
4630     }
4631     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4632       << NewTD << isa<TypeAliasDecl>(NewTD);
4633 
4634     if (ChangesLinkage)
4635       return;
4636   }
4637 
4638   // Otherwise, set this as the anon-decl typedef for the tag.
4639   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4640 }
4641 
4642 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4643   switch (T) {
4644   case DeclSpec::TST_class:
4645     return 0;
4646   case DeclSpec::TST_struct:
4647     return 1;
4648   case DeclSpec::TST_interface:
4649     return 2;
4650   case DeclSpec::TST_union:
4651     return 3;
4652   case DeclSpec::TST_enum:
4653     return 4;
4654   default:
4655     llvm_unreachable("unexpected type specifier");
4656   }
4657 }
4658 
4659 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4660 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4661 /// parameters to cope with template friend declarations.
4662 Decl *
4663 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4664                                  MultiTemplateParamsArg TemplateParams,
4665                                  bool IsExplicitInstantiation,
4666                                  RecordDecl *&AnonRecord) {
4667   Decl *TagD = nullptr;
4668   TagDecl *Tag = nullptr;
4669   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4670       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4671       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4672       DS.getTypeSpecType() == DeclSpec::TST_union ||
4673       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4674     TagD = DS.getRepAsDecl();
4675 
4676     if (!TagD) // We probably had an error
4677       return nullptr;
4678 
4679     // Note that the above type specs guarantee that the
4680     // type rep is a Decl, whereas in many of the others
4681     // it's a Type.
4682     if (isa<TagDecl>(TagD))
4683       Tag = cast<TagDecl>(TagD);
4684     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4685       Tag = CTD->getTemplatedDecl();
4686   }
4687 
4688   if (Tag) {
4689     handleTagNumbering(Tag, S);
4690     Tag->setFreeStanding();
4691     if (Tag->isInvalidDecl())
4692       return Tag;
4693   }
4694 
4695   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4696     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4697     // or incomplete types shall not be restrict-qualified."
4698     if (TypeQuals & DeclSpec::TQ_restrict)
4699       Diag(DS.getRestrictSpecLoc(),
4700            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4701            << DS.getSourceRange();
4702   }
4703 
4704   if (DS.isInlineSpecified())
4705     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4706         << getLangOpts().CPlusPlus17;
4707 
4708   if (DS.hasConstexprSpecifier()) {
4709     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4710     // and definitions of functions and variables.
4711     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4712     // the declaration of a function or function template
4713     if (Tag)
4714       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4715           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4716           << static_cast<int>(DS.getConstexprSpecifier());
4717     else
4718       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4719           << static_cast<int>(DS.getConstexprSpecifier());
4720     // Don't emit warnings after this error.
4721     return TagD;
4722   }
4723 
4724   DiagnoseFunctionSpecifiers(DS);
4725 
4726   if (DS.isFriendSpecified()) {
4727     // If we're dealing with a decl but not a TagDecl, assume that
4728     // whatever routines created it handled the friendship aspect.
4729     if (TagD && !Tag)
4730       return nullptr;
4731     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4732   }
4733 
4734   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4735   bool IsExplicitSpecialization =
4736     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4737   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4738       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4739       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4740     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4741     // nested-name-specifier unless it is an explicit instantiation
4742     // or an explicit specialization.
4743     //
4744     // FIXME: We allow class template partial specializations here too, per the
4745     // obvious intent of DR1819.
4746     //
4747     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4748     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4749         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4750     return nullptr;
4751   }
4752 
4753   // Track whether this decl-specifier declares anything.
4754   bool DeclaresAnything = true;
4755 
4756   // Handle anonymous struct definitions.
4757   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4758     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4759         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4760       if (getLangOpts().CPlusPlus ||
4761           Record->getDeclContext()->isRecord()) {
4762         // If CurContext is a DeclContext that can contain statements,
4763         // RecursiveASTVisitor won't visit the decls that
4764         // BuildAnonymousStructOrUnion() will put into CurContext.
4765         // Also store them here so that they can be part of the
4766         // DeclStmt that gets created in this case.
4767         // FIXME: Also return the IndirectFieldDecls created by
4768         // BuildAnonymousStructOr union, for the same reason?
4769         if (CurContext->isFunctionOrMethod())
4770           AnonRecord = Record;
4771         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4772                                            Context.getPrintingPolicy());
4773       }
4774 
4775       DeclaresAnything = false;
4776     }
4777   }
4778 
4779   // C11 6.7.2.1p2:
4780   //   A struct-declaration that does not declare an anonymous structure or
4781   //   anonymous union shall contain a struct-declarator-list.
4782   //
4783   // This rule also existed in C89 and C99; the grammar for struct-declaration
4784   // did not permit a struct-declaration without a struct-declarator-list.
4785   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4786       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4787     // Check for Microsoft C extension: anonymous struct/union member.
4788     // Handle 2 kinds of anonymous struct/union:
4789     //   struct STRUCT;
4790     //   union UNION;
4791     // and
4792     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4793     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4794     if ((Tag && Tag->getDeclName()) ||
4795         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4796       RecordDecl *Record = nullptr;
4797       if (Tag)
4798         Record = dyn_cast<RecordDecl>(Tag);
4799       else if (const RecordType *RT =
4800                    DS.getRepAsType().get()->getAsStructureType())
4801         Record = RT->getDecl();
4802       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4803         Record = UT->getDecl();
4804 
4805       if (Record && getLangOpts().MicrosoftExt) {
4806         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4807             << Record->isUnion() << DS.getSourceRange();
4808         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4809       }
4810 
4811       DeclaresAnything = false;
4812     }
4813   }
4814 
4815   // Skip all the checks below if we have a type error.
4816   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4817       (TagD && TagD->isInvalidDecl()))
4818     return TagD;
4819 
4820   if (getLangOpts().CPlusPlus &&
4821       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4822     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4823       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4824           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4825         DeclaresAnything = false;
4826 
4827   if (!DS.isMissingDeclaratorOk()) {
4828     // Customize diagnostic for a typedef missing a name.
4829     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4830       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4831           << DS.getSourceRange();
4832     else
4833       DeclaresAnything = false;
4834   }
4835 
4836   if (DS.isModulePrivateSpecified() &&
4837       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4838     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4839       << Tag->getTagKind()
4840       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4841 
4842   ActOnDocumentableDecl(TagD);
4843 
4844   // C 6.7/2:
4845   //   A declaration [...] shall declare at least a declarator [...], a tag,
4846   //   or the members of an enumeration.
4847   // C++ [dcl.dcl]p3:
4848   //   [If there are no declarators], and except for the declaration of an
4849   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4850   //   names into the program, or shall redeclare a name introduced by a
4851   //   previous declaration.
4852   if (!DeclaresAnything) {
4853     // In C, we allow this as a (popular) extension / bug. Don't bother
4854     // producing further diagnostics for redundant qualifiers after this.
4855     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4856                                ? diag::err_no_declarators
4857                                : diag::ext_no_declarators)
4858         << DS.getSourceRange();
4859     return TagD;
4860   }
4861 
4862   // C++ [dcl.stc]p1:
4863   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4864   //   init-declarator-list of the declaration shall not be empty.
4865   // C++ [dcl.fct.spec]p1:
4866   //   If a cv-qualifier appears in a decl-specifier-seq, the
4867   //   init-declarator-list of the declaration shall not be empty.
4868   //
4869   // Spurious qualifiers here appear to be valid in C.
4870   unsigned DiagID = diag::warn_standalone_specifier;
4871   if (getLangOpts().CPlusPlus)
4872     DiagID = diag::ext_standalone_specifier;
4873 
4874   // Note that a linkage-specification sets a storage class, but
4875   // 'extern "C" struct foo;' is actually valid and not theoretically
4876   // useless.
4877   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4878     if (SCS == DeclSpec::SCS_mutable)
4879       // Since mutable is not a viable storage class specifier in C, there is
4880       // no reason to treat it as an extension. Instead, diagnose as an error.
4881       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4882     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4883       Diag(DS.getStorageClassSpecLoc(), DiagID)
4884         << DeclSpec::getSpecifierName(SCS);
4885   }
4886 
4887   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4888     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4889       << DeclSpec::getSpecifierName(TSCS);
4890   if (DS.getTypeQualifiers()) {
4891     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4892       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4893     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4894       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4895     // Restrict is covered above.
4896     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4897       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4898     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4899       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4900   }
4901 
4902   // Warn about ignored type attributes, for example:
4903   // __attribute__((aligned)) struct A;
4904   // Attributes should be placed after tag to apply to type declaration.
4905   if (!DS.getAttributes().empty()) {
4906     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4907     if (TypeSpecType == DeclSpec::TST_class ||
4908         TypeSpecType == DeclSpec::TST_struct ||
4909         TypeSpecType == DeclSpec::TST_interface ||
4910         TypeSpecType == DeclSpec::TST_union ||
4911         TypeSpecType == DeclSpec::TST_enum) {
4912       for (const ParsedAttr &AL : DS.getAttributes())
4913         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4914             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4915     }
4916   }
4917 
4918   return TagD;
4919 }
4920 
4921 /// We are trying to inject an anonymous member into the given scope;
4922 /// check if there's an existing declaration that can't be overloaded.
4923 ///
4924 /// \return true if this is a forbidden redeclaration
4925 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4926                                          Scope *S,
4927                                          DeclContext *Owner,
4928                                          DeclarationName Name,
4929                                          SourceLocation NameLoc,
4930                                          bool IsUnion) {
4931   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4932                  Sema::ForVisibleRedeclaration);
4933   if (!SemaRef.LookupName(R, S)) return false;
4934 
4935   // Pick a representative declaration.
4936   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4937   assert(PrevDecl && "Expected a non-null Decl");
4938 
4939   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4940     return false;
4941 
4942   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4943     << IsUnion << Name;
4944   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4945 
4946   return true;
4947 }
4948 
4949 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4950 /// anonymous struct or union AnonRecord into the owning context Owner
4951 /// and scope S. This routine will be invoked just after we realize
4952 /// that an unnamed union or struct is actually an anonymous union or
4953 /// struct, e.g.,
4954 ///
4955 /// @code
4956 /// union {
4957 ///   int i;
4958 ///   float f;
4959 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4960 ///    // f into the surrounding scope.x
4961 /// @endcode
4962 ///
4963 /// This routine is recursive, injecting the names of nested anonymous
4964 /// structs/unions into the owning context and scope as well.
4965 static bool
4966 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4967                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4968                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4969   bool Invalid = false;
4970 
4971   // Look every FieldDecl and IndirectFieldDecl with a name.
4972   for (auto *D : AnonRecord->decls()) {
4973     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4974         cast<NamedDecl>(D)->getDeclName()) {
4975       ValueDecl *VD = cast<ValueDecl>(D);
4976       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4977                                        VD->getLocation(),
4978                                        AnonRecord->isUnion())) {
4979         // C++ [class.union]p2:
4980         //   The names of the members of an anonymous union shall be
4981         //   distinct from the names of any other entity in the
4982         //   scope in which the anonymous union is declared.
4983         Invalid = true;
4984       } else {
4985         // C++ [class.union]p2:
4986         //   For the purpose of name lookup, after the anonymous union
4987         //   definition, the members of the anonymous union are
4988         //   considered to have been defined in the scope in which the
4989         //   anonymous union is declared.
4990         unsigned OldChainingSize = Chaining.size();
4991         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4992           Chaining.append(IF->chain_begin(), IF->chain_end());
4993         else
4994           Chaining.push_back(VD);
4995 
4996         assert(Chaining.size() >= 2);
4997         NamedDecl **NamedChain =
4998           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4999         for (unsigned i = 0; i < Chaining.size(); i++)
5000           NamedChain[i] = Chaining[i];
5001 
5002         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5003             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5004             VD->getType(), {NamedChain, Chaining.size()});
5005 
5006         for (const auto *Attr : VD->attrs())
5007           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5008 
5009         IndirectField->setAccess(AS);
5010         IndirectField->setImplicit();
5011         SemaRef.PushOnScopeChains(IndirectField, S);
5012 
5013         // That includes picking up the appropriate access specifier.
5014         if (AS != AS_none) IndirectField->setAccess(AS);
5015 
5016         Chaining.resize(OldChainingSize);
5017       }
5018     }
5019   }
5020 
5021   return Invalid;
5022 }
5023 
5024 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5025 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5026 /// illegal input values are mapped to SC_None.
5027 static StorageClass
5028 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5029   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5030   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5031          "Parser allowed 'typedef' as storage class VarDecl.");
5032   switch (StorageClassSpec) {
5033   case DeclSpec::SCS_unspecified:    return SC_None;
5034   case DeclSpec::SCS_extern:
5035     if (DS.isExternInLinkageSpec())
5036       return SC_None;
5037     return SC_Extern;
5038   case DeclSpec::SCS_static:         return SC_Static;
5039   case DeclSpec::SCS_auto:           return SC_Auto;
5040   case DeclSpec::SCS_register:       return SC_Register;
5041   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5042     // Illegal SCSs map to None: error reporting is up to the caller.
5043   case DeclSpec::SCS_mutable:        // Fall through.
5044   case DeclSpec::SCS_typedef:        return SC_None;
5045   }
5046   llvm_unreachable("unknown storage class specifier");
5047 }
5048 
5049 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5050   assert(Record->hasInClassInitializer());
5051 
5052   for (const auto *I : Record->decls()) {
5053     const auto *FD = dyn_cast<FieldDecl>(I);
5054     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5055       FD = IFD->getAnonField();
5056     if (FD && FD->hasInClassInitializer())
5057       return FD->getLocation();
5058   }
5059 
5060   llvm_unreachable("couldn't find in-class initializer");
5061 }
5062 
5063 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5064                                       SourceLocation DefaultInitLoc) {
5065   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5066     return;
5067 
5068   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5069   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5070 }
5071 
5072 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5073                                       CXXRecordDecl *AnonUnion) {
5074   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5075     return;
5076 
5077   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5078 }
5079 
5080 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5081 /// anonymous structure or union. Anonymous unions are a C++ feature
5082 /// (C++ [class.union]) and a C11 feature; anonymous structures
5083 /// are a C11 feature and GNU C++ extension.
5084 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5085                                         AccessSpecifier AS,
5086                                         RecordDecl *Record,
5087                                         const PrintingPolicy &Policy) {
5088   DeclContext *Owner = Record->getDeclContext();
5089 
5090   // Diagnose whether this anonymous struct/union is an extension.
5091   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5092     Diag(Record->getLocation(), diag::ext_anonymous_union);
5093   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5094     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5095   else if (!Record->isUnion() && !getLangOpts().C11)
5096     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5097 
5098   // C and C++ require different kinds of checks for anonymous
5099   // structs/unions.
5100   bool Invalid = false;
5101   if (getLangOpts().CPlusPlus) {
5102     const char *PrevSpec = nullptr;
5103     if (Record->isUnion()) {
5104       // C++ [class.union]p6:
5105       // C++17 [class.union.anon]p2:
5106       //   Anonymous unions declared in a named namespace or in the
5107       //   global namespace shall be declared static.
5108       unsigned DiagID;
5109       DeclContext *OwnerScope = Owner->getRedeclContext();
5110       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5111           (OwnerScope->isTranslationUnit() ||
5112            (OwnerScope->isNamespace() &&
5113             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5114         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5115           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5116 
5117         // Recover by adding 'static'.
5118         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5119                                PrevSpec, DiagID, Policy);
5120       }
5121       // C++ [class.union]p6:
5122       //   A storage class is not allowed in a declaration of an
5123       //   anonymous union in a class scope.
5124       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5125                isa<RecordDecl>(Owner)) {
5126         Diag(DS.getStorageClassSpecLoc(),
5127              diag::err_anonymous_union_with_storage_spec)
5128           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5129 
5130         // Recover by removing the storage specifier.
5131         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5132                                SourceLocation(),
5133                                PrevSpec, DiagID, Context.getPrintingPolicy());
5134       }
5135     }
5136 
5137     // Ignore const/volatile/restrict qualifiers.
5138     if (DS.getTypeQualifiers()) {
5139       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5140         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5141           << Record->isUnion() << "const"
5142           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5143       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5144         Diag(DS.getVolatileSpecLoc(),
5145              diag::ext_anonymous_struct_union_qualified)
5146           << Record->isUnion() << "volatile"
5147           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5148       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5149         Diag(DS.getRestrictSpecLoc(),
5150              diag::ext_anonymous_struct_union_qualified)
5151           << Record->isUnion() << "restrict"
5152           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5153       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5154         Diag(DS.getAtomicSpecLoc(),
5155              diag::ext_anonymous_struct_union_qualified)
5156           << Record->isUnion() << "_Atomic"
5157           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5158       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5159         Diag(DS.getUnalignedSpecLoc(),
5160              diag::ext_anonymous_struct_union_qualified)
5161           << Record->isUnion() << "__unaligned"
5162           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5163 
5164       DS.ClearTypeQualifiers();
5165     }
5166 
5167     // C++ [class.union]p2:
5168     //   The member-specification of an anonymous union shall only
5169     //   define non-static data members. [Note: nested types and
5170     //   functions cannot be declared within an anonymous union. ]
5171     for (auto *Mem : Record->decls()) {
5172       // Ignore invalid declarations; we already diagnosed them.
5173       if (Mem->isInvalidDecl())
5174         continue;
5175 
5176       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5177         // C++ [class.union]p3:
5178         //   An anonymous union shall not have private or protected
5179         //   members (clause 11).
5180         assert(FD->getAccess() != AS_none);
5181         if (FD->getAccess() != AS_public) {
5182           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5183             << Record->isUnion() << (FD->getAccess() == AS_protected);
5184           Invalid = true;
5185         }
5186 
5187         // C++ [class.union]p1
5188         //   An object of a class with a non-trivial constructor, a non-trivial
5189         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5190         //   assignment operator cannot be a member of a union, nor can an
5191         //   array of such objects.
5192         if (CheckNontrivialField(FD))
5193           Invalid = true;
5194       } else if (Mem->isImplicit()) {
5195         // Any implicit members are fine.
5196       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5197         // This is a type that showed up in an
5198         // elaborated-type-specifier inside the anonymous struct or
5199         // union, but which actually declares a type outside of the
5200         // anonymous struct or union. It's okay.
5201       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5202         if (!MemRecord->isAnonymousStructOrUnion() &&
5203             MemRecord->getDeclName()) {
5204           // Visual C++ allows type definition in anonymous struct or union.
5205           if (getLangOpts().MicrosoftExt)
5206             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5207               << Record->isUnion();
5208           else {
5209             // This is a nested type declaration.
5210             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5211               << Record->isUnion();
5212             Invalid = true;
5213           }
5214         } else {
5215           // This is an anonymous type definition within another anonymous type.
5216           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5217           // not part of standard C++.
5218           Diag(MemRecord->getLocation(),
5219                diag::ext_anonymous_record_with_anonymous_type)
5220             << Record->isUnion();
5221         }
5222       } else if (isa<AccessSpecDecl>(Mem)) {
5223         // Any access specifier is fine.
5224       } else if (isa<StaticAssertDecl>(Mem)) {
5225         // In C++1z, static_assert declarations are also fine.
5226       } else {
5227         // We have something that isn't a non-static data
5228         // member. Complain about it.
5229         unsigned DK = diag::err_anonymous_record_bad_member;
5230         if (isa<TypeDecl>(Mem))
5231           DK = diag::err_anonymous_record_with_type;
5232         else if (isa<FunctionDecl>(Mem))
5233           DK = diag::err_anonymous_record_with_function;
5234         else if (isa<VarDecl>(Mem))
5235           DK = diag::err_anonymous_record_with_static;
5236 
5237         // Visual C++ allows type definition in anonymous struct or union.
5238         if (getLangOpts().MicrosoftExt &&
5239             DK == diag::err_anonymous_record_with_type)
5240           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5241             << Record->isUnion();
5242         else {
5243           Diag(Mem->getLocation(), DK) << Record->isUnion();
5244           Invalid = true;
5245         }
5246       }
5247     }
5248 
5249     // C++11 [class.union]p8 (DR1460):
5250     //   At most one variant member of a union may have a
5251     //   brace-or-equal-initializer.
5252     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5253         Owner->isRecord())
5254       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5255                                 cast<CXXRecordDecl>(Record));
5256   }
5257 
5258   if (!Record->isUnion() && !Owner->isRecord()) {
5259     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5260       << getLangOpts().CPlusPlus;
5261     Invalid = true;
5262   }
5263 
5264   // C++ [dcl.dcl]p3:
5265   //   [If there are no declarators], and except for the declaration of an
5266   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5267   //   names into the program
5268   // C++ [class.mem]p2:
5269   //   each such member-declaration shall either declare at least one member
5270   //   name of the class or declare at least one unnamed bit-field
5271   //
5272   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5273   if (getLangOpts().CPlusPlus && Record->field_empty())
5274     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5275 
5276   // Mock up a declarator.
5277   Declarator Dc(DS, DeclaratorContext::Member);
5278   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5279   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5280 
5281   // Create a declaration for this anonymous struct/union.
5282   NamedDecl *Anon = nullptr;
5283   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5284     Anon = FieldDecl::Create(
5285         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5286         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5287         /*BitWidth=*/nullptr, /*Mutable=*/false,
5288         /*InitStyle=*/ICIS_NoInit);
5289     Anon->setAccess(AS);
5290     ProcessDeclAttributes(S, Anon, Dc);
5291 
5292     if (getLangOpts().CPlusPlus)
5293       FieldCollector->Add(cast<FieldDecl>(Anon));
5294   } else {
5295     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5296     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5297     if (SCSpec == DeclSpec::SCS_mutable) {
5298       // mutable can only appear on non-static class members, so it's always
5299       // an error here
5300       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5301       Invalid = true;
5302       SC = SC_None;
5303     }
5304 
5305     assert(DS.getAttributes().empty() && "No attribute expected");
5306     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5307                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5308                            Context.getTypeDeclType(Record), TInfo, SC);
5309 
5310     // Default-initialize the implicit variable. This initialization will be
5311     // trivial in almost all cases, except if a union member has an in-class
5312     // initializer:
5313     //   union { int n = 0; };
5314     ActOnUninitializedDecl(Anon);
5315   }
5316   Anon->setImplicit();
5317 
5318   // Mark this as an anonymous struct/union type.
5319   Record->setAnonymousStructOrUnion(true);
5320 
5321   // Add the anonymous struct/union object to the current
5322   // context. We'll be referencing this object when we refer to one of
5323   // its members.
5324   Owner->addDecl(Anon);
5325 
5326   // Inject the members of the anonymous struct/union into the owning
5327   // context and into the identifier resolver chain for name lookup
5328   // purposes.
5329   SmallVector<NamedDecl*, 2> Chain;
5330   Chain.push_back(Anon);
5331 
5332   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5333     Invalid = true;
5334 
5335   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5336     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5337       MangleNumberingContext *MCtx;
5338       Decl *ManglingContextDecl;
5339       std::tie(MCtx, ManglingContextDecl) =
5340           getCurrentMangleNumberContext(NewVD->getDeclContext());
5341       if (MCtx) {
5342         Context.setManglingNumber(
5343             NewVD, MCtx->getManglingNumber(
5344                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5345         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5346       }
5347     }
5348   }
5349 
5350   if (Invalid)
5351     Anon->setInvalidDecl();
5352 
5353   return Anon;
5354 }
5355 
5356 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5357 /// Microsoft C anonymous structure.
5358 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5359 /// Example:
5360 ///
5361 /// struct A { int a; };
5362 /// struct B { struct A; int b; };
5363 ///
5364 /// void foo() {
5365 ///   B var;
5366 ///   var.a = 3;
5367 /// }
5368 ///
5369 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5370                                            RecordDecl *Record) {
5371   assert(Record && "expected a record!");
5372 
5373   // Mock up a declarator.
5374   Declarator Dc(DS, DeclaratorContext::TypeName);
5375   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5376   assert(TInfo && "couldn't build declarator info for anonymous struct");
5377 
5378   auto *ParentDecl = cast<RecordDecl>(CurContext);
5379   QualType RecTy = Context.getTypeDeclType(Record);
5380 
5381   // Create a declaration for this anonymous struct.
5382   NamedDecl *Anon =
5383       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5384                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5385                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5386                         /*InitStyle=*/ICIS_NoInit);
5387   Anon->setImplicit();
5388 
5389   // Add the anonymous struct object to the current context.
5390   CurContext->addDecl(Anon);
5391 
5392   // Inject the members of the anonymous struct into the current
5393   // context and into the identifier resolver chain for name lookup
5394   // purposes.
5395   SmallVector<NamedDecl*, 2> Chain;
5396   Chain.push_back(Anon);
5397 
5398   RecordDecl *RecordDef = Record->getDefinition();
5399   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5400                                diag::err_field_incomplete_or_sizeless) ||
5401       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5402                                           AS_none, Chain)) {
5403     Anon->setInvalidDecl();
5404     ParentDecl->setInvalidDecl();
5405   }
5406 
5407   return Anon;
5408 }
5409 
5410 /// GetNameForDeclarator - Determine the full declaration name for the
5411 /// given Declarator.
5412 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5413   return GetNameFromUnqualifiedId(D.getName());
5414 }
5415 
5416 /// Retrieves the declaration name from a parsed unqualified-id.
5417 DeclarationNameInfo
5418 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5419   DeclarationNameInfo NameInfo;
5420   NameInfo.setLoc(Name.StartLocation);
5421 
5422   switch (Name.getKind()) {
5423 
5424   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5425   case UnqualifiedIdKind::IK_Identifier:
5426     NameInfo.setName(Name.Identifier);
5427     return NameInfo;
5428 
5429   case UnqualifiedIdKind::IK_DeductionGuideName: {
5430     // C++ [temp.deduct.guide]p3:
5431     //   The simple-template-id shall name a class template specialization.
5432     //   The template-name shall be the same identifier as the template-name
5433     //   of the simple-template-id.
5434     // These together intend to imply that the template-name shall name a
5435     // class template.
5436     // FIXME: template<typename T> struct X {};
5437     //        template<typename T> using Y = X<T>;
5438     //        Y(int) -> Y<int>;
5439     //   satisfies these rules but does not name a class template.
5440     TemplateName TN = Name.TemplateName.get().get();
5441     auto *Template = TN.getAsTemplateDecl();
5442     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5443       Diag(Name.StartLocation,
5444            diag::err_deduction_guide_name_not_class_template)
5445         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5446       if (Template)
5447         Diag(Template->getLocation(), diag::note_template_decl_here);
5448       return DeclarationNameInfo();
5449     }
5450 
5451     NameInfo.setName(
5452         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5453     return NameInfo;
5454   }
5455 
5456   case UnqualifiedIdKind::IK_OperatorFunctionId:
5457     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5458                                            Name.OperatorFunctionId.Operator));
5459     NameInfo.setCXXOperatorNameRange(SourceRange(
5460         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5461     return NameInfo;
5462 
5463   case UnqualifiedIdKind::IK_LiteralOperatorId:
5464     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5465                                                            Name.Identifier));
5466     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5467     return NameInfo;
5468 
5469   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5470     TypeSourceInfo *TInfo;
5471     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5472     if (Ty.isNull())
5473       return DeclarationNameInfo();
5474     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5475                                                Context.getCanonicalType(Ty)));
5476     NameInfo.setNamedTypeInfo(TInfo);
5477     return NameInfo;
5478   }
5479 
5480   case UnqualifiedIdKind::IK_ConstructorName: {
5481     TypeSourceInfo *TInfo;
5482     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5483     if (Ty.isNull())
5484       return DeclarationNameInfo();
5485     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5486                                               Context.getCanonicalType(Ty)));
5487     NameInfo.setNamedTypeInfo(TInfo);
5488     return NameInfo;
5489   }
5490 
5491   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5492     // In well-formed code, we can only have a constructor
5493     // template-id that refers to the current context, so go there
5494     // to find the actual type being constructed.
5495     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5496     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5497       return DeclarationNameInfo();
5498 
5499     // Determine the type of the class being constructed.
5500     QualType CurClassType = Context.getTypeDeclType(CurClass);
5501 
5502     // FIXME: Check two things: that the template-id names the same type as
5503     // CurClassType, and that the template-id does not occur when the name
5504     // was qualified.
5505 
5506     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5507                                     Context.getCanonicalType(CurClassType)));
5508     // FIXME: should we retrieve TypeSourceInfo?
5509     NameInfo.setNamedTypeInfo(nullptr);
5510     return NameInfo;
5511   }
5512 
5513   case UnqualifiedIdKind::IK_DestructorName: {
5514     TypeSourceInfo *TInfo;
5515     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5516     if (Ty.isNull())
5517       return DeclarationNameInfo();
5518     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5519                                               Context.getCanonicalType(Ty)));
5520     NameInfo.setNamedTypeInfo(TInfo);
5521     return NameInfo;
5522   }
5523 
5524   case UnqualifiedIdKind::IK_TemplateId: {
5525     TemplateName TName = Name.TemplateId->Template.get();
5526     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5527     return Context.getNameForTemplate(TName, TNameLoc);
5528   }
5529 
5530   } // switch (Name.getKind())
5531 
5532   llvm_unreachable("Unknown name kind");
5533 }
5534 
5535 static QualType getCoreType(QualType Ty) {
5536   do {
5537     if (Ty->isPointerType() || Ty->isReferenceType())
5538       Ty = Ty->getPointeeType();
5539     else if (Ty->isArrayType())
5540       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5541     else
5542       return Ty.withoutLocalFastQualifiers();
5543   } while (true);
5544 }
5545 
5546 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5547 /// and Definition have "nearly" matching parameters. This heuristic is
5548 /// used to improve diagnostics in the case where an out-of-line function
5549 /// definition doesn't match any declaration within the class or namespace.
5550 /// Also sets Params to the list of indices to the parameters that differ
5551 /// between the declaration and the definition. If hasSimilarParameters
5552 /// returns true and Params is empty, then all of the parameters match.
5553 static bool hasSimilarParameters(ASTContext &Context,
5554                                      FunctionDecl *Declaration,
5555                                      FunctionDecl *Definition,
5556                                      SmallVectorImpl<unsigned> &Params) {
5557   Params.clear();
5558   if (Declaration->param_size() != Definition->param_size())
5559     return false;
5560   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5561     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5562     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5563 
5564     // The parameter types are identical
5565     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5566       continue;
5567 
5568     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5569     QualType DefParamBaseTy = getCoreType(DefParamTy);
5570     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5571     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5572 
5573     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5574         (DeclTyName && DeclTyName == DefTyName))
5575       Params.push_back(Idx);
5576     else  // The two parameters aren't even close
5577       return false;
5578   }
5579 
5580   return true;
5581 }
5582 
5583 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5584 /// declarator needs to be rebuilt in the current instantiation.
5585 /// Any bits of declarator which appear before the name are valid for
5586 /// consideration here.  That's specifically the type in the decl spec
5587 /// and the base type in any member-pointer chunks.
5588 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5589                                                     DeclarationName Name) {
5590   // The types we specifically need to rebuild are:
5591   //   - typenames, typeofs, and decltypes
5592   //   - types which will become injected class names
5593   // Of course, we also need to rebuild any type referencing such a
5594   // type.  It's safest to just say "dependent", but we call out a
5595   // few cases here.
5596 
5597   DeclSpec &DS = D.getMutableDeclSpec();
5598   switch (DS.getTypeSpecType()) {
5599   case DeclSpec::TST_typename:
5600   case DeclSpec::TST_typeofType:
5601   case DeclSpec::TST_underlyingType:
5602   case DeclSpec::TST_atomic: {
5603     // Grab the type from the parser.
5604     TypeSourceInfo *TSI = nullptr;
5605     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5606     if (T.isNull() || !T->isInstantiationDependentType()) break;
5607 
5608     // Make sure there's a type source info.  This isn't really much
5609     // of a waste; most dependent types should have type source info
5610     // attached already.
5611     if (!TSI)
5612       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5613 
5614     // Rebuild the type in the current instantiation.
5615     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5616     if (!TSI) return true;
5617 
5618     // Store the new type back in the decl spec.
5619     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5620     DS.UpdateTypeRep(LocType);
5621     break;
5622   }
5623 
5624   case DeclSpec::TST_decltype:
5625   case DeclSpec::TST_typeofExpr: {
5626     Expr *E = DS.getRepAsExpr();
5627     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5628     if (Result.isInvalid()) return true;
5629     DS.UpdateExprRep(Result.get());
5630     break;
5631   }
5632 
5633   default:
5634     // Nothing to do for these decl specs.
5635     break;
5636   }
5637 
5638   // It doesn't matter what order we do this in.
5639   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5640     DeclaratorChunk &Chunk = D.getTypeObject(I);
5641 
5642     // The only type information in the declarator which can come
5643     // before the declaration name is the base type of a member
5644     // pointer.
5645     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5646       continue;
5647 
5648     // Rebuild the scope specifier in-place.
5649     CXXScopeSpec &SS = Chunk.Mem.Scope();
5650     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5651       return true;
5652   }
5653 
5654   return false;
5655 }
5656 
5657 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5658   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5659   // of system decl.
5660   if (D->getPreviousDecl() || D->isImplicit())
5661     return;
5662   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5663   if (Status != ReservedIdentifierStatus::NotReserved &&
5664       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5665     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5666         << D << static_cast<int>(Status);
5667 }
5668 
5669 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5670   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5671   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5672 
5673   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5674       Dcl && Dcl->getDeclContext()->isFileContext())
5675     Dcl->setTopLevelDeclInObjCContainer();
5676 
5677   return Dcl;
5678 }
5679 
5680 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5681 ///   If T is the name of a class, then each of the following shall have a
5682 ///   name different from T:
5683 ///     - every static data member of class T;
5684 ///     - every member function of class T
5685 ///     - every member of class T that is itself a type;
5686 /// \returns true if the declaration name violates these rules.
5687 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5688                                    DeclarationNameInfo NameInfo) {
5689   DeclarationName Name = NameInfo.getName();
5690 
5691   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5692   while (Record && Record->isAnonymousStructOrUnion())
5693     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5694   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5695     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5696     return true;
5697   }
5698 
5699   return false;
5700 }
5701 
5702 /// Diagnose a declaration whose declarator-id has the given
5703 /// nested-name-specifier.
5704 ///
5705 /// \param SS The nested-name-specifier of the declarator-id.
5706 ///
5707 /// \param DC The declaration context to which the nested-name-specifier
5708 /// resolves.
5709 ///
5710 /// \param Name The name of the entity being declared.
5711 ///
5712 /// \param Loc The location of the name of the entity being declared.
5713 ///
5714 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5715 /// we're declaring an explicit / partial specialization / instantiation.
5716 ///
5717 /// \returns true if we cannot safely recover from this error, false otherwise.
5718 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5719                                         DeclarationName Name,
5720                                         SourceLocation Loc, bool IsTemplateId) {
5721   DeclContext *Cur = CurContext;
5722   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5723     Cur = Cur->getParent();
5724 
5725   // If the user provided a superfluous scope specifier that refers back to the
5726   // class in which the entity is already declared, diagnose and ignore it.
5727   //
5728   // class X {
5729   //   void X::f();
5730   // };
5731   //
5732   // Note, it was once ill-formed to give redundant qualification in all
5733   // contexts, but that rule was removed by DR482.
5734   if (Cur->Equals(DC)) {
5735     if (Cur->isRecord()) {
5736       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5737                                       : diag::err_member_extra_qualification)
5738         << Name << FixItHint::CreateRemoval(SS.getRange());
5739       SS.clear();
5740     } else {
5741       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5742     }
5743     return false;
5744   }
5745 
5746   // Check whether the qualifying scope encloses the scope of the original
5747   // declaration. For a template-id, we perform the checks in
5748   // CheckTemplateSpecializationScope.
5749   if (!Cur->Encloses(DC) && !IsTemplateId) {
5750     if (Cur->isRecord())
5751       Diag(Loc, diag::err_member_qualification)
5752         << Name << SS.getRange();
5753     else if (isa<TranslationUnitDecl>(DC))
5754       Diag(Loc, diag::err_invalid_declarator_global_scope)
5755         << Name << SS.getRange();
5756     else if (isa<FunctionDecl>(Cur))
5757       Diag(Loc, diag::err_invalid_declarator_in_function)
5758         << Name << SS.getRange();
5759     else if (isa<BlockDecl>(Cur))
5760       Diag(Loc, diag::err_invalid_declarator_in_block)
5761         << Name << SS.getRange();
5762     else
5763       Diag(Loc, diag::err_invalid_declarator_scope)
5764       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5765 
5766     return true;
5767   }
5768 
5769   if (Cur->isRecord()) {
5770     // Cannot qualify members within a class.
5771     Diag(Loc, diag::err_member_qualification)
5772       << Name << SS.getRange();
5773     SS.clear();
5774 
5775     // C++ constructors and destructors with incorrect scopes can break
5776     // our AST invariants by having the wrong underlying types. If
5777     // that's the case, then drop this declaration entirely.
5778     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5779          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5780         !Context.hasSameType(Name.getCXXNameType(),
5781                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5782       return true;
5783 
5784     return false;
5785   }
5786 
5787   // C++11 [dcl.meaning]p1:
5788   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5789   //   not begin with a decltype-specifer"
5790   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5791   while (SpecLoc.getPrefix())
5792     SpecLoc = SpecLoc.getPrefix();
5793   if (isa_and_nonnull<DecltypeType>(
5794           SpecLoc.getNestedNameSpecifier()->getAsType()))
5795     Diag(Loc, diag::err_decltype_in_declarator)
5796       << SpecLoc.getTypeLoc().getSourceRange();
5797 
5798   return false;
5799 }
5800 
5801 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5802                                   MultiTemplateParamsArg TemplateParamLists) {
5803   // TODO: consider using NameInfo for diagnostic.
5804   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5805   DeclarationName Name = NameInfo.getName();
5806 
5807   // All of these full declarators require an identifier.  If it doesn't have
5808   // one, the ParsedFreeStandingDeclSpec action should be used.
5809   if (D.isDecompositionDeclarator()) {
5810     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5811   } else if (!Name) {
5812     if (!D.isInvalidType())  // Reject this if we think it is valid.
5813       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5814           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5815     return nullptr;
5816   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5817     return nullptr;
5818 
5819   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5820   // we find one that is.
5821   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5822          (S->getFlags() & Scope::TemplateParamScope) != 0)
5823     S = S->getParent();
5824 
5825   DeclContext *DC = CurContext;
5826   if (D.getCXXScopeSpec().isInvalid())
5827     D.setInvalidType();
5828   else if (D.getCXXScopeSpec().isSet()) {
5829     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5830                                         UPPC_DeclarationQualifier))
5831       return nullptr;
5832 
5833     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5834     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5835     if (!DC || isa<EnumDecl>(DC)) {
5836       // If we could not compute the declaration context, it's because the
5837       // declaration context is dependent but does not refer to a class,
5838       // class template, or class template partial specialization. Complain
5839       // and return early, to avoid the coming semantic disaster.
5840       Diag(D.getIdentifierLoc(),
5841            diag::err_template_qualified_declarator_no_match)
5842         << D.getCXXScopeSpec().getScopeRep()
5843         << D.getCXXScopeSpec().getRange();
5844       return nullptr;
5845     }
5846     bool IsDependentContext = DC->isDependentContext();
5847 
5848     if (!IsDependentContext &&
5849         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5850       return nullptr;
5851 
5852     // If a class is incomplete, do not parse entities inside it.
5853     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5854       Diag(D.getIdentifierLoc(),
5855            diag::err_member_def_undefined_record)
5856         << Name << DC << D.getCXXScopeSpec().getRange();
5857       return nullptr;
5858     }
5859     if (!D.getDeclSpec().isFriendSpecified()) {
5860       if (diagnoseQualifiedDeclaration(
5861               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5862               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5863         if (DC->isRecord())
5864           return nullptr;
5865 
5866         D.setInvalidType();
5867       }
5868     }
5869 
5870     // Check whether we need to rebuild the type of the given
5871     // declaration in the current instantiation.
5872     if (EnteringContext && IsDependentContext &&
5873         TemplateParamLists.size() != 0) {
5874       ContextRAII SavedContext(*this, DC);
5875       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5876         D.setInvalidType();
5877     }
5878   }
5879 
5880   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5881   QualType R = TInfo->getType();
5882 
5883   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5884                                       UPPC_DeclarationType))
5885     D.setInvalidType();
5886 
5887   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5888                         forRedeclarationInCurContext());
5889 
5890   // See if this is a redefinition of a variable in the same scope.
5891   if (!D.getCXXScopeSpec().isSet()) {
5892     bool IsLinkageLookup = false;
5893     bool CreateBuiltins = false;
5894 
5895     // If the declaration we're planning to build will be a function
5896     // or object with linkage, then look for another declaration with
5897     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5898     //
5899     // If the declaration we're planning to build will be declared with
5900     // external linkage in the translation unit, create any builtin with
5901     // the same name.
5902     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5903       /* Do nothing*/;
5904     else if (CurContext->isFunctionOrMethod() &&
5905              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5906               R->isFunctionType())) {
5907       IsLinkageLookup = true;
5908       CreateBuiltins =
5909           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5910     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5911                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5912       CreateBuiltins = true;
5913 
5914     if (IsLinkageLookup) {
5915       Previous.clear(LookupRedeclarationWithLinkage);
5916       Previous.setRedeclarationKind(ForExternalRedeclaration);
5917     }
5918 
5919     LookupName(Previous, S, CreateBuiltins);
5920   } else { // Something like "int foo::x;"
5921     LookupQualifiedName(Previous, DC);
5922 
5923     // C++ [dcl.meaning]p1:
5924     //   When the declarator-id is qualified, the declaration shall refer to a
5925     //  previously declared member of the class or namespace to which the
5926     //  qualifier refers (or, in the case of a namespace, of an element of the
5927     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5928     //  thereof; [...]
5929     //
5930     // Note that we already checked the context above, and that we do not have
5931     // enough information to make sure that Previous contains the declaration
5932     // we want to match. For example, given:
5933     //
5934     //   class X {
5935     //     void f();
5936     //     void f(float);
5937     //   };
5938     //
5939     //   void X::f(int) { } // ill-formed
5940     //
5941     // In this case, Previous will point to the overload set
5942     // containing the two f's declared in X, but neither of them
5943     // matches.
5944 
5945     // C++ [dcl.meaning]p1:
5946     //   [...] the member shall not merely have been introduced by a
5947     //   using-declaration in the scope of the class or namespace nominated by
5948     //   the nested-name-specifier of the declarator-id.
5949     RemoveUsingDecls(Previous);
5950   }
5951 
5952   if (Previous.isSingleResult() &&
5953       Previous.getFoundDecl()->isTemplateParameter()) {
5954     // Maybe we will complain about the shadowed template parameter.
5955     if (!D.isInvalidType())
5956       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5957                                       Previous.getFoundDecl());
5958 
5959     // Just pretend that we didn't see the previous declaration.
5960     Previous.clear();
5961   }
5962 
5963   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5964     // Forget that the previous declaration is the injected-class-name.
5965     Previous.clear();
5966 
5967   // In C++, the previous declaration we find might be a tag type
5968   // (class or enum). In this case, the new declaration will hide the
5969   // tag type. Note that this applies to functions, function templates, and
5970   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5971   if (Previous.isSingleTagDecl() &&
5972       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5973       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5974     Previous.clear();
5975 
5976   // Check that there are no default arguments other than in the parameters
5977   // of a function declaration (C++ only).
5978   if (getLangOpts().CPlusPlus)
5979     CheckExtraCXXDefaultArguments(D);
5980 
5981   NamedDecl *New;
5982 
5983   bool AddToScope = true;
5984   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5985     if (TemplateParamLists.size()) {
5986       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5987       return nullptr;
5988     }
5989 
5990     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5991   } else if (R->isFunctionType()) {
5992     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5993                                   TemplateParamLists,
5994                                   AddToScope);
5995   } else {
5996     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5997                                   AddToScope);
5998   }
5999 
6000   if (!New)
6001     return nullptr;
6002 
6003   // If this has an identifier and is not a function template specialization,
6004   // add it to the scope stack.
6005   if (New->getDeclName() && AddToScope)
6006     PushOnScopeChains(New, S);
6007 
6008   if (isInOpenMPDeclareTargetContext())
6009     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6010 
6011   return New;
6012 }
6013 
6014 /// Helper method to turn variable array types into constant array
6015 /// types in certain situations which would otherwise be errors (for
6016 /// GCC compatibility).
6017 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6018                                                     ASTContext &Context,
6019                                                     bool &SizeIsNegative,
6020                                                     llvm::APSInt &Oversized) {
6021   // This method tries to turn a variable array into a constant
6022   // array even when the size isn't an ICE.  This is necessary
6023   // for compatibility with code that depends on gcc's buggy
6024   // constant expression folding, like struct {char x[(int)(char*)2];}
6025   SizeIsNegative = false;
6026   Oversized = 0;
6027 
6028   if (T->isDependentType())
6029     return QualType();
6030 
6031   QualifierCollector Qs;
6032   const Type *Ty = Qs.strip(T);
6033 
6034   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6035     QualType Pointee = PTy->getPointeeType();
6036     QualType FixedType =
6037         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6038                                             Oversized);
6039     if (FixedType.isNull()) return FixedType;
6040     FixedType = Context.getPointerType(FixedType);
6041     return Qs.apply(Context, FixedType);
6042   }
6043   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6044     QualType Inner = PTy->getInnerType();
6045     QualType FixedType =
6046         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6047                                             Oversized);
6048     if (FixedType.isNull()) return FixedType;
6049     FixedType = Context.getParenType(FixedType);
6050     return Qs.apply(Context, FixedType);
6051   }
6052 
6053   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6054   if (!VLATy)
6055     return QualType();
6056 
6057   QualType ElemTy = VLATy->getElementType();
6058   if (ElemTy->isVariablyModifiedType()) {
6059     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6060                                                  SizeIsNegative, Oversized);
6061     if (ElemTy.isNull())
6062       return QualType();
6063   }
6064 
6065   Expr::EvalResult Result;
6066   if (!VLATy->getSizeExpr() ||
6067       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6068     return QualType();
6069 
6070   llvm::APSInt Res = Result.Val.getInt();
6071 
6072   // Check whether the array size is negative.
6073   if (Res.isSigned() && Res.isNegative()) {
6074     SizeIsNegative = true;
6075     return QualType();
6076   }
6077 
6078   // Check whether the array is too large to be addressed.
6079   unsigned ActiveSizeBits =
6080       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6081        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6082           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6083           : Res.getActiveBits();
6084   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6085     Oversized = Res;
6086     return QualType();
6087   }
6088 
6089   QualType FoldedArrayType = Context.getConstantArrayType(
6090       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6091   return Qs.apply(Context, FoldedArrayType);
6092 }
6093 
6094 static void
6095 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6096   SrcTL = SrcTL.getUnqualifiedLoc();
6097   DstTL = DstTL.getUnqualifiedLoc();
6098   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6099     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6100     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6101                                       DstPTL.getPointeeLoc());
6102     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6103     return;
6104   }
6105   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6106     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6107     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6108                                       DstPTL.getInnerLoc());
6109     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6110     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6111     return;
6112   }
6113   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6114   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6115   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6116   TypeLoc DstElemTL = DstATL.getElementLoc();
6117   if (VariableArrayTypeLoc SrcElemATL =
6118           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6119     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6120     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6121   } else {
6122     DstElemTL.initializeFullCopy(SrcElemTL);
6123   }
6124   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6125   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6126   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6127 }
6128 
6129 /// Helper method to turn variable array types into constant array
6130 /// types in certain situations which would otherwise be errors (for
6131 /// GCC compatibility).
6132 static TypeSourceInfo*
6133 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6134                                               ASTContext &Context,
6135                                               bool &SizeIsNegative,
6136                                               llvm::APSInt &Oversized) {
6137   QualType FixedTy
6138     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6139                                           SizeIsNegative, Oversized);
6140   if (FixedTy.isNull())
6141     return nullptr;
6142   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6143   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6144                                     FixedTInfo->getTypeLoc());
6145   return FixedTInfo;
6146 }
6147 
6148 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6149 /// true if we were successful.
6150 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6151                                            QualType &T, SourceLocation Loc,
6152                                            unsigned FailedFoldDiagID) {
6153   bool SizeIsNegative;
6154   llvm::APSInt Oversized;
6155   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6156       TInfo, Context, SizeIsNegative, Oversized);
6157   if (FixedTInfo) {
6158     Diag(Loc, diag::ext_vla_folded_to_constant);
6159     TInfo = FixedTInfo;
6160     T = FixedTInfo->getType();
6161     return true;
6162   }
6163 
6164   if (SizeIsNegative)
6165     Diag(Loc, diag::err_typecheck_negative_array_size);
6166   else if (Oversized.getBoolValue())
6167     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6168   else if (FailedFoldDiagID)
6169     Diag(Loc, FailedFoldDiagID);
6170   return false;
6171 }
6172 
6173 /// Register the given locally-scoped extern "C" declaration so
6174 /// that it can be found later for redeclarations. We include any extern "C"
6175 /// declaration that is not visible in the translation unit here, not just
6176 /// function-scope declarations.
6177 void
6178 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6179   if (!getLangOpts().CPlusPlus &&
6180       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6181     // Don't need to track declarations in the TU in C.
6182     return;
6183 
6184   // Note that we have a locally-scoped external with this name.
6185   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6186 }
6187 
6188 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6189   // FIXME: We can have multiple results via __attribute__((overloadable)).
6190   auto Result = Context.getExternCContextDecl()->lookup(Name);
6191   return Result.empty() ? nullptr : *Result.begin();
6192 }
6193 
6194 /// Diagnose function specifiers on a declaration of an identifier that
6195 /// does not identify a function.
6196 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6197   // FIXME: We should probably indicate the identifier in question to avoid
6198   // confusion for constructs like "virtual int a(), b;"
6199   if (DS.isVirtualSpecified())
6200     Diag(DS.getVirtualSpecLoc(),
6201          diag::err_virtual_non_function);
6202 
6203   if (DS.hasExplicitSpecifier())
6204     Diag(DS.getExplicitSpecLoc(),
6205          diag::err_explicit_non_function);
6206 
6207   if (DS.isNoreturnSpecified())
6208     Diag(DS.getNoreturnSpecLoc(),
6209          diag::err_noreturn_non_function);
6210 }
6211 
6212 NamedDecl*
6213 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6214                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6215   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6216   if (D.getCXXScopeSpec().isSet()) {
6217     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6218       << D.getCXXScopeSpec().getRange();
6219     D.setInvalidType();
6220     // Pretend we didn't see the scope specifier.
6221     DC = CurContext;
6222     Previous.clear();
6223   }
6224 
6225   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6226 
6227   if (D.getDeclSpec().isInlineSpecified())
6228     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6229         << getLangOpts().CPlusPlus17;
6230   if (D.getDeclSpec().hasConstexprSpecifier())
6231     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6232         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6233 
6234   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6235     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6236       Diag(D.getName().StartLocation,
6237            diag::err_deduction_guide_invalid_specifier)
6238           << "typedef";
6239     else
6240       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6241           << D.getName().getSourceRange();
6242     return nullptr;
6243   }
6244 
6245   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6246   if (!NewTD) return nullptr;
6247 
6248   // Handle attributes prior to checking for duplicates in MergeVarDecl
6249   ProcessDeclAttributes(S, NewTD, D);
6250 
6251   CheckTypedefForVariablyModifiedType(S, NewTD);
6252 
6253   bool Redeclaration = D.isRedeclaration();
6254   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6255   D.setRedeclaration(Redeclaration);
6256   return ND;
6257 }
6258 
6259 void
6260 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6261   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6262   // then it shall have block scope.
6263   // Note that variably modified types must be fixed before merging the decl so
6264   // that redeclarations will match.
6265   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6266   QualType T = TInfo->getType();
6267   if (T->isVariablyModifiedType()) {
6268     setFunctionHasBranchProtectedScope();
6269 
6270     if (S->getFnParent() == nullptr) {
6271       bool SizeIsNegative;
6272       llvm::APSInt Oversized;
6273       TypeSourceInfo *FixedTInfo =
6274         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6275                                                       SizeIsNegative,
6276                                                       Oversized);
6277       if (FixedTInfo) {
6278         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6279         NewTD->setTypeSourceInfo(FixedTInfo);
6280       } else {
6281         if (SizeIsNegative)
6282           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6283         else if (T->isVariableArrayType())
6284           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6285         else if (Oversized.getBoolValue())
6286           Diag(NewTD->getLocation(), diag::err_array_too_large)
6287             << toString(Oversized, 10);
6288         else
6289           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6290         NewTD->setInvalidDecl();
6291       }
6292     }
6293   }
6294 }
6295 
6296 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6297 /// declares a typedef-name, either using the 'typedef' type specifier or via
6298 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6299 NamedDecl*
6300 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6301                            LookupResult &Previous, bool &Redeclaration) {
6302 
6303   // Find the shadowed declaration before filtering for scope.
6304   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6305 
6306   // Merge the decl with the existing one if appropriate. If the decl is
6307   // in an outer scope, it isn't the same thing.
6308   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6309                        /*AllowInlineNamespace*/false);
6310   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6311   if (!Previous.empty()) {
6312     Redeclaration = true;
6313     MergeTypedefNameDecl(S, NewTD, Previous);
6314   } else {
6315     inferGslPointerAttribute(NewTD);
6316   }
6317 
6318   if (ShadowedDecl && !Redeclaration)
6319     CheckShadow(NewTD, ShadowedDecl, Previous);
6320 
6321   // If this is the C FILE type, notify the AST context.
6322   if (IdentifierInfo *II = NewTD->getIdentifier())
6323     if (!NewTD->isInvalidDecl() &&
6324         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6325       if (II->isStr("FILE"))
6326         Context.setFILEDecl(NewTD);
6327       else if (II->isStr("jmp_buf"))
6328         Context.setjmp_bufDecl(NewTD);
6329       else if (II->isStr("sigjmp_buf"))
6330         Context.setsigjmp_bufDecl(NewTD);
6331       else if (II->isStr("ucontext_t"))
6332         Context.setucontext_tDecl(NewTD);
6333     }
6334 
6335   return NewTD;
6336 }
6337 
6338 /// Determines whether the given declaration is an out-of-scope
6339 /// previous declaration.
6340 ///
6341 /// This routine should be invoked when name lookup has found a
6342 /// previous declaration (PrevDecl) that is not in the scope where a
6343 /// new declaration by the same name is being introduced. If the new
6344 /// declaration occurs in a local scope, previous declarations with
6345 /// linkage may still be considered previous declarations (C99
6346 /// 6.2.2p4-5, C++ [basic.link]p6).
6347 ///
6348 /// \param PrevDecl the previous declaration found by name
6349 /// lookup
6350 ///
6351 /// \param DC the context in which the new declaration is being
6352 /// declared.
6353 ///
6354 /// \returns true if PrevDecl is an out-of-scope previous declaration
6355 /// for a new delcaration with the same name.
6356 static bool
6357 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6358                                 ASTContext &Context) {
6359   if (!PrevDecl)
6360     return false;
6361 
6362   if (!PrevDecl->hasLinkage())
6363     return false;
6364 
6365   if (Context.getLangOpts().CPlusPlus) {
6366     // C++ [basic.link]p6:
6367     //   If there is a visible declaration of an entity with linkage
6368     //   having the same name and type, ignoring entities declared
6369     //   outside the innermost enclosing namespace scope, the block
6370     //   scope declaration declares that same entity and receives the
6371     //   linkage of the previous declaration.
6372     DeclContext *OuterContext = DC->getRedeclContext();
6373     if (!OuterContext->isFunctionOrMethod())
6374       // This rule only applies to block-scope declarations.
6375       return false;
6376 
6377     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6378     if (PrevOuterContext->isRecord())
6379       // We found a member function: ignore it.
6380       return false;
6381 
6382     // Find the innermost enclosing namespace for the new and
6383     // previous declarations.
6384     OuterContext = OuterContext->getEnclosingNamespaceContext();
6385     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6386 
6387     // The previous declaration is in a different namespace, so it
6388     // isn't the same function.
6389     if (!OuterContext->Equals(PrevOuterContext))
6390       return false;
6391   }
6392 
6393   return true;
6394 }
6395 
6396 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6397   CXXScopeSpec &SS = D.getCXXScopeSpec();
6398   if (!SS.isSet()) return;
6399   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6400 }
6401 
6402 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6403   QualType type = decl->getType();
6404   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6405   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6406     // Various kinds of declaration aren't allowed to be __autoreleasing.
6407     unsigned kind = -1U;
6408     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6409       if (var->hasAttr<BlocksAttr>())
6410         kind = 0; // __block
6411       else if (!var->hasLocalStorage())
6412         kind = 1; // global
6413     } else if (isa<ObjCIvarDecl>(decl)) {
6414       kind = 3; // ivar
6415     } else if (isa<FieldDecl>(decl)) {
6416       kind = 2; // field
6417     }
6418 
6419     if (kind != -1U) {
6420       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6421         << kind;
6422     }
6423   } else if (lifetime == Qualifiers::OCL_None) {
6424     // Try to infer lifetime.
6425     if (!type->isObjCLifetimeType())
6426       return false;
6427 
6428     lifetime = type->getObjCARCImplicitLifetime();
6429     type = Context.getLifetimeQualifiedType(type, lifetime);
6430     decl->setType(type);
6431   }
6432 
6433   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6434     // Thread-local variables cannot have lifetime.
6435     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6436         var->getTLSKind()) {
6437       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6438         << var->getType();
6439       return true;
6440     }
6441   }
6442 
6443   return false;
6444 }
6445 
6446 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6447   if (Decl->getType().hasAddressSpace())
6448     return;
6449   if (Decl->getType()->isDependentType())
6450     return;
6451   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6452     QualType Type = Var->getType();
6453     if (Type->isSamplerT() || Type->isVoidType())
6454       return;
6455     LangAS ImplAS = LangAS::opencl_private;
6456     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6457     // __opencl_c_program_scope_global_variables feature, the address space
6458     // for a variable at program scope or a static or extern variable inside
6459     // a function are inferred to be __global.
6460     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6461         Var->hasGlobalStorage())
6462       ImplAS = LangAS::opencl_global;
6463     // If the original type from a decayed type is an array type and that array
6464     // type has no address space yet, deduce it now.
6465     if (auto DT = dyn_cast<DecayedType>(Type)) {
6466       auto OrigTy = DT->getOriginalType();
6467       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6468         // Add the address space to the original array type and then propagate
6469         // that to the element type through `getAsArrayType`.
6470         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6471         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6472         // Re-generate the decayed type.
6473         Type = Context.getDecayedType(OrigTy);
6474       }
6475     }
6476     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6477     // Apply any qualifiers (including address space) from the array type to
6478     // the element type. This implements C99 6.7.3p8: "If the specification of
6479     // an array type includes any type qualifiers, the element type is so
6480     // qualified, not the array type."
6481     if (Type->isArrayType())
6482       Type = QualType(Context.getAsArrayType(Type), 0);
6483     Decl->setType(Type);
6484   }
6485 }
6486 
6487 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6488   // Ensure that an auto decl is deduced otherwise the checks below might cache
6489   // the wrong linkage.
6490   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6491 
6492   // 'weak' only applies to declarations with external linkage.
6493   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6494     if (!ND.isExternallyVisible()) {
6495       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6496       ND.dropAttr<WeakAttr>();
6497     }
6498   }
6499   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6500     if (ND.isExternallyVisible()) {
6501       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6502       ND.dropAttr<WeakRefAttr>();
6503       ND.dropAttr<AliasAttr>();
6504     }
6505   }
6506 
6507   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6508     if (VD->hasInit()) {
6509       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6510         assert(VD->isThisDeclarationADefinition() &&
6511                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6512         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6513         VD->dropAttr<AliasAttr>();
6514       }
6515     }
6516   }
6517 
6518   // 'selectany' only applies to externally visible variable declarations.
6519   // It does not apply to functions.
6520   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6521     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6522       S.Diag(Attr->getLocation(),
6523              diag::err_attribute_selectany_non_extern_data);
6524       ND.dropAttr<SelectAnyAttr>();
6525     }
6526   }
6527 
6528   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6529     auto *VD = dyn_cast<VarDecl>(&ND);
6530     bool IsAnonymousNS = false;
6531     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6532     if (VD) {
6533       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6534       while (NS && !IsAnonymousNS) {
6535         IsAnonymousNS = NS->isAnonymousNamespace();
6536         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6537       }
6538     }
6539     // dll attributes require external linkage. Static locals may have external
6540     // linkage but still cannot be explicitly imported or exported.
6541     // In Microsoft mode, a variable defined in anonymous namespace must have
6542     // external linkage in order to be exported.
6543     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6544     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6545         (!AnonNSInMicrosoftMode &&
6546          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6547       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6548         << &ND << Attr;
6549       ND.setInvalidDecl();
6550     }
6551   }
6552 
6553   // Check the attributes on the function type, if any.
6554   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6555     // Don't declare this variable in the second operand of the for-statement;
6556     // GCC miscompiles that by ending its lifetime before evaluating the
6557     // third operand. See gcc.gnu.org/PR86769.
6558     AttributedTypeLoc ATL;
6559     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6560          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6561          TL = ATL.getModifiedLoc()) {
6562       // The [[lifetimebound]] attribute can be applied to the implicit object
6563       // parameter of a non-static member function (other than a ctor or dtor)
6564       // by applying it to the function type.
6565       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6566         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6567         if (!MD || MD->isStatic()) {
6568           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6569               << !MD << A->getRange();
6570         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6571           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6572               << isa<CXXDestructorDecl>(MD) << A->getRange();
6573         }
6574       }
6575     }
6576   }
6577 }
6578 
6579 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6580                                            NamedDecl *NewDecl,
6581                                            bool IsSpecialization,
6582                                            bool IsDefinition) {
6583   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6584     return;
6585 
6586   bool IsTemplate = false;
6587   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6588     OldDecl = OldTD->getTemplatedDecl();
6589     IsTemplate = true;
6590     if (!IsSpecialization)
6591       IsDefinition = false;
6592   }
6593   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6594     NewDecl = NewTD->getTemplatedDecl();
6595     IsTemplate = true;
6596   }
6597 
6598   if (!OldDecl || !NewDecl)
6599     return;
6600 
6601   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6602   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6603   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6604   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6605 
6606   // dllimport and dllexport are inheritable attributes so we have to exclude
6607   // inherited attribute instances.
6608   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6609                     (NewExportAttr && !NewExportAttr->isInherited());
6610 
6611   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6612   // the only exception being explicit specializations.
6613   // Implicitly generated declarations are also excluded for now because there
6614   // is no other way to switch these to use dllimport or dllexport.
6615   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6616 
6617   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6618     // Allow with a warning for free functions and global variables.
6619     bool JustWarn = false;
6620     if (!OldDecl->isCXXClassMember()) {
6621       auto *VD = dyn_cast<VarDecl>(OldDecl);
6622       if (VD && !VD->getDescribedVarTemplate())
6623         JustWarn = true;
6624       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6625       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6626         JustWarn = true;
6627     }
6628 
6629     // We cannot change a declaration that's been used because IR has already
6630     // been emitted. Dllimported functions will still work though (modulo
6631     // address equality) as they can use the thunk.
6632     if (OldDecl->isUsed())
6633       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6634         JustWarn = false;
6635 
6636     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6637                                : diag::err_attribute_dll_redeclaration;
6638     S.Diag(NewDecl->getLocation(), DiagID)
6639         << NewDecl
6640         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6641     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6642     if (!JustWarn) {
6643       NewDecl->setInvalidDecl();
6644       return;
6645     }
6646   }
6647 
6648   // A redeclaration is not allowed to drop a dllimport attribute, the only
6649   // exceptions being inline function definitions (except for function
6650   // templates), local extern declarations, qualified friend declarations or
6651   // special MSVC extension: in the last case, the declaration is treated as if
6652   // it were marked dllexport.
6653   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6654   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6655   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6656     // Ignore static data because out-of-line definitions are diagnosed
6657     // separately.
6658     IsStaticDataMember = VD->isStaticDataMember();
6659     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6660                    VarDecl::DeclarationOnly;
6661   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6662     IsInline = FD->isInlined();
6663     IsQualifiedFriend = FD->getQualifier() &&
6664                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6665   }
6666 
6667   if (OldImportAttr && !HasNewAttr &&
6668       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6669       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6670     if (IsMicrosoftABI && IsDefinition) {
6671       S.Diag(NewDecl->getLocation(),
6672              diag::warn_redeclaration_without_import_attribute)
6673           << NewDecl;
6674       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6675       NewDecl->dropAttr<DLLImportAttr>();
6676       NewDecl->addAttr(
6677           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6678     } else {
6679       S.Diag(NewDecl->getLocation(),
6680              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6681           << NewDecl << OldImportAttr;
6682       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6683       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6684       OldDecl->dropAttr<DLLImportAttr>();
6685       NewDecl->dropAttr<DLLImportAttr>();
6686     }
6687   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6688     // In MinGW, seeing a function declared inline drops the dllimport
6689     // attribute.
6690     OldDecl->dropAttr<DLLImportAttr>();
6691     NewDecl->dropAttr<DLLImportAttr>();
6692     S.Diag(NewDecl->getLocation(),
6693            diag::warn_dllimport_dropped_from_inline_function)
6694         << NewDecl << OldImportAttr;
6695   }
6696 
6697   // A specialization of a class template member function is processed here
6698   // since it's a redeclaration. If the parent class is dllexport, the
6699   // specialization inherits that attribute. This doesn't happen automatically
6700   // since the parent class isn't instantiated until later.
6701   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6702     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6703         !NewImportAttr && !NewExportAttr) {
6704       if (const DLLExportAttr *ParentExportAttr =
6705               MD->getParent()->getAttr<DLLExportAttr>()) {
6706         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6707         NewAttr->setInherited(true);
6708         NewDecl->addAttr(NewAttr);
6709       }
6710     }
6711   }
6712 }
6713 
6714 /// Given that we are within the definition of the given function,
6715 /// will that definition behave like C99's 'inline', where the
6716 /// definition is discarded except for optimization purposes?
6717 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6718   // Try to avoid calling GetGVALinkageForFunction.
6719 
6720   // All cases of this require the 'inline' keyword.
6721   if (!FD->isInlined()) return false;
6722 
6723   // This is only possible in C++ with the gnu_inline attribute.
6724   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6725     return false;
6726 
6727   // Okay, go ahead and call the relatively-more-expensive function.
6728   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6729 }
6730 
6731 /// Determine whether a variable is extern "C" prior to attaching
6732 /// an initializer. We can't just call isExternC() here, because that
6733 /// will also compute and cache whether the declaration is externally
6734 /// visible, which might change when we attach the initializer.
6735 ///
6736 /// This can only be used if the declaration is known to not be a
6737 /// redeclaration of an internal linkage declaration.
6738 ///
6739 /// For instance:
6740 ///
6741 ///   auto x = []{};
6742 ///
6743 /// Attaching the initializer here makes this declaration not externally
6744 /// visible, because its type has internal linkage.
6745 ///
6746 /// FIXME: This is a hack.
6747 template<typename T>
6748 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6749   if (S.getLangOpts().CPlusPlus) {
6750     // In C++, the overloadable attribute negates the effects of extern "C".
6751     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6752       return false;
6753 
6754     // So do CUDA's host/device attributes.
6755     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6756                                  D->template hasAttr<CUDAHostAttr>()))
6757       return false;
6758   }
6759   return D->isExternC();
6760 }
6761 
6762 static bool shouldConsiderLinkage(const VarDecl *VD) {
6763   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6764   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6765       isa<OMPDeclareMapperDecl>(DC))
6766     return VD->hasExternalStorage();
6767   if (DC->isFileContext())
6768     return true;
6769   if (DC->isRecord())
6770     return false;
6771   if (isa<RequiresExprBodyDecl>(DC))
6772     return false;
6773   llvm_unreachable("Unexpected context");
6774 }
6775 
6776 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6777   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6778   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6779       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6780     return true;
6781   if (DC->isRecord())
6782     return false;
6783   llvm_unreachable("Unexpected context");
6784 }
6785 
6786 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6787                           ParsedAttr::Kind Kind) {
6788   // Check decl attributes on the DeclSpec.
6789   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6790     return true;
6791 
6792   // Walk the declarator structure, checking decl attributes that were in a type
6793   // position to the decl itself.
6794   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6795     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6796       return true;
6797   }
6798 
6799   // Finally, check attributes on the decl itself.
6800   return PD.getAttributes().hasAttribute(Kind);
6801 }
6802 
6803 /// Adjust the \c DeclContext for a function or variable that might be a
6804 /// function-local external declaration.
6805 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6806   if (!DC->isFunctionOrMethod())
6807     return false;
6808 
6809   // If this is a local extern function or variable declared within a function
6810   // template, don't add it into the enclosing namespace scope until it is
6811   // instantiated; it might have a dependent type right now.
6812   if (DC->isDependentContext())
6813     return true;
6814 
6815   // C++11 [basic.link]p7:
6816   //   When a block scope declaration of an entity with linkage is not found to
6817   //   refer to some other declaration, then that entity is a member of the
6818   //   innermost enclosing namespace.
6819   //
6820   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6821   // semantically-enclosing namespace, not a lexically-enclosing one.
6822   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6823     DC = DC->getParent();
6824   return true;
6825 }
6826 
6827 /// Returns true if given declaration has external C language linkage.
6828 static bool isDeclExternC(const Decl *D) {
6829   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6830     return FD->isExternC();
6831   if (const auto *VD = dyn_cast<VarDecl>(D))
6832     return VD->isExternC();
6833 
6834   llvm_unreachable("Unknown type of decl!");
6835 }
6836 
6837 /// Returns true if there hasn't been any invalid type diagnosed.
6838 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6839   DeclContext *DC = NewVD->getDeclContext();
6840   QualType R = NewVD->getType();
6841 
6842   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6843   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6844   // argument.
6845   if (R->isImageType() || R->isPipeType()) {
6846     Se.Diag(NewVD->getLocation(),
6847             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6848         << R;
6849     NewVD->setInvalidDecl();
6850     return false;
6851   }
6852 
6853   // OpenCL v1.2 s6.9.r:
6854   // The event type cannot be used to declare a program scope variable.
6855   // OpenCL v2.0 s6.9.q:
6856   // The clk_event_t and reserve_id_t types cannot be declared in program
6857   // scope.
6858   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6859     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6860       Se.Diag(NewVD->getLocation(),
6861               diag::err_invalid_type_for_program_scope_var)
6862           << R;
6863       NewVD->setInvalidDecl();
6864       return false;
6865     }
6866   }
6867 
6868   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6869   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6870                                                Se.getLangOpts())) {
6871     QualType NR = R.getCanonicalType();
6872     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6873            NR->isReferenceType()) {
6874       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6875           NR->isFunctionReferenceType()) {
6876         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6877             << NR->isReferenceType();
6878         NewVD->setInvalidDecl();
6879         return false;
6880       }
6881       NR = NR->getPointeeType();
6882     }
6883   }
6884 
6885   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6886                                                Se.getLangOpts())) {
6887     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6888     // half array type (unless the cl_khr_fp16 extension is enabled).
6889     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6890       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6891       NewVD->setInvalidDecl();
6892       return false;
6893     }
6894   }
6895 
6896   // OpenCL v1.2 s6.9.r:
6897   // The event type cannot be used with the __local, __constant and __global
6898   // address space qualifiers.
6899   if (R->isEventT()) {
6900     if (R.getAddressSpace() != LangAS::opencl_private) {
6901       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6902       NewVD->setInvalidDecl();
6903       return false;
6904     }
6905   }
6906 
6907   if (R->isSamplerT()) {
6908     // OpenCL v1.2 s6.9.b p4:
6909     // The sampler type cannot be used with the __local and __global address
6910     // space qualifiers.
6911     if (R.getAddressSpace() == LangAS::opencl_local ||
6912         R.getAddressSpace() == LangAS::opencl_global) {
6913       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6914       NewVD->setInvalidDecl();
6915     }
6916 
6917     // OpenCL v1.2 s6.12.14.1:
6918     // A global sampler must be declared with either the constant address
6919     // space qualifier or with the const qualifier.
6920     if (DC->isTranslationUnit() &&
6921         !(R.getAddressSpace() == LangAS::opencl_constant ||
6922           R.isConstQualified())) {
6923       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6924       NewVD->setInvalidDecl();
6925     }
6926     if (NewVD->isInvalidDecl())
6927       return false;
6928   }
6929 
6930   return true;
6931 }
6932 
6933 template <typename AttrTy>
6934 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6935   const TypedefNameDecl *TND = TT->getDecl();
6936   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6937     AttrTy *Clone = Attribute->clone(S.Context);
6938     Clone->setInherited(true);
6939     D->addAttr(Clone);
6940   }
6941 }
6942 
6943 NamedDecl *Sema::ActOnVariableDeclarator(
6944     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6945     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6946     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6947   QualType R = TInfo->getType();
6948   DeclarationName Name = GetNameForDeclarator(D).getName();
6949 
6950   IdentifierInfo *II = Name.getAsIdentifierInfo();
6951 
6952   if (D.isDecompositionDeclarator()) {
6953     // Take the name of the first declarator as our name for diagnostic
6954     // purposes.
6955     auto &Decomp = D.getDecompositionDeclarator();
6956     if (!Decomp.bindings().empty()) {
6957       II = Decomp.bindings()[0].Name;
6958       Name = II;
6959     }
6960   } else if (!II) {
6961     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6962     return nullptr;
6963   }
6964 
6965 
6966   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6967   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6968 
6969   // dllimport globals without explicit storage class are treated as extern. We
6970   // have to change the storage class this early to get the right DeclContext.
6971   if (SC == SC_None && !DC->isRecord() &&
6972       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6973       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6974     SC = SC_Extern;
6975 
6976   DeclContext *OriginalDC = DC;
6977   bool IsLocalExternDecl = SC == SC_Extern &&
6978                            adjustContextForLocalExternDecl(DC);
6979 
6980   if (SCSpec == DeclSpec::SCS_mutable) {
6981     // mutable can only appear on non-static class members, so it's always
6982     // an error here
6983     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6984     D.setInvalidType();
6985     SC = SC_None;
6986   }
6987 
6988   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6989       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6990                               D.getDeclSpec().getStorageClassSpecLoc())) {
6991     // In C++11, the 'register' storage class specifier is deprecated.
6992     // Suppress the warning in system macros, it's used in macros in some
6993     // popular C system headers, such as in glibc's htonl() macro.
6994     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6995          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6996                                    : diag::warn_deprecated_register)
6997       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6998   }
6999 
7000   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7001 
7002   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7003     // C99 6.9p2: The storage-class specifiers auto and register shall not
7004     // appear in the declaration specifiers in an external declaration.
7005     // Global Register+Asm is a GNU extension we support.
7006     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7007       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7008       D.setInvalidType();
7009     }
7010   }
7011 
7012   // If this variable has a VLA type and an initializer, try to
7013   // fold to a constant-sized type. This is otherwise invalid.
7014   if (D.hasInitializer() && R->isVariableArrayType())
7015     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7016                                     /*DiagID=*/0);
7017 
7018   bool IsMemberSpecialization = false;
7019   bool IsVariableTemplateSpecialization = false;
7020   bool IsPartialSpecialization = false;
7021   bool IsVariableTemplate = false;
7022   VarDecl *NewVD = nullptr;
7023   VarTemplateDecl *NewTemplate = nullptr;
7024   TemplateParameterList *TemplateParams = nullptr;
7025   if (!getLangOpts().CPlusPlus) {
7026     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7027                             II, R, TInfo, SC);
7028 
7029     if (R->getContainedDeducedType())
7030       ParsingInitForAutoVars.insert(NewVD);
7031 
7032     if (D.isInvalidType())
7033       NewVD->setInvalidDecl();
7034 
7035     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7036         NewVD->hasLocalStorage())
7037       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7038                             NTCUC_AutoVar, NTCUK_Destruct);
7039   } else {
7040     bool Invalid = false;
7041 
7042     if (DC->isRecord() && !CurContext->isRecord()) {
7043       // This is an out-of-line definition of a static data member.
7044       switch (SC) {
7045       case SC_None:
7046         break;
7047       case SC_Static:
7048         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7049              diag::err_static_out_of_line)
7050           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7051         break;
7052       case SC_Auto:
7053       case SC_Register:
7054       case SC_Extern:
7055         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7056         // to names of variables declared in a block or to function parameters.
7057         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7058         // of class members
7059 
7060         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7061              diag::err_storage_class_for_static_member)
7062           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7063         break;
7064       case SC_PrivateExtern:
7065         llvm_unreachable("C storage class in c++!");
7066       }
7067     }
7068 
7069     if (SC == SC_Static && CurContext->isRecord()) {
7070       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7071         // Walk up the enclosing DeclContexts to check for any that are
7072         // incompatible with static data members.
7073         const DeclContext *FunctionOrMethod = nullptr;
7074         const CXXRecordDecl *AnonStruct = nullptr;
7075         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7076           if (Ctxt->isFunctionOrMethod()) {
7077             FunctionOrMethod = Ctxt;
7078             break;
7079           }
7080           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7081           if (ParentDecl && !ParentDecl->getDeclName()) {
7082             AnonStruct = ParentDecl;
7083             break;
7084           }
7085         }
7086         if (FunctionOrMethod) {
7087           // C++ [class.static.data]p5: A local class shall not have static data
7088           // members.
7089           Diag(D.getIdentifierLoc(),
7090                diag::err_static_data_member_not_allowed_in_local_class)
7091             << Name << RD->getDeclName() << RD->getTagKind();
7092         } else if (AnonStruct) {
7093           // C++ [class.static.data]p4: Unnamed classes and classes contained
7094           // directly or indirectly within unnamed classes shall not contain
7095           // static data members.
7096           Diag(D.getIdentifierLoc(),
7097                diag::err_static_data_member_not_allowed_in_anon_struct)
7098             << Name << AnonStruct->getTagKind();
7099           Invalid = true;
7100         } else if (RD->isUnion()) {
7101           // C++98 [class.union]p1: If a union contains a static data member,
7102           // the program is ill-formed. C++11 drops this restriction.
7103           Diag(D.getIdentifierLoc(),
7104                getLangOpts().CPlusPlus11
7105                  ? diag::warn_cxx98_compat_static_data_member_in_union
7106                  : diag::ext_static_data_member_in_union) << Name;
7107         }
7108       }
7109     }
7110 
7111     // Match up the template parameter lists with the scope specifier, then
7112     // determine whether we have a template or a template specialization.
7113     bool InvalidScope = false;
7114     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7115         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7116         D.getCXXScopeSpec(),
7117         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7118             ? D.getName().TemplateId
7119             : nullptr,
7120         TemplateParamLists,
7121         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7122     Invalid |= InvalidScope;
7123 
7124     if (TemplateParams) {
7125       if (!TemplateParams->size() &&
7126           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7127         // There is an extraneous 'template<>' for this variable. Complain
7128         // about it, but allow the declaration of the variable.
7129         Diag(TemplateParams->getTemplateLoc(),
7130              diag::err_template_variable_noparams)
7131           << II
7132           << SourceRange(TemplateParams->getTemplateLoc(),
7133                          TemplateParams->getRAngleLoc());
7134         TemplateParams = nullptr;
7135       } else {
7136         // Check that we can declare a template here.
7137         if (CheckTemplateDeclScope(S, TemplateParams))
7138           return nullptr;
7139 
7140         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7141           // This is an explicit specialization or a partial specialization.
7142           IsVariableTemplateSpecialization = true;
7143           IsPartialSpecialization = TemplateParams->size() > 0;
7144         } else { // if (TemplateParams->size() > 0)
7145           // This is a template declaration.
7146           IsVariableTemplate = true;
7147 
7148           // Only C++1y supports variable templates (N3651).
7149           Diag(D.getIdentifierLoc(),
7150                getLangOpts().CPlusPlus14
7151                    ? diag::warn_cxx11_compat_variable_template
7152                    : diag::ext_variable_template);
7153         }
7154       }
7155     } else {
7156       // Check that we can declare a member specialization here.
7157       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7158           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7159         return nullptr;
7160       assert((Invalid ||
7161               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7162              "should have a 'template<>' for this decl");
7163     }
7164 
7165     if (IsVariableTemplateSpecialization) {
7166       SourceLocation TemplateKWLoc =
7167           TemplateParamLists.size() > 0
7168               ? TemplateParamLists[0]->getTemplateLoc()
7169               : SourceLocation();
7170       DeclResult Res = ActOnVarTemplateSpecialization(
7171           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7172           IsPartialSpecialization);
7173       if (Res.isInvalid())
7174         return nullptr;
7175       NewVD = cast<VarDecl>(Res.get());
7176       AddToScope = false;
7177     } else if (D.isDecompositionDeclarator()) {
7178       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7179                                         D.getIdentifierLoc(), R, TInfo, SC,
7180                                         Bindings);
7181     } else
7182       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7183                               D.getIdentifierLoc(), II, R, TInfo, SC);
7184 
7185     // If this is supposed to be a variable template, create it as such.
7186     if (IsVariableTemplate) {
7187       NewTemplate =
7188           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7189                                   TemplateParams, NewVD);
7190       NewVD->setDescribedVarTemplate(NewTemplate);
7191     }
7192 
7193     // If this decl has an auto type in need of deduction, make a note of the
7194     // Decl so we can diagnose uses of it in its own initializer.
7195     if (R->getContainedDeducedType())
7196       ParsingInitForAutoVars.insert(NewVD);
7197 
7198     if (D.isInvalidType() || Invalid) {
7199       NewVD->setInvalidDecl();
7200       if (NewTemplate)
7201         NewTemplate->setInvalidDecl();
7202     }
7203 
7204     SetNestedNameSpecifier(*this, NewVD, D);
7205 
7206     // If we have any template parameter lists that don't directly belong to
7207     // the variable (matching the scope specifier), store them.
7208     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7209     if (TemplateParamLists.size() > VDTemplateParamLists)
7210       NewVD->setTemplateParameterListsInfo(
7211           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7212   }
7213 
7214   if (D.getDeclSpec().isInlineSpecified()) {
7215     if (!getLangOpts().CPlusPlus) {
7216       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7217           << 0;
7218     } else if (CurContext->isFunctionOrMethod()) {
7219       // 'inline' is not allowed on block scope variable declaration.
7220       Diag(D.getDeclSpec().getInlineSpecLoc(),
7221            diag::err_inline_declaration_block_scope) << Name
7222         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7223     } else {
7224       Diag(D.getDeclSpec().getInlineSpecLoc(),
7225            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7226                                      : diag::ext_inline_variable);
7227       NewVD->setInlineSpecified();
7228     }
7229   }
7230 
7231   // Set the lexical context. If the declarator has a C++ scope specifier, the
7232   // lexical context will be different from the semantic context.
7233   NewVD->setLexicalDeclContext(CurContext);
7234   if (NewTemplate)
7235     NewTemplate->setLexicalDeclContext(CurContext);
7236 
7237   if (IsLocalExternDecl) {
7238     if (D.isDecompositionDeclarator())
7239       for (auto *B : Bindings)
7240         B->setLocalExternDecl();
7241     else
7242       NewVD->setLocalExternDecl();
7243   }
7244 
7245   bool EmitTLSUnsupportedError = false;
7246   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7247     // C++11 [dcl.stc]p4:
7248     //   When thread_local is applied to a variable of block scope the
7249     //   storage-class-specifier static is implied if it does not appear
7250     //   explicitly.
7251     // Core issue: 'static' is not implied if the variable is declared
7252     //   'extern'.
7253     if (NewVD->hasLocalStorage() &&
7254         (SCSpec != DeclSpec::SCS_unspecified ||
7255          TSCS != DeclSpec::TSCS_thread_local ||
7256          !DC->isFunctionOrMethod()))
7257       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7258            diag::err_thread_non_global)
7259         << DeclSpec::getSpecifierName(TSCS);
7260     else if (!Context.getTargetInfo().isTLSSupported()) {
7261       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7262           getLangOpts().SYCLIsDevice) {
7263         // Postpone error emission until we've collected attributes required to
7264         // figure out whether it's a host or device variable and whether the
7265         // error should be ignored.
7266         EmitTLSUnsupportedError = true;
7267         // We still need to mark the variable as TLS so it shows up in AST with
7268         // proper storage class for other tools to use even if we're not going
7269         // to emit any code for it.
7270         NewVD->setTSCSpec(TSCS);
7271       } else
7272         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7273              diag::err_thread_unsupported);
7274     } else
7275       NewVD->setTSCSpec(TSCS);
7276   }
7277 
7278   switch (D.getDeclSpec().getConstexprSpecifier()) {
7279   case ConstexprSpecKind::Unspecified:
7280     break;
7281 
7282   case ConstexprSpecKind::Consteval:
7283     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7284          diag::err_constexpr_wrong_decl_kind)
7285         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7286     LLVM_FALLTHROUGH;
7287 
7288   case ConstexprSpecKind::Constexpr:
7289     NewVD->setConstexpr(true);
7290     // C++1z [dcl.spec.constexpr]p1:
7291     //   A static data member declared with the constexpr specifier is
7292     //   implicitly an inline variable.
7293     if (NewVD->isStaticDataMember() &&
7294         (getLangOpts().CPlusPlus17 ||
7295          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7296       NewVD->setImplicitlyInline();
7297     break;
7298 
7299   case ConstexprSpecKind::Constinit:
7300     if (!NewVD->hasGlobalStorage())
7301       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7302            diag::err_constinit_local_variable);
7303     else
7304       NewVD->addAttr(ConstInitAttr::Create(
7305           Context, D.getDeclSpec().getConstexprSpecLoc(),
7306           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7307     break;
7308   }
7309 
7310   // C99 6.7.4p3
7311   //   An inline definition of a function with external linkage shall
7312   //   not contain a definition of a modifiable object with static or
7313   //   thread storage duration...
7314   // We only apply this when the function is required to be defined
7315   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7316   // that a local variable with thread storage duration still has to
7317   // be marked 'static'.  Also note that it's possible to get these
7318   // semantics in C++ using __attribute__((gnu_inline)).
7319   if (SC == SC_Static && S->getFnParent() != nullptr &&
7320       !NewVD->getType().isConstQualified()) {
7321     FunctionDecl *CurFD = getCurFunctionDecl();
7322     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7323       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7324            diag::warn_static_local_in_extern_inline);
7325       MaybeSuggestAddingStaticToDecl(CurFD);
7326     }
7327   }
7328 
7329   if (D.getDeclSpec().isModulePrivateSpecified()) {
7330     if (IsVariableTemplateSpecialization)
7331       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7332           << (IsPartialSpecialization ? 1 : 0)
7333           << FixItHint::CreateRemoval(
7334                  D.getDeclSpec().getModulePrivateSpecLoc());
7335     else if (IsMemberSpecialization)
7336       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7337         << 2
7338         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7339     else if (NewVD->hasLocalStorage())
7340       Diag(NewVD->getLocation(), diag::err_module_private_local)
7341           << 0 << NewVD
7342           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7343           << FixItHint::CreateRemoval(
7344                  D.getDeclSpec().getModulePrivateSpecLoc());
7345     else {
7346       NewVD->setModulePrivate();
7347       if (NewTemplate)
7348         NewTemplate->setModulePrivate();
7349       for (auto *B : Bindings)
7350         B->setModulePrivate();
7351     }
7352   }
7353 
7354   if (getLangOpts().OpenCL) {
7355     deduceOpenCLAddressSpace(NewVD);
7356 
7357     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7358     if (TSC != TSCS_unspecified) {
7359       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7360            diag::err_opencl_unknown_type_specifier)
7361           << getLangOpts().getOpenCLVersionString()
7362           << DeclSpec::getSpecifierName(TSC) << 1;
7363       NewVD->setInvalidDecl();
7364     }
7365   }
7366 
7367   // Handle attributes prior to checking for duplicates in MergeVarDecl
7368   ProcessDeclAttributes(S, NewVD, D);
7369 
7370   // FIXME: This is probably the wrong location to be doing this and we should
7371   // probably be doing this for more attributes (especially for function
7372   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7373   // the code to copy attributes would be generated by TableGen.
7374   if (R->isFunctionPointerType())
7375     if (const auto *TT = R->getAs<TypedefType>())
7376       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7377 
7378   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7379       getLangOpts().SYCLIsDevice) {
7380     if (EmitTLSUnsupportedError &&
7381         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7382          (getLangOpts().OpenMPIsDevice &&
7383           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7384       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7385            diag::err_thread_unsupported);
7386 
7387     if (EmitTLSUnsupportedError &&
7388         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7389       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7390     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7391     // storage [duration]."
7392     if (SC == SC_None && S->getFnParent() != nullptr &&
7393         (NewVD->hasAttr<CUDASharedAttr>() ||
7394          NewVD->hasAttr<CUDAConstantAttr>())) {
7395       NewVD->setStorageClass(SC_Static);
7396     }
7397   }
7398 
7399   // Ensure that dllimport globals without explicit storage class are treated as
7400   // extern. The storage class is set above using parsed attributes. Now we can
7401   // check the VarDecl itself.
7402   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7403          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7404          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7405 
7406   // In auto-retain/release, infer strong retension for variables of
7407   // retainable type.
7408   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7409     NewVD->setInvalidDecl();
7410 
7411   // Handle GNU asm-label extension (encoded as an attribute).
7412   if (Expr *E = (Expr*)D.getAsmLabel()) {
7413     // The parser guarantees this is a string.
7414     StringLiteral *SE = cast<StringLiteral>(E);
7415     StringRef Label = SE->getString();
7416     if (S->getFnParent() != nullptr) {
7417       switch (SC) {
7418       case SC_None:
7419       case SC_Auto:
7420         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7421         break;
7422       case SC_Register:
7423         // Local Named register
7424         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7425             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7426           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7427         break;
7428       case SC_Static:
7429       case SC_Extern:
7430       case SC_PrivateExtern:
7431         break;
7432       }
7433     } else if (SC == SC_Register) {
7434       // Global Named register
7435       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7436         const auto &TI = Context.getTargetInfo();
7437         bool HasSizeMismatch;
7438 
7439         if (!TI.isValidGCCRegisterName(Label))
7440           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7441         else if (!TI.validateGlobalRegisterVariable(Label,
7442                                                     Context.getTypeSize(R),
7443                                                     HasSizeMismatch))
7444           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7445         else if (HasSizeMismatch)
7446           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7447       }
7448 
7449       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7450         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7451         NewVD->setInvalidDecl(true);
7452       }
7453     }
7454 
7455     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7456                                         /*IsLiteralLabel=*/true,
7457                                         SE->getStrTokenLoc(0)));
7458   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7459     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7460       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7461     if (I != ExtnameUndeclaredIdentifiers.end()) {
7462       if (isDeclExternC(NewVD)) {
7463         NewVD->addAttr(I->second);
7464         ExtnameUndeclaredIdentifiers.erase(I);
7465       } else
7466         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7467             << /*Variable*/1 << NewVD;
7468     }
7469   }
7470 
7471   // Find the shadowed declaration before filtering for scope.
7472   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7473                                 ? getShadowedDeclaration(NewVD, Previous)
7474                                 : nullptr;
7475 
7476   // Don't consider existing declarations that are in a different
7477   // scope and are out-of-semantic-context declarations (if the new
7478   // declaration has linkage).
7479   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7480                        D.getCXXScopeSpec().isNotEmpty() ||
7481                        IsMemberSpecialization ||
7482                        IsVariableTemplateSpecialization);
7483 
7484   // Check whether the previous declaration is in the same block scope. This
7485   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7486   if (getLangOpts().CPlusPlus &&
7487       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7488     NewVD->setPreviousDeclInSameBlockScope(
7489         Previous.isSingleResult() && !Previous.isShadowed() &&
7490         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7491 
7492   if (!getLangOpts().CPlusPlus) {
7493     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7494   } else {
7495     // If this is an explicit specialization of a static data member, check it.
7496     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7497         CheckMemberSpecialization(NewVD, Previous))
7498       NewVD->setInvalidDecl();
7499 
7500     // Merge the decl with the existing one if appropriate.
7501     if (!Previous.empty()) {
7502       if (Previous.isSingleResult() &&
7503           isa<FieldDecl>(Previous.getFoundDecl()) &&
7504           D.getCXXScopeSpec().isSet()) {
7505         // The user tried to define a non-static data member
7506         // out-of-line (C++ [dcl.meaning]p1).
7507         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7508           << D.getCXXScopeSpec().getRange();
7509         Previous.clear();
7510         NewVD->setInvalidDecl();
7511       }
7512     } else if (D.getCXXScopeSpec().isSet()) {
7513       // No previous declaration in the qualifying scope.
7514       Diag(D.getIdentifierLoc(), diag::err_no_member)
7515         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7516         << D.getCXXScopeSpec().getRange();
7517       NewVD->setInvalidDecl();
7518     }
7519 
7520     if (!IsVariableTemplateSpecialization)
7521       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7522 
7523     if (NewTemplate) {
7524       VarTemplateDecl *PrevVarTemplate =
7525           NewVD->getPreviousDecl()
7526               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7527               : nullptr;
7528 
7529       // Check the template parameter list of this declaration, possibly
7530       // merging in the template parameter list from the previous variable
7531       // template declaration.
7532       if (CheckTemplateParameterList(
7533               TemplateParams,
7534               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7535                               : nullptr,
7536               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7537                DC->isDependentContext())
7538                   ? TPC_ClassTemplateMember
7539                   : TPC_VarTemplate))
7540         NewVD->setInvalidDecl();
7541 
7542       // If we are providing an explicit specialization of a static variable
7543       // template, make a note of that.
7544       if (PrevVarTemplate &&
7545           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7546         PrevVarTemplate->setMemberSpecialization();
7547     }
7548   }
7549 
7550   // Diagnose shadowed variables iff this isn't a redeclaration.
7551   if (ShadowedDecl && !D.isRedeclaration())
7552     CheckShadow(NewVD, ShadowedDecl, Previous);
7553 
7554   ProcessPragmaWeak(S, NewVD);
7555 
7556   // If this is the first declaration of an extern C variable, update
7557   // the map of such variables.
7558   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7559       isIncompleteDeclExternC(*this, NewVD))
7560     RegisterLocallyScopedExternCDecl(NewVD, S);
7561 
7562   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7563     MangleNumberingContext *MCtx;
7564     Decl *ManglingContextDecl;
7565     std::tie(MCtx, ManglingContextDecl) =
7566         getCurrentMangleNumberContext(NewVD->getDeclContext());
7567     if (MCtx) {
7568       Context.setManglingNumber(
7569           NewVD, MCtx->getManglingNumber(
7570                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7571       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7572     }
7573   }
7574 
7575   // Special handling of variable named 'main'.
7576   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7577       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7578       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7579 
7580     // C++ [basic.start.main]p3
7581     // A program that declares a variable main at global scope is ill-formed.
7582     if (getLangOpts().CPlusPlus)
7583       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7584 
7585     // In C, and external-linkage variable named main results in undefined
7586     // behavior.
7587     else if (NewVD->hasExternalFormalLinkage())
7588       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7589   }
7590 
7591   if (D.isRedeclaration() && !Previous.empty()) {
7592     NamedDecl *Prev = Previous.getRepresentativeDecl();
7593     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7594                                    D.isFunctionDefinition());
7595   }
7596 
7597   if (NewTemplate) {
7598     if (NewVD->isInvalidDecl())
7599       NewTemplate->setInvalidDecl();
7600     ActOnDocumentableDecl(NewTemplate);
7601     return NewTemplate;
7602   }
7603 
7604   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7605     CompleteMemberSpecialization(NewVD, Previous);
7606 
7607   return NewVD;
7608 }
7609 
7610 /// Enum describing the %select options in diag::warn_decl_shadow.
7611 enum ShadowedDeclKind {
7612   SDK_Local,
7613   SDK_Global,
7614   SDK_StaticMember,
7615   SDK_Field,
7616   SDK_Typedef,
7617   SDK_Using,
7618   SDK_StructuredBinding
7619 };
7620 
7621 /// Determine what kind of declaration we're shadowing.
7622 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7623                                                 const DeclContext *OldDC) {
7624   if (isa<TypeAliasDecl>(ShadowedDecl))
7625     return SDK_Using;
7626   else if (isa<TypedefDecl>(ShadowedDecl))
7627     return SDK_Typedef;
7628   else if (isa<BindingDecl>(ShadowedDecl))
7629     return SDK_StructuredBinding;
7630   else if (isa<RecordDecl>(OldDC))
7631     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7632 
7633   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7634 }
7635 
7636 /// Return the location of the capture if the given lambda captures the given
7637 /// variable \p VD, or an invalid source location otherwise.
7638 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7639                                          const VarDecl *VD) {
7640   for (const Capture &Capture : LSI->Captures) {
7641     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7642       return Capture.getLocation();
7643   }
7644   return SourceLocation();
7645 }
7646 
7647 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7648                                      const LookupResult &R) {
7649   // Only diagnose if we're shadowing an unambiguous field or variable.
7650   if (R.getResultKind() != LookupResult::Found)
7651     return false;
7652 
7653   // Return false if warning is ignored.
7654   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7655 }
7656 
7657 /// Return the declaration shadowed by the given variable \p D, or null
7658 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7659 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7660                                         const LookupResult &R) {
7661   if (!shouldWarnIfShadowedDecl(Diags, R))
7662     return nullptr;
7663 
7664   // Don't diagnose declarations at file scope.
7665   if (D->hasGlobalStorage())
7666     return nullptr;
7667 
7668   NamedDecl *ShadowedDecl = R.getFoundDecl();
7669   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7670                                                             : nullptr;
7671 }
7672 
7673 /// Return the declaration shadowed by the given typedef \p D, or null
7674 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7675 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7676                                         const LookupResult &R) {
7677   // Don't warn if typedef declaration is part of a class
7678   if (D->getDeclContext()->isRecord())
7679     return nullptr;
7680 
7681   if (!shouldWarnIfShadowedDecl(Diags, R))
7682     return nullptr;
7683 
7684   NamedDecl *ShadowedDecl = R.getFoundDecl();
7685   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7686 }
7687 
7688 /// Return the declaration shadowed by the given variable \p D, or null
7689 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7690 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7691                                         const LookupResult &R) {
7692   if (!shouldWarnIfShadowedDecl(Diags, R))
7693     return nullptr;
7694 
7695   NamedDecl *ShadowedDecl = R.getFoundDecl();
7696   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7697                                                             : nullptr;
7698 }
7699 
7700 /// Diagnose variable or built-in function shadowing.  Implements
7701 /// -Wshadow.
7702 ///
7703 /// This method is called whenever a VarDecl is added to a "useful"
7704 /// scope.
7705 ///
7706 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7707 /// \param R the lookup of the name
7708 ///
7709 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7710                        const LookupResult &R) {
7711   DeclContext *NewDC = D->getDeclContext();
7712 
7713   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7714     // Fields are not shadowed by variables in C++ static methods.
7715     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7716       if (MD->isStatic())
7717         return;
7718 
7719     // Fields shadowed by constructor parameters are a special case. Usually
7720     // the constructor initializes the field with the parameter.
7721     if (isa<CXXConstructorDecl>(NewDC))
7722       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7723         // Remember that this was shadowed so we can either warn about its
7724         // modification or its existence depending on warning settings.
7725         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7726         return;
7727       }
7728   }
7729 
7730   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7731     if (shadowedVar->isExternC()) {
7732       // For shadowing external vars, make sure that we point to the global
7733       // declaration, not a locally scoped extern declaration.
7734       for (auto I : shadowedVar->redecls())
7735         if (I->isFileVarDecl()) {
7736           ShadowedDecl = I;
7737           break;
7738         }
7739     }
7740 
7741   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7742 
7743   unsigned WarningDiag = diag::warn_decl_shadow;
7744   SourceLocation CaptureLoc;
7745   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7746       isa<CXXMethodDecl>(NewDC)) {
7747     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7748       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7749         if (RD->getLambdaCaptureDefault() == LCD_None) {
7750           // Try to avoid warnings for lambdas with an explicit capture list.
7751           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7752           // Warn only when the lambda captures the shadowed decl explicitly.
7753           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7754           if (CaptureLoc.isInvalid())
7755             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7756         } else {
7757           // Remember that this was shadowed so we can avoid the warning if the
7758           // shadowed decl isn't captured and the warning settings allow it.
7759           cast<LambdaScopeInfo>(getCurFunction())
7760               ->ShadowingDecls.push_back(
7761                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7762           return;
7763         }
7764       }
7765 
7766       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7767         // A variable can't shadow a local variable in an enclosing scope, if
7768         // they are separated by a non-capturing declaration context.
7769         for (DeclContext *ParentDC = NewDC;
7770              ParentDC && !ParentDC->Equals(OldDC);
7771              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7772           // Only block literals, captured statements, and lambda expressions
7773           // can capture; other scopes don't.
7774           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7775               !isLambdaCallOperator(ParentDC)) {
7776             return;
7777           }
7778         }
7779       }
7780     }
7781   }
7782 
7783   // Only warn about certain kinds of shadowing for class members.
7784   if (NewDC && NewDC->isRecord()) {
7785     // In particular, don't warn about shadowing non-class members.
7786     if (!OldDC->isRecord())
7787       return;
7788 
7789     // TODO: should we warn about static data members shadowing
7790     // static data members from base classes?
7791 
7792     // TODO: don't diagnose for inaccessible shadowed members.
7793     // This is hard to do perfectly because we might friend the
7794     // shadowing context, but that's just a false negative.
7795   }
7796 
7797 
7798   DeclarationName Name = R.getLookupName();
7799 
7800   // Emit warning and note.
7801   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7802   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7803   if (!CaptureLoc.isInvalid())
7804     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7805         << Name << /*explicitly*/ 1;
7806   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7807 }
7808 
7809 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7810 /// when these variables are captured by the lambda.
7811 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7812   for (const auto &Shadow : LSI->ShadowingDecls) {
7813     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7814     // Try to avoid the warning when the shadowed decl isn't captured.
7815     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7816     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7817     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7818                                        ? diag::warn_decl_shadow_uncaptured_local
7819                                        : diag::warn_decl_shadow)
7820         << Shadow.VD->getDeclName()
7821         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7822     if (!CaptureLoc.isInvalid())
7823       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7824           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7825     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7826   }
7827 }
7828 
7829 /// Check -Wshadow without the advantage of a previous lookup.
7830 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7831   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7832     return;
7833 
7834   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7835                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7836   LookupName(R, S);
7837   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7838     CheckShadow(D, ShadowedDecl, R);
7839 }
7840 
7841 /// Check if 'E', which is an expression that is about to be modified, refers
7842 /// to a constructor parameter that shadows a field.
7843 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7844   // Quickly ignore expressions that can't be shadowing ctor parameters.
7845   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7846     return;
7847   E = E->IgnoreParenImpCasts();
7848   auto *DRE = dyn_cast<DeclRefExpr>(E);
7849   if (!DRE)
7850     return;
7851   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7852   auto I = ShadowingDecls.find(D);
7853   if (I == ShadowingDecls.end())
7854     return;
7855   const NamedDecl *ShadowedDecl = I->second;
7856   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7857   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7858   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7859   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7860 
7861   // Avoid issuing multiple warnings about the same decl.
7862   ShadowingDecls.erase(I);
7863 }
7864 
7865 /// Check for conflict between this global or extern "C" declaration and
7866 /// previous global or extern "C" declarations. This is only used in C++.
7867 template<typename T>
7868 static bool checkGlobalOrExternCConflict(
7869     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7870   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7871   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7872 
7873   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7874     // The common case: this global doesn't conflict with any extern "C"
7875     // declaration.
7876     return false;
7877   }
7878 
7879   if (Prev) {
7880     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7881       // Both the old and new declarations have C language linkage. This is a
7882       // redeclaration.
7883       Previous.clear();
7884       Previous.addDecl(Prev);
7885       return true;
7886     }
7887 
7888     // This is a global, non-extern "C" declaration, and there is a previous
7889     // non-global extern "C" declaration. Diagnose if this is a variable
7890     // declaration.
7891     if (!isa<VarDecl>(ND))
7892       return false;
7893   } else {
7894     // The declaration is extern "C". Check for any declaration in the
7895     // translation unit which might conflict.
7896     if (IsGlobal) {
7897       // We have already performed the lookup into the translation unit.
7898       IsGlobal = false;
7899       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7900            I != E; ++I) {
7901         if (isa<VarDecl>(*I)) {
7902           Prev = *I;
7903           break;
7904         }
7905       }
7906     } else {
7907       DeclContext::lookup_result R =
7908           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7909       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7910            I != E; ++I) {
7911         if (isa<VarDecl>(*I)) {
7912           Prev = *I;
7913           break;
7914         }
7915         // FIXME: If we have any other entity with this name in global scope,
7916         // the declaration is ill-formed, but that is a defect: it breaks the
7917         // 'stat' hack, for instance. Only variables can have mangled name
7918         // clashes with extern "C" declarations, so only they deserve a
7919         // diagnostic.
7920       }
7921     }
7922 
7923     if (!Prev)
7924       return false;
7925   }
7926 
7927   // Use the first declaration's location to ensure we point at something which
7928   // is lexically inside an extern "C" linkage-spec.
7929   assert(Prev && "should have found a previous declaration to diagnose");
7930   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7931     Prev = FD->getFirstDecl();
7932   else
7933     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7934 
7935   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7936     << IsGlobal << ND;
7937   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7938     << IsGlobal;
7939   return false;
7940 }
7941 
7942 /// Apply special rules for handling extern "C" declarations. Returns \c true
7943 /// if we have found that this is a redeclaration of some prior entity.
7944 ///
7945 /// Per C++ [dcl.link]p6:
7946 ///   Two declarations [for a function or variable] with C language linkage
7947 ///   with the same name that appear in different scopes refer to the same
7948 ///   [entity]. An entity with C language linkage shall not be declared with
7949 ///   the same name as an entity in global scope.
7950 template<typename T>
7951 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7952                                                   LookupResult &Previous) {
7953   if (!S.getLangOpts().CPlusPlus) {
7954     // In C, when declaring a global variable, look for a corresponding 'extern'
7955     // variable declared in function scope. We don't need this in C++, because
7956     // we find local extern decls in the surrounding file-scope DeclContext.
7957     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7958       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7959         Previous.clear();
7960         Previous.addDecl(Prev);
7961         return true;
7962       }
7963     }
7964     return false;
7965   }
7966 
7967   // A declaration in the translation unit can conflict with an extern "C"
7968   // declaration.
7969   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7970     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7971 
7972   // An extern "C" declaration can conflict with a declaration in the
7973   // translation unit or can be a redeclaration of an extern "C" declaration
7974   // in another scope.
7975   if (isIncompleteDeclExternC(S,ND))
7976     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7977 
7978   // Neither global nor extern "C": nothing to do.
7979   return false;
7980 }
7981 
7982 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7983   // If the decl is already known invalid, don't check it.
7984   if (NewVD->isInvalidDecl())
7985     return;
7986 
7987   QualType T = NewVD->getType();
7988 
7989   // Defer checking an 'auto' type until its initializer is attached.
7990   if (T->isUndeducedType())
7991     return;
7992 
7993   if (NewVD->hasAttrs())
7994     CheckAlignasUnderalignment(NewVD);
7995 
7996   if (T->isObjCObjectType()) {
7997     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7998       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7999     T = Context.getObjCObjectPointerType(T);
8000     NewVD->setType(T);
8001   }
8002 
8003   // Emit an error if an address space was applied to decl with local storage.
8004   // This includes arrays of objects with address space qualifiers, but not
8005   // automatic variables that point to other address spaces.
8006   // ISO/IEC TR 18037 S5.1.2
8007   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8008       T.getAddressSpace() != LangAS::Default) {
8009     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8010     NewVD->setInvalidDecl();
8011     return;
8012   }
8013 
8014   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8015   // scope.
8016   if (getLangOpts().OpenCLVersion == 120 &&
8017       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8018                                             getLangOpts()) &&
8019       NewVD->isStaticLocal()) {
8020     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8021     NewVD->setInvalidDecl();
8022     return;
8023   }
8024 
8025   if (getLangOpts().OpenCL) {
8026     if (!diagnoseOpenCLTypes(*this, NewVD))
8027       return;
8028 
8029     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8030     if (NewVD->hasAttr<BlocksAttr>()) {
8031       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8032       return;
8033     }
8034 
8035     if (T->isBlockPointerType()) {
8036       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8037       // can't use 'extern' storage class.
8038       if (!T.isConstQualified()) {
8039         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8040             << 0 /*const*/;
8041         NewVD->setInvalidDecl();
8042         return;
8043       }
8044       if (NewVD->hasExternalStorage()) {
8045         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8046         NewVD->setInvalidDecl();
8047         return;
8048       }
8049     }
8050 
8051     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8052     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8053         NewVD->hasExternalStorage()) {
8054       if (!T->isSamplerT() && !T->isDependentType() &&
8055           !(T.getAddressSpace() == LangAS::opencl_constant ||
8056             (T.getAddressSpace() == LangAS::opencl_global &&
8057              getOpenCLOptions().areProgramScopeVariablesSupported(
8058                  getLangOpts())))) {
8059         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8060         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8061           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8062               << Scope << "global or constant";
8063         else
8064           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8065               << Scope << "constant";
8066         NewVD->setInvalidDecl();
8067         return;
8068       }
8069     } else {
8070       if (T.getAddressSpace() == LangAS::opencl_global) {
8071         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8072             << 1 /*is any function*/ << "global";
8073         NewVD->setInvalidDecl();
8074         return;
8075       }
8076       if (T.getAddressSpace() == LangAS::opencl_constant ||
8077           T.getAddressSpace() == LangAS::opencl_local) {
8078         FunctionDecl *FD = getCurFunctionDecl();
8079         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8080         // in functions.
8081         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8082           if (T.getAddressSpace() == LangAS::opencl_constant)
8083             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8084                 << 0 /*non-kernel only*/ << "constant";
8085           else
8086             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8087                 << 0 /*non-kernel only*/ << "local";
8088           NewVD->setInvalidDecl();
8089           return;
8090         }
8091         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8092         // in the outermost scope of a kernel function.
8093         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8094           if (!getCurScope()->isFunctionScope()) {
8095             if (T.getAddressSpace() == LangAS::opencl_constant)
8096               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8097                   << "constant";
8098             else
8099               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8100                   << "local";
8101             NewVD->setInvalidDecl();
8102             return;
8103           }
8104         }
8105       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8106                  // If we are parsing a template we didn't deduce an addr
8107                  // space yet.
8108                  T.getAddressSpace() != LangAS::Default) {
8109         // Do not allow other address spaces on automatic variable.
8110         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8111         NewVD->setInvalidDecl();
8112         return;
8113       }
8114     }
8115   }
8116 
8117   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8118       && !NewVD->hasAttr<BlocksAttr>()) {
8119     if (getLangOpts().getGC() != LangOptions::NonGC)
8120       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8121     else {
8122       assert(!getLangOpts().ObjCAutoRefCount);
8123       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8124     }
8125   }
8126 
8127   bool isVM = T->isVariablyModifiedType();
8128   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8129       NewVD->hasAttr<BlocksAttr>())
8130     setFunctionHasBranchProtectedScope();
8131 
8132   if ((isVM && NewVD->hasLinkage()) ||
8133       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8134     bool SizeIsNegative;
8135     llvm::APSInt Oversized;
8136     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8137         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8138     QualType FixedT;
8139     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8140       FixedT = FixedTInfo->getType();
8141     else if (FixedTInfo) {
8142       // Type and type-as-written are canonically different. We need to fix up
8143       // both types separately.
8144       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8145                                                    Oversized);
8146     }
8147     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8148       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8149       // FIXME: This won't give the correct result for
8150       // int a[10][n];
8151       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8152 
8153       if (NewVD->isFileVarDecl())
8154         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8155         << SizeRange;
8156       else if (NewVD->isStaticLocal())
8157         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8158         << SizeRange;
8159       else
8160         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8161         << SizeRange;
8162       NewVD->setInvalidDecl();
8163       return;
8164     }
8165 
8166     if (!FixedTInfo) {
8167       if (NewVD->isFileVarDecl())
8168         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8169       else
8170         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8171       NewVD->setInvalidDecl();
8172       return;
8173     }
8174 
8175     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8176     NewVD->setType(FixedT);
8177     NewVD->setTypeSourceInfo(FixedTInfo);
8178   }
8179 
8180   if (T->isVoidType()) {
8181     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8182     //                    of objects and functions.
8183     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8184       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8185         << T;
8186       NewVD->setInvalidDecl();
8187       return;
8188     }
8189   }
8190 
8191   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8192     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8193     NewVD->setInvalidDecl();
8194     return;
8195   }
8196 
8197   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8198     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8199     NewVD->setInvalidDecl();
8200     return;
8201   }
8202 
8203   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8204     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8205     NewVD->setInvalidDecl();
8206     return;
8207   }
8208 
8209   if (NewVD->isConstexpr() && !T->isDependentType() &&
8210       RequireLiteralType(NewVD->getLocation(), T,
8211                          diag::err_constexpr_var_non_literal)) {
8212     NewVD->setInvalidDecl();
8213     return;
8214   }
8215 
8216   // PPC MMA non-pointer types are not allowed as non-local variable types.
8217   if (Context.getTargetInfo().getTriple().isPPC64() &&
8218       !NewVD->isLocalVarDecl() &&
8219       CheckPPCMMAType(T, NewVD->getLocation())) {
8220     NewVD->setInvalidDecl();
8221     return;
8222   }
8223 }
8224 
8225 /// Perform semantic checking on a newly-created variable
8226 /// declaration.
8227 ///
8228 /// This routine performs all of the type-checking required for a
8229 /// variable declaration once it has been built. It is used both to
8230 /// check variables after they have been parsed and their declarators
8231 /// have been translated into a declaration, and to check variables
8232 /// that have been instantiated from a template.
8233 ///
8234 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8235 ///
8236 /// Returns true if the variable declaration is a redeclaration.
8237 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8238   CheckVariableDeclarationType(NewVD);
8239 
8240   // If the decl is already known invalid, don't check it.
8241   if (NewVD->isInvalidDecl())
8242     return false;
8243 
8244   // If we did not find anything by this name, look for a non-visible
8245   // extern "C" declaration with the same name.
8246   if (Previous.empty() &&
8247       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8248     Previous.setShadowed();
8249 
8250   if (!Previous.empty()) {
8251     MergeVarDecl(NewVD, Previous);
8252     return true;
8253   }
8254   return false;
8255 }
8256 
8257 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8258 /// and if so, check that it's a valid override and remember it.
8259 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8260   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8261 
8262   // Look for methods in base classes that this method might override.
8263   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8264                      /*DetectVirtual=*/false);
8265   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8266     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8267     DeclarationName Name = MD->getDeclName();
8268 
8269     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8270       // We really want to find the base class destructor here.
8271       QualType T = Context.getTypeDeclType(BaseRecord);
8272       CanQualType CT = Context.getCanonicalType(T);
8273       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8274     }
8275 
8276     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8277       CXXMethodDecl *BaseMD =
8278           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8279       if (!BaseMD || !BaseMD->isVirtual() ||
8280           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8281                      /*ConsiderCudaAttrs=*/true,
8282                      // C++2a [class.virtual]p2 does not consider requires
8283                      // clauses when overriding.
8284                      /*ConsiderRequiresClauses=*/false))
8285         continue;
8286 
8287       if (Overridden.insert(BaseMD).second) {
8288         MD->addOverriddenMethod(BaseMD);
8289         CheckOverridingFunctionReturnType(MD, BaseMD);
8290         CheckOverridingFunctionAttributes(MD, BaseMD);
8291         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8292         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8293       }
8294 
8295       // A method can only override one function from each base class. We
8296       // don't track indirectly overridden methods from bases of bases.
8297       return true;
8298     }
8299 
8300     return false;
8301   };
8302 
8303   DC->lookupInBases(VisitBase, Paths);
8304   return !Overridden.empty();
8305 }
8306 
8307 namespace {
8308   // Struct for holding all of the extra arguments needed by
8309   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8310   struct ActOnFDArgs {
8311     Scope *S;
8312     Declarator &D;
8313     MultiTemplateParamsArg TemplateParamLists;
8314     bool AddToScope;
8315   };
8316 } // end anonymous namespace
8317 
8318 namespace {
8319 
8320 // Callback to only accept typo corrections that have a non-zero edit distance.
8321 // Also only accept corrections that have the same parent decl.
8322 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8323  public:
8324   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8325                             CXXRecordDecl *Parent)
8326       : Context(Context), OriginalFD(TypoFD),
8327         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8328 
8329   bool ValidateCandidate(const TypoCorrection &candidate) override {
8330     if (candidate.getEditDistance() == 0)
8331       return false;
8332 
8333     SmallVector<unsigned, 1> MismatchedParams;
8334     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8335                                           CDeclEnd = candidate.end();
8336          CDecl != CDeclEnd; ++CDecl) {
8337       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8338 
8339       if (FD && !FD->hasBody() &&
8340           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8341         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8342           CXXRecordDecl *Parent = MD->getParent();
8343           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8344             return true;
8345         } else if (!ExpectedParent) {
8346           return true;
8347         }
8348       }
8349     }
8350 
8351     return false;
8352   }
8353 
8354   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8355     return std::make_unique<DifferentNameValidatorCCC>(*this);
8356   }
8357 
8358  private:
8359   ASTContext &Context;
8360   FunctionDecl *OriginalFD;
8361   CXXRecordDecl *ExpectedParent;
8362 };
8363 
8364 } // end anonymous namespace
8365 
8366 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8367   TypoCorrectedFunctionDefinitions.insert(F);
8368 }
8369 
8370 /// Generate diagnostics for an invalid function redeclaration.
8371 ///
8372 /// This routine handles generating the diagnostic messages for an invalid
8373 /// function redeclaration, including finding possible similar declarations
8374 /// or performing typo correction if there are no previous declarations with
8375 /// the same name.
8376 ///
8377 /// Returns a NamedDecl iff typo correction was performed and substituting in
8378 /// the new declaration name does not cause new errors.
8379 static NamedDecl *DiagnoseInvalidRedeclaration(
8380     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8381     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8382   DeclarationName Name = NewFD->getDeclName();
8383   DeclContext *NewDC = NewFD->getDeclContext();
8384   SmallVector<unsigned, 1> MismatchedParams;
8385   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8386   TypoCorrection Correction;
8387   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8388   unsigned DiagMsg =
8389     IsLocalFriend ? diag::err_no_matching_local_friend :
8390     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8391     diag::err_member_decl_does_not_match;
8392   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8393                     IsLocalFriend ? Sema::LookupLocalFriendName
8394                                   : Sema::LookupOrdinaryName,
8395                     Sema::ForVisibleRedeclaration);
8396 
8397   NewFD->setInvalidDecl();
8398   if (IsLocalFriend)
8399     SemaRef.LookupName(Prev, S);
8400   else
8401     SemaRef.LookupQualifiedName(Prev, NewDC);
8402   assert(!Prev.isAmbiguous() &&
8403          "Cannot have an ambiguity in previous-declaration lookup");
8404   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8405   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8406                                 MD ? MD->getParent() : nullptr);
8407   if (!Prev.empty()) {
8408     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8409          Func != FuncEnd; ++Func) {
8410       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8411       if (FD &&
8412           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8413         // Add 1 to the index so that 0 can mean the mismatch didn't
8414         // involve a parameter
8415         unsigned ParamNum =
8416             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8417         NearMatches.push_back(std::make_pair(FD, ParamNum));
8418       }
8419     }
8420   // If the qualified name lookup yielded nothing, try typo correction
8421   } else if ((Correction = SemaRef.CorrectTypo(
8422                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8423                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8424                   IsLocalFriend ? nullptr : NewDC))) {
8425     // Set up everything for the call to ActOnFunctionDeclarator
8426     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8427                               ExtraArgs.D.getIdentifierLoc());
8428     Previous.clear();
8429     Previous.setLookupName(Correction.getCorrection());
8430     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8431                                     CDeclEnd = Correction.end();
8432          CDecl != CDeclEnd; ++CDecl) {
8433       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8434       if (FD && !FD->hasBody() &&
8435           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8436         Previous.addDecl(FD);
8437       }
8438     }
8439     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8440 
8441     NamedDecl *Result;
8442     // Retry building the function declaration with the new previous
8443     // declarations, and with errors suppressed.
8444     {
8445       // Trap errors.
8446       Sema::SFINAETrap Trap(SemaRef);
8447 
8448       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8449       // pieces need to verify the typo-corrected C++ declaration and hopefully
8450       // eliminate the need for the parameter pack ExtraArgs.
8451       Result = SemaRef.ActOnFunctionDeclarator(
8452           ExtraArgs.S, ExtraArgs.D,
8453           Correction.getCorrectionDecl()->getDeclContext(),
8454           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8455           ExtraArgs.AddToScope);
8456 
8457       if (Trap.hasErrorOccurred())
8458         Result = nullptr;
8459     }
8460 
8461     if (Result) {
8462       // Determine which correction we picked.
8463       Decl *Canonical = Result->getCanonicalDecl();
8464       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8465            I != E; ++I)
8466         if ((*I)->getCanonicalDecl() == Canonical)
8467           Correction.setCorrectionDecl(*I);
8468 
8469       // Let Sema know about the correction.
8470       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8471       SemaRef.diagnoseTypo(
8472           Correction,
8473           SemaRef.PDiag(IsLocalFriend
8474                           ? diag::err_no_matching_local_friend_suggest
8475                           : diag::err_member_decl_does_not_match_suggest)
8476             << Name << NewDC << IsDefinition);
8477       return Result;
8478     }
8479 
8480     // Pretend the typo correction never occurred
8481     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8482                               ExtraArgs.D.getIdentifierLoc());
8483     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8484     Previous.clear();
8485     Previous.setLookupName(Name);
8486   }
8487 
8488   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8489       << Name << NewDC << IsDefinition << NewFD->getLocation();
8490 
8491   bool NewFDisConst = false;
8492   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8493     NewFDisConst = NewMD->isConst();
8494 
8495   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8496        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8497        NearMatch != NearMatchEnd; ++NearMatch) {
8498     FunctionDecl *FD = NearMatch->first;
8499     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8500     bool FDisConst = MD && MD->isConst();
8501     bool IsMember = MD || !IsLocalFriend;
8502 
8503     // FIXME: These notes are poorly worded for the local friend case.
8504     if (unsigned Idx = NearMatch->second) {
8505       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8506       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8507       if (Loc.isInvalid()) Loc = FD->getLocation();
8508       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8509                                  : diag::note_local_decl_close_param_match)
8510         << Idx << FDParam->getType()
8511         << NewFD->getParamDecl(Idx - 1)->getType();
8512     } else if (FDisConst != NewFDisConst) {
8513       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8514           << NewFDisConst << FD->getSourceRange().getEnd()
8515           << (NewFDisConst
8516                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8517                                                  .getConstQualifierLoc())
8518                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8519                                                    .getRParenLoc()
8520                                                    .getLocWithOffset(1),
8521                                                " const"));
8522     } else
8523       SemaRef.Diag(FD->getLocation(),
8524                    IsMember ? diag::note_member_def_close_match
8525                             : diag::note_local_decl_close_match);
8526   }
8527   return nullptr;
8528 }
8529 
8530 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8531   switch (D.getDeclSpec().getStorageClassSpec()) {
8532   default: llvm_unreachable("Unknown storage class!");
8533   case DeclSpec::SCS_auto:
8534   case DeclSpec::SCS_register:
8535   case DeclSpec::SCS_mutable:
8536     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8537                  diag::err_typecheck_sclass_func);
8538     D.getMutableDeclSpec().ClearStorageClassSpecs();
8539     D.setInvalidType();
8540     break;
8541   case DeclSpec::SCS_unspecified: break;
8542   case DeclSpec::SCS_extern:
8543     if (D.getDeclSpec().isExternInLinkageSpec())
8544       return SC_None;
8545     return SC_Extern;
8546   case DeclSpec::SCS_static: {
8547     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8548       // C99 6.7.1p5:
8549       //   The declaration of an identifier for a function that has
8550       //   block scope shall have no explicit storage-class specifier
8551       //   other than extern
8552       // See also (C++ [dcl.stc]p4).
8553       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8554                    diag::err_static_block_func);
8555       break;
8556     } else
8557       return SC_Static;
8558   }
8559   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8560   }
8561 
8562   // No explicit storage class has already been returned
8563   return SC_None;
8564 }
8565 
8566 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8567                                            DeclContext *DC, QualType &R,
8568                                            TypeSourceInfo *TInfo,
8569                                            StorageClass SC,
8570                                            bool &IsVirtualOkay) {
8571   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8572   DeclarationName Name = NameInfo.getName();
8573 
8574   FunctionDecl *NewFD = nullptr;
8575   bool isInline = D.getDeclSpec().isInlineSpecified();
8576 
8577   if (!SemaRef.getLangOpts().CPlusPlus) {
8578     // Determine whether the function was written with a
8579     // prototype. This true when:
8580     //   - there is a prototype in the declarator, or
8581     //   - the type R of the function is some kind of typedef or other non-
8582     //     attributed reference to a type name (which eventually refers to a
8583     //     function type).
8584     bool HasPrototype =
8585       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8586       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8587 
8588     NewFD = FunctionDecl::Create(
8589         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8590         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8591         ConstexprSpecKind::Unspecified,
8592         /*TrailingRequiresClause=*/nullptr);
8593     if (D.isInvalidType())
8594       NewFD->setInvalidDecl();
8595 
8596     return NewFD;
8597   }
8598 
8599   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8600 
8601   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8602   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8603     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8604                  diag::err_constexpr_wrong_decl_kind)
8605         << static_cast<int>(ConstexprKind);
8606     ConstexprKind = ConstexprSpecKind::Unspecified;
8607     D.getMutableDeclSpec().ClearConstexprSpec();
8608   }
8609   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8610 
8611   // Check that the return type is not an abstract class type.
8612   // For record types, this is done by the AbstractClassUsageDiagnoser once
8613   // the class has been completely parsed.
8614   if (!DC->isRecord() &&
8615       SemaRef.RequireNonAbstractType(
8616           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8617           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8618     D.setInvalidType();
8619 
8620   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8621     // This is a C++ constructor declaration.
8622     assert(DC->isRecord() &&
8623            "Constructors can only be declared in a member context");
8624 
8625     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8626     return CXXConstructorDecl::Create(
8627         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8628         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8629         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8630         InheritedConstructor(), TrailingRequiresClause);
8631 
8632   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8633     // This is a C++ destructor declaration.
8634     if (DC->isRecord()) {
8635       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8636       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8637       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8638           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8639           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8640           /*isImplicitlyDeclared=*/false, ConstexprKind,
8641           TrailingRequiresClause);
8642 
8643       // If the destructor needs an implicit exception specification, set it
8644       // now. FIXME: It'd be nice to be able to create the right type to start
8645       // with, but the type needs to reference the destructor declaration.
8646       if (SemaRef.getLangOpts().CPlusPlus11)
8647         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8648 
8649       IsVirtualOkay = true;
8650       return NewDD;
8651 
8652     } else {
8653       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8654       D.setInvalidType();
8655 
8656       // Create a FunctionDecl to satisfy the function definition parsing
8657       // code path.
8658       return FunctionDecl::Create(
8659           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8660           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8661           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8662     }
8663 
8664   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8665     if (!DC->isRecord()) {
8666       SemaRef.Diag(D.getIdentifierLoc(),
8667            diag::err_conv_function_not_member);
8668       return nullptr;
8669     }
8670 
8671     SemaRef.CheckConversionDeclarator(D, R, SC);
8672     if (D.isInvalidType())
8673       return nullptr;
8674 
8675     IsVirtualOkay = true;
8676     return CXXConversionDecl::Create(
8677         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8678         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8679         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8680         TrailingRequiresClause);
8681 
8682   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8683     if (TrailingRequiresClause)
8684       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8685                    diag::err_trailing_requires_clause_on_deduction_guide)
8686           << TrailingRequiresClause->getSourceRange();
8687     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8688 
8689     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8690                                          ExplicitSpecifier, NameInfo, R, TInfo,
8691                                          D.getEndLoc());
8692   } else if (DC->isRecord()) {
8693     // If the name of the function is the same as the name of the record,
8694     // then this must be an invalid constructor that has a return type.
8695     // (The parser checks for a return type and makes the declarator a
8696     // constructor if it has no return type).
8697     if (Name.getAsIdentifierInfo() &&
8698         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8699       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8700         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8701         << SourceRange(D.getIdentifierLoc());
8702       return nullptr;
8703     }
8704 
8705     // This is a C++ method declaration.
8706     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8707         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8708         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8709         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8710     IsVirtualOkay = !Ret->isStatic();
8711     return Ret;
8712   } else {
8713     bool isFriend =
8714         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8715     if (!isFriend && SemaRef.CurContext->isRecord())
8716       return nullptr;
8717 
8718     // Determine whether the function was written with a
8719     // prototype. This true when:
8720     //   - we're in C++ (where every function has a prototype),
8721     return FunctionDecl::Create(
8722         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8723         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8724         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8725   }
8726 }
8727 
8728 enum OpenCLParamType {
8729   ValidKernelParam,
8730   PtrPtrKernelParam,
8731   PtrKernelParam,
8732   InvalidAddrSpacePtrKernelParam,
8733   InvalidKernelParam,
8734   RecordKernelParam
8735 };
8736 
8737 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8738   // Size dependent types are just typedefs to normal integer types
8739   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8740   // integers other than by their names.
8741   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8742 
8743   // Remove typedefs one by one until we reach a typedef
8744   // for a size dependent type.
8745   QualType DesugaredTy = Ty;
8746   do {
8747     ArrayRef<StringRef> Names(SizeTypeNames);
8748     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8749     if (Names.end() != Match)
8750       return true;
8751 
8752     Ty = DesugaredTy;
8753     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8754   } while (DesugaredTy != Ty);
8755 
8756   return false;
8757 }
8758 
8759 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8760   if (PT->isDependentType())
8761     return InvalidKernelParam;
8762 
8763   if (PT->isPointerType() || PT->isReferenceType()) {
8764     QualType PointeeType = PT->getPointeeType();
8765     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8766         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8767         PointeeType.getAddressSpace() == LangAS::Default)
8768       return InvalidAddrSpacePtrKernelParam;
8769 
8770     if (PointeeType->isPointerType()) {
8771       // This is a pointer to pointer parameter.
8772       // Recursively check inner type.
8773       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8774       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8775           ParamKind == InvalidKernelParam)
8776         return ParamKind;
8777 
8778       return PtrPtrKernelParam;
8779     }
8780 
8781     // C++ for OpenCL v1.0 s2.4:
8782     // Moreover the types used in parameters of the kernel functions must be:
8783     // Standard layout types for pointer parameters. The same applies to
8784     // reference if an implementation supports them in kernel parameters.
8785     if (S.getLangOpts().OpenCLCPlusPlus &&
8786         !S.getOpenCLOptions().isAvailableOption(
8787             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8788         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8789         !PointeeType->isStandardLayoutType())
8790       return InvalidKernelParam;
8791 
8792     return PtrKernelParam;
8793   }
8794 
8795   // OpenCL v1.2 s6.9.k:
8796   // Arguments to kernel functions in a program cannot be declared with the
8797   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8798   // uintptr_t or a struct and/or union that contain fields declared to be one
8799   // of these built-in scalar types.
8800   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8801     return InvalidKernelParam;
8802 
8803   if (PT->isImageType())
8804     return PtrKernelParam;
8805 
8806   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8807     return InvalidKernelParam;
8808 
8809   // OpenCL extension spec v1.2 s9.5:
8810   // This extension adds support for half scalar and vector types as built-in
8811   // types that can be used for arithmetic operations, conversions etc.
8812   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8813       PT->isHalfType())
8814     return InvalidKernelParam;
8815 
8816   // Look into an array argument to check if it has a forbidden type.
8817   if (PT->isArrayType()) {
8818     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8819     // Call ourself to check an underlying type of an array. Since the
8820     // getPointeeOrArrayElementType returns an innermost type which is not an
8821     // array, this recursive call only happens once.
8822     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8823   }
8824 
8825   // C++ for OpenCL v1.0 s2.4:
8826   // Moreover the types used in parameters of the kernel functions must be:
8827   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8828   // types) for parameters passed by value;
8829   if (S.getLangOpts().OpenCLCPlusPlus &&
8830       !S.getOpenCLOptions().isAvailableOption(
8831           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8832       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8833     return InvalidKernelParam;
8834 
8835   if (PT->isRecordType())
8836     return RecordKernelParam;
8837 
8838   return ValidKernelParam;
8839 }
8840 
8841 static void checkIsValidOpenCLKernelParameter(
8842   Sema &S,
8843   Declarator &D,
8844   ParmVarDecl *Param,
8845   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8846   QualType PT = Param->getType();
8847 
8848   // Cache the valid types we encounter to avoid rechecking structs that are
8849   // used again
8850   if (ValidTypes.count(PT.getTypePtr()))
8851     return;
8852 
8853   switch (getOpenCLKernelParameterType(S, PT)) {
8854   case PtrPtrKernelParam:
8855     // OpenCL v3.0 s6.11.a:
8856     // A kernel function argument cannot be declared as a pointer to a pointer
8857     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8858     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8859       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8860       D.setInvalidType();
8861       return;
8862     }
8863 
8864     ValidTypes.insert(PT.getTypePtr());
8865     return;
8866 
8867   case InvalidAddrSpacePtrKernelParam:
8868     // OpenCL v1.0 s6.5:
8869     // __kernel function arguments declared to be a pointer of a type can point
8870     // to one of the following address spaces only : __global, __local or
8871     // __constant.
8872     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8873     D.setInvalidType();
8874     return;
8875 
8876     // OpenCL v1.2 s6.9.k:
8877     // Arguments to kernel functions in a program cannot be declared with the
8878     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8879     // uintptr_t or a struct and/or union that contain fields declared to be
8880     // one of these built-in scalar types.
8881 
8882   case InvalidKernelParam:
8883     // OpenCL v1.2 s6.8 n:
8884     // A kernel function argument cannot be declared
8885     // of event_t type.
8886     // Do not diagnose half type since it is diagnosed as invalid argument
8887     // type for any function elsewhere.
8888     if (!PT->isHalfType()) {
8889       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8890 
8891       // Explain what typedefs are involved.
8892       const TypedefType *Typedef = nullptr;
8893       while ((Typedef = PT->getAs<TypedefType>())) {
8894         SourceLocation Loc = Typedef->getDecl()->getLocation();
8895         // SourceLocation may be invalid for a built-in type.
8896         if (Loc.isValid())
8897           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8898         PT = Typedef->desugar();
8899       }
8900     }
8901 
8902     D.setInvalidType();
8903     return;
8904 
8905   case PtrKernelParam:
8906   case ValidKernelParam:
8907     ValidTypes.insert(PT.getTypePtr());
8908     return;
8909 
8910   case RecordKernelParam:
8911     break;
8912   }
8913 
8914   // Track nested structs we will inspect
8915   SmallVector<const Decl *, 4> VisitStack;
8916 
8917   // Track where we are in the nested structs. Items will migrate from
8918   // VisitStack to HistoryStack as we do the DFS for bad field.
8919   SmallVector<const FieldDecl *, 4> HistoryStack;
8920   HistoryStack.push_back(nullptr);
8921 
8922   // At this point we already handled everything except of a RecordType or
8923   // an ArrayType of a RecordType.
8924   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8925   const RecordType *RecTy =
8926       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8927   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8928 
8929   VisitStack.push_back(RecTy->getDecl());
8930   assert(VisitStack.back() && "First decl null?");
8931 
8932   do {
8933     const Decl *Next = VisitStack.pop_back_val();
8934     if (!Next) {
8935       assert(!HistoryStack.empty());
8936       // Found a marker, we have gone up a level
8937       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8938         ValidTypes.insert(Hist->getType().getTypePtr());
8939 
8940       continue;
8941     }
8942 
8943     // Adds everything except the original parameter declaration (which is not a
8944     // field itself) to the history stack.
8945     const RecordDecl *RD;
8946     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8947       HistoryStack.push_back(Field);
8948 
8949       QualType FieldTy = Field->getType();
8950       // Other field types (known to be valid or invalid) are handled while we
8951       // walk around RecordDecl::fields().
8952       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8953              "Unexpected type.");
8954       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8955 
8956       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8957     } else {
8958       RD = cast<RecordDecl>(Next);
8959     }
8960 
8961     // Add a null marker so we know when we've gone back up a level
8962     VisitStack.push_back(nullptr);
8963 
8964     for (const auto *FD : RD->fields()) {
8965       QualType QT = FD->getType();
8966 
8967       if (ValidTypes.count(QT.getTypePtr()))
8968         continue;
8969 
8970       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8971       if (ParamType == ValidKernelParam)
8972         continue;
8973 
8974       if (ParamType == RecordKernelParam) {
8975         VisitStack.push_back(FD);
8976         continue;
8977       }
8978 
8979       // OpenCL v1.2 s6.9.p:
8980       // Arguments to kernel functions that are declared to be a struct or union
8981       // do not allow OpenCL objects to be passed as elements of the struct or
8982       // union.
8983       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8984           ParamType == InvalidAddrSpacePtrKernelParam) {
8985         S.Diag(Param->getLocation(),
8986                diag::err_record_with_pointers_kernel_param)
8987           << PT->isUnionType()
8988           << PT;
8989       } else {
8990         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8991       }
8992 
8993       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8994           << OrigRecDecl->getDeclName();
8995 
8996       // We have an error, now let's go back up through history and show where
8997       // the offending field came from
8998       for (ArrayRef<const FieldDecl *>::const_iterator
8999                I = HistoryStack.begin() + 1,
9000                E = HistoryStack.end();
9001            I != E; ++I) {
9002         const FieldDecl *OuterField = *I;
9003         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9004           << OuterField->getType();
9005       }
9006 
9007       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9008         << QT->isPointerType()
9009         << QT;
9010       D.setInvalidType();
9011       return;
9012     }
9013   } while (!VisitStack.empty());
9014 }
9015 
9016 /// Find the DeclContext in which a tag is implicitly declared if we see an
9017 /// elaborated type specifier in the specified context, and lookup finds
9018 /// nothing.
9019 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9020   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9021     DC = DC->getParent();
9022   return DC;
9023 }
9024 
9025 /// Find the Scope in which a tag is implicitly declared if we see an
9026 /// elaborated type specifier in the specified context, and lookup finds
9027 /// nothing.
9028 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9029   while (S->isClassScope() ||
9030          (LangOpts.CPlusPlus &&
9031           S->isFunctionPrototypeScope()) ||
9032          ((S->getFlags() & Scope::DeclScope) == 0) ||
9033          (S->getEntity() && S->getEntity()->isTransparentContext()))
9034     S = S->getParent();
9035   return S;
9036 }
9037 
9038 NamedDecl*
9039 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9040                               TypeSourceInfo *TInfo, LookupResult &Previous,
9041                               MultiTemplateParamsArg TemplateParamListsRef,
9042                               bool &AddToScope) {
9043   QualType R = TInfo->getType();
9044 
9045   assert(R->isFunctionType());
9046   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9047     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9048 
9049   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9050   for (TemplateParameterList *TPL : TemplateParamListsRef)
9051     TemplateParamLists.push_back(TPL);
9052   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9053     if (!TemplateParamLists.empty() &&
9054         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9055       TemplateParamLists.back() = Invented;
9056     else
9057       TemplateParamLists.push_back(Invented);
9058   }
9059 
9060   // TODO: consider using NameInfo for diagnostic.
9061   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9062   DeclarationName Name = NameInfo.getName();
9063   StorageClass SC = getFunctionStorageClass(*this, D);
9064 
9065   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9066     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9067          diag::err_invalid_thread)
9068       << DeclSpec::getSpecifierName(TSCS);
9069 
9070   if (D.isFirstDeclarationOfMember())
9071     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9072                            D.getIdentifierLoc());
9073 
9074   bool isFriend = false;
9075   FunctionTemplateDecl *FunctionTemplate = nullptr;
9076   bool isMemberSpecialization = false;
9077   bool isFunctionTemplateSpecialization = false;
9078 
9079   bool isDependentClassScopeExplicitSpecialization = false;
9080   bool HasExplicitTemplateArgs = false;
9081   TemplateArgumentListInfo TemplateArgs;
9082 
9083   bool isVirtualOkay = false;
9084 
9085   DeclContext *OriginalDC = DC;
9086   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9087 
9088   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9089                                               isVirtualOkay);
9090   if (!NewFD) return nullptr;
9091 
9092   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9093     NewFD->setTopLevelDeclInObjCContainer();
9094 
9095   // Set the lexical context. If this is a function-scope declaration, or has a
9096   // C++ scope specifier, or is the object of a friend declaration, the lexical
9097   // context will be different from the semantic context.
9098   NewFD->setLexicalDeclContext(CurContext);
9099 
9100   if (IsLocalExternDecl)
9101     NewFD->setLocalExternDecl();
9102 
9103   if (getLangOpts().CPlusPlus) {
9104     bool isInline = D.getDeclSpec().isInlineSpecified();
9105     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9106     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9107     isFriend = D.getDeclSpec().isFriendSpecified();
9108     if (isFriend && !isInline && D.isFunctionDefinition()) {
9109       // C++ [class.friend]p5
9110       //   A function can be defined in a friend declaration of a
9111       //   class . . . . Such a function is implicitly inline.
9112       NewFD->setImplicitlyInline();
9113     }
9114 
9115     // If this is a method defined in an __interface, and is not a constructor
9116     // or an overloaded operator, then set the pure flag (isVirtual will already
9117     // return true).
9118     if (const CXXRecordDecl *Parent =
9119           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9120       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9121         NewFD->setPure(true);
9122 
9123       // C++ [class.union]p2
9124       //   A union can have member functions, but not virtual functions.
9125       if (isVirtual && Parent->isUnion()) {
9126         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9127         NewFD->setInvalidDecl();
9128       }
9129     }
9130 
9131     SetNestedNameSpecifier(*this, NewFD, D);
9132     isMemberSpecialization = false;
9133     isFunctionTemplateSpecialization = false;
9134     if (D.isInvalidType())
9135       NewFD->setInvalidDecl();
9136 
9137     // Match up the template parameter lists with the scope specifier, then
9138     // determine whether we have a template or a template specialization.
9139     bool Invalid = false;
9140     TemplateParameterList *TemplateParams =
9141         MatchTemplateParametersToScopeSpecifier(
9142             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9143             D.getCXXScopeSpec(),
9144             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9145                 ? D.getName().TemplateId
9146                 : nullptr,
9147             TemplateParamLists, isFriend, isMemberSpecialization,
9148             Invalid);
9149     if (TemplateParams) {
9150       // Check that we can declare a template here.
9151       if (CheckTemplateDeclScope(S, TemplateParams))
9152         NewFD->setInvalidDecl();
9153 
9154       if (TemplateParams->size() > 0) {
9155         // This is a function template
9156 
9157         // A destructor cannot be a template.
9158         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9159           Diag(NewFD->getLocation(), diag::err_destructor_template);
9160           NewFD->setInvalidDecl();
9161         }
9162 
9163         // If we're adding a template to a dependent context, we may need to
9164         // rebuilding some of the types used within the template parameter list,
9165         // now that we know what the current instantiation is.
9166         if (DC->isDependentContext()) {
9167           ContextRAII SavedContext(*this, DC);
9168           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9169             Invalid = true;
9170         }
9171 
9172         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9173                                                         NewFD->getLocation(),
9174                                                         Name, TemplateParams,
9175                                                         NewFD);
9176         FunctionTemplate->setLexicalDeclContext(CurContext);
9177         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9178 
9179         // For source fidelity, store the other template param lists.
9180         if (TemplateParamLists.size() > 1) {
9181           NewFD->setTemplateParameterListsInfo(Context,
9182               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9183                   .drop_back(1));
9184         }
9185       } else {
9186         // This is a function template specialization.
9187         isFunctionTemplateSpecialization = true;
9188         // For source fidelity, store all the template param lists.
9189         if (TemplateParamLists.size() > 0)
9190           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9191 
9192         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9193         if (isFriend) {
9194           // We want to remove the "template<>", found here.
9195           SourceRange RemoveRange = TemplateParams->getSourceRange();
9196 
9197           // If we remove the template<> and the name is not a
9198           // template-id, we're actually silently creating a problem:
9199           // the friend declaration will refer to an untemplated decl,
9200           // and clearly the user wants a template specialization.  So
9201           // we need to insert '<>' after the name.
9202           SourceLocation InsertLoc;
9203           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9204             InsertLoc = D.getName().getSourceRange().getEnd();
9205             InsertLoc = getLocForEndOfToken(InsertLoc);
9206           }
9207 
9208           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9209             << Name << RemoveRange
9210             << FixItHint::CreateRemoval(RemoveRange)
9211             << FixItHint::CreateInsertion(InsertLoc, "<>");
9212           Invalid = true;
9213         }
9214       }
9215     } else {
9216       // Check that we can declare a template here.
9217       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9218           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9219         NewFD->setInvalidDecl();
9220 
9221       // All template param lists were matched against the scope specifier:
9222       // this is NOT (an explicit specialization of) a template.
9223       if (TemplateParamLists.size() > 0)
9224         // For source fidelity, store all the template param lists.
9225         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9226     }
9227 
9228     if (Invalid) {
9229       NewFD->setInvalidDecl();
9230       if (FunctionTemplate)
9231         FunctionTemplate->setInvalidDecl();
9232     }
9233 
9234     // C++ [dcl.fct.spec]p5:
9235     //   The virtual specifier shall only be used in declarations of
9236     //   nonstatic class member functions that appear within a
9237     //   member-specification of a class declaration; see 10.3.
9238     //
9239     if (isVirtual && !NewFD->isInvalidDecl()) {
9240       if (!isVirtualOkay) {
9241         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9242              diag::err_virtual_non_function);
9243       } else if (!CurContext->isRecord()) {
9244         // 'virtual' was specified outside of the class.
9245         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9246              diag::err_virtual_out_of_class)
9247           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9248       } else if (NewFD->getDescribedFunctionTemplate()) {
9249         // C++ [temp.mem]p3:
9250         //  A member function template shall not be virtual.
9251         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9252              diag::err_virtual_member_function_template)
9253           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9254       } else {
9255         // Okay: Add virtual to the method.
9256         NewFD->setVirtualAsWritten(true);
9257       }
9258 
9259       if (getLangOpts().CPlusPlus14 &&
9260           NewFD->getReturnType()->isUndeducedType())
9261         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9262     }
9263 
9264     if (getLangOpts().CPlusPlus14 &&
9265         (NewFD->isDependentContext() ||
9266          (isFriend && CurContext->isDependentContext())) &&
9267         NewFD->getReturnType()->isUndeducedType()) {
9268       // If the function template is referenced directly (for instance, as a
9269       // member of the current instantiation), pretend it has a dependent type.
9270       // This is not really justified by the standard, but is the only sane
9271       // thing to do.
9272       // FIXME: For a friend function, we have not marked the function as being
9273       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9274       const FunctionProtoType *FPT =
9275           NewFD->getType()->castAs<FunctionProtoType>();
9276       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9277       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9278                                              FPT->getExtProtoInfo()));
9279     }
9280 
9281     // C++ [dcl.fct.spec]p3:
9282     //  The inline specifier shall not appear on a block scope function
9283     //  declaration.
9284     if (isInline && !NewFD->isInvalidDecl()) {
9285       if (CurContext->isFunctionOrMethod()) {
9286         // 'inline' is not allowed on block scope function declaration.
9287         Diag(D.getDeclSpec().getInlineSpecLoc(),
9288              diag::err_inline_declaration_block_scope) << Name
9289           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9290       }
9291     }
9292 
9293     // C++ [dcl.fct.spec]p6:
9294     //  The explicit specifier shall be used only in the declaration of a
9295     //  constructor or conversion function within its class definition;
9296     //  see 12.3.1 and 12.3.2.
9297     if (hasExplicit && !NewFD->isInvalidDecl() &&
9298         !isa<CXXDeductionGuideDecl>(NewFD)) {
9299       if (!CurContext->isRecord()) {
9300         // 'explicit' was specified outside of the class.
9301         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9302              diag::err_explicit_out_of_class)
9303             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9304       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9305                  !isa<CXXConversionDecl>(NewFD)) {
9306         // 'explicit' was specified on a function that wasn't a constructor
9307         // or conversion function.
9308         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9309              diag::err_explicit_non_ctor_or_conv_function)
9310             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9311       }
9312     }
9313 
9314     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9315     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9316       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9317       // are implicitly inline.
9318       NewFD->setImplicitlyInline();
9319 
9320       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9321       // be either constructors or to return a literal type. Therefore,
9322       // destructors cannot be declared constexpr.
9323       if (isa<CXXDestructorDecl>(NewFD) &&
9324           (!getLangOpts().CPlusPlus20 ||
9325            ConstexprKind == ConstexprSpecKind::Consteval)) {
9326         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9327             << static_cast<int>(ConstexprKind);
9328         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9329                                     ? ConstexprSpecKind::Unspecified
9330                                     : ConstexprSpecKind::Constexpr);
9331       }
9332       // C++20 [dcl.constexpr]p2: An allocation function, or a
9333       // deallocation function shall not be declared with the consteval
9334       // specifier.
9335       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9336           (NewFD->getOverloadedOperator() == OO_New ||
9337            NewFD->getOverloadedOperator() == OO_Array_New ||
9338            NewFD->getOverloadedOperator() == OO_Delete ||
9339            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9340         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9341              diag::err_invalid_consteval_decl_kind)
9342             << NewFD;
9343         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9344       }
9345     }
9346 
9347     // If __module_private__ was specified, mark the function accordingly.
9348     if (D.getDeclSpec().isModulePrivateSpecified()) {
9349       if (isFunctionTemplateSpecialization) {
9350         SourceLocation ModulePrivateLoc
9351           = D.getDeclSpec().getModulePrivateSpecLoc();
9352         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9353           << 0
9354           << FixItHint::CreateRemoval(ModulePrivateLoc);
9355       } else {
9356         NewFD->setModulePrivate();
9357         if (FunctionTemplate)
9358           FunctionTemplate->setModulePrivate();
9359       }
9360     }
9361 
9362     if (isFriend) {
9363       if (FunctionTemplate) {
9364         FunctionTemplate->setObjectOfFriendDecl();
9365         FunctionTemplate->setAccess(AS_public);
9366       }
9367       NewFD->setObjectOfFriendDecl();
9368       NewFD->setAccess(AS_public);
9369     }
9370 
9371     // If a function is defined as defaulted or deleted, mark it as such now.
9372     // We'll do the relevant checks on defaulted / deleted functions later.
9373     switch (D.getFunctionDefinitionKind()) {
9374     case FunctionDefinitionKind::Declaration:
9375     case FunctionDefinitionKind::Definition:
9376       break;
9377 
9378     case FunctionDefinitionKind::Defaulted:
9379       NewFD->setDefaulted();
9380       break;
9381 
9382     case FunctionDefinitionKind::Deleted:
9383       NewFD->setDeletedAsWritten();
9384       break;
9385     }
9386 
9387     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9388         D.isFunctionDefinition()) {
9389       // C++ [class.mfct]p2:
9390       //   A member function may be defined (8.4) in its class definition, in
9391       //   which case it is an inline member function (7.1.2)
9392       NewFD->setImplicitlyInline();
9393     }
9394 
9395     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9396         !CurContext->isRecord()) {
9397       // C++ [class.static]p1:
9398       //   A data or function member of a class may be declared static
9399       //   in a class definition, in which case it is a static member of
9400       //   the class.
9401 
9402       // Complain about the 'static' specifier if it's on an out-of-line
9403       // member function definition.
9404 
9405       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9406       // member function template declaration and class member template
9407       // declaration (MSVC versions before 2015), warn about this.
9408       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9409            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9410              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9411            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9412            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9413         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9414     }
9415 
9416     // C++11 [except.spec]p15:
9417     //   A deallocation function with no exception-specification is treated
9418     //   as if it were specified with noexcept(true).
9419     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9420     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9421          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9422         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9423       NewFD->setType(Context.getFunctionType(
9424           FPT->getReturnType(), FPT->getParamTypes(),
9425           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9426   }
9427 
9428   // Filter out previous declarations that don't match the scope.
9429   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9430                        D.getCXXScopeSpec().isNotEmpty() ||
9431                        isMemberSpecialization ||
9432                        isFunctionTemplateSpecialization);
9433 
9434   // Handle GNU asm-label extension (encoded as an attribute).
9435   if (Expr *E = (Expr*) D.getAsmLabel()) {
9436     // The parser guarantees this is a string.
9437     StringLiteral *SE = cast<StringLiteral>(E);
9438     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9439                                         /*IsLiteralLabel=*/true,
9440                                         SE->getStrTokenLoc(0)));
9441   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9442     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9443       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9444     if (I != ExtnameUndeclaredIdentifiers.end()) {
9445       if (isDeclExternC(NewFD)) {
9446         NewFD->addAttr(I->second);
9447         ExtnameUndeclaredIdentifiers.erase(I);
9448       } else
9449         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9450             << /*Variable*/0 << NewFD;
9451     }
9452   }
9453 
9454   // Copy the parameter declarations from the declarator D to the function
9455   // declaration NewFD, if they are available.  First scavenge them into Params.
9456   SmallVector<ParmVarDecl*, 16> Params;
9457   unsigned FTIIdx;
9458   if (D.isFunctionDeclarator(FTIIdx)) {
9459     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9460 
9461     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9462     // function that takes no arguments, not a function that takes a
9463     // single void argument.
9464     // We let through "const void" here because Sema::GetTypeForDeclarator
9465     // already checks for that case.
9466     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9467       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9468         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9469         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9470         Param->setDeclContext(NewFD);
9471         Params.push_back(Param);
9472 
9473         if (Param->isInvalidDecl())
9474           NewFD->setInvalidDecl();
9475       }
9476     }
9477 
9478     if (!getLangOpts().CPlusPlus) {
9479       // In C, find all the tag declarations from the prototype and move them
9480       // into the function DeclContext. Remove them from the surrounding tag
9481       // injection context of the function, which is typically but not always
9482       // the TU.
9483       DeclContext *PrototypeTagContext =
9484           getTagInjectionContext(NewFD->getLexicalDeclContext());
9485       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9486         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9487 
9488         // We don't want to reparent enumerators. Look at their parent enum
9489         // instead.
9490         if (!TD) {
9491           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9492             TD = cast<EnumDecl>(ECD->getDeclContext());
9493         }
9494         if (!TD)
9495           continue;
9496         DeclContext *TagDC = TD->getLexicalDeclContext();
9497         if (!TagDC->containsDecl(TD))
9498           continue;
9499         TagDC->removeDecl(TD);
9500         TD->setDeclContext(NewFD);
9501         NewFD->addDecl(TD);
9502 
9503         // Preserve the lexical DeclContext if it is not the surrounding tag
9504         // injection context of the FD. In this example, the semantic context of
9505         // E will be f and the lexical context will be S, while both the
9506         // semantic and lexical contexts of S will be f:
9507         //   void f(struct S { enum E { a } f; } s);
9508         if (TagDC != PrototypeTagContext)
9509           TD->setLexicalDeclContext(TagDC);
9510       }
9511     }
9512   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9513     // When we're declaring a function with a typedef, typeof, etc as in the
9514     // following example, we'll need to synthesize (unnamed)
9515     // parameters for use in the declaration.
9516     //
9517     // @code
9518     // typedef void fn(int);
9519     // fn f;
9520     // @endcode
9521 
9522     // Synthesize a parameter for each argument type.
9523     for (const auto &AI : FT->param_types()) {
9524       ParmVarDecl *Param =
9525           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9526       Param->setScopeInfo(0, Params.size());
9527       Params.push_back(Param);
9528     }
9529   } else {
9530     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9531            "Should not need args for typedef of non-prototype fn");
9532   }
9533 
9534   // Finally, we know we have the right number of parameters, install them.
9535   NewFD->setParams(Params);
9536 
9537   if (D.getDeclSpec().isNoreturnSpecified())
9538     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9539                                            D.getDeclSpec().getNoreturnSpecLoc(),
9540                                            AttributeCommonInfo::AS_Keyword));
9541 
9542   // Functions returning a variably modified type violate C99 6.7.5.2p2
9543   // because all functions have linkage.
9544   if (!NewFD->isInvalidDecl() &&
9545       NewFD->getReturnType()->isVariablyModifiedType()) {
9546     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9547     NewFD->setInvalidDecl();
9548   }
9549 
9550   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9551   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9552       !NewFD->hasAttr<SectionAttr>())
9553     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9554         Context, PragmaClangTextSection.SectionName,
9555         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9556 
9557   // Apply an implicit SectionAttr if #pragma code_seg is active.
9558   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9559       !NewFD->hasAttr<SectionAttr>()) {
9560     NewFD->addAttr(SectionAttr::CreateImplicit(
9561         Context, CodeSegStack.CurrentValue->getString(),
9562         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9563         SectionAttr::Declspec_allocate));
9564     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9565                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9566                          ASTContext::PSF_Read,
9567                      NewFD))
9568       NewFD->dropAttr<SectionAttr>();
9569   }
9570 
9571   // Apply an implicit CodeSegAttr from class declspec or
9572   // apply an implicit SectionAttr from #pragma code_seg if active.
9573   if (!NewFD->hasAttr<CodeSegAttr>()) {
9574     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9575                                                                  D.isFunctionDefinition())) {
9576       NewFD->addAttr(SAttr);
9577     }
9578   }
9579 
9580   // Handle attributes.
9581   ProcessDeclAttributes(S, NewFD, D);
9582 
9583   if (getLangOpts().OpenCL) {
9584     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9585     // type declaration will generate a compilation error.
9586     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9587     if (AddressSpace != LangAS::Default) {
9588       Diag(NewFD->getLocation(),
9589            diag::err_opencl_return_value_with_address_space);
9590       NewFD->setInvalidDecl();
9591     }
9592   }
9593 
9594   if (!getLangOpts().CPlusPlus) {
9595     // Perform semantic checking on the function declaration.
9596     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9597       CheckMain(NewFD, D.getDeclSpec());
9598 
9599     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9600       CheckMSVCRTEntryPoint(NewFD);
9601 
9602     if (!NewFD->isInvalidDecl())
9603       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9604                                                   isMemberSpecialization));
9605     else if (!Previous.empty())
9606       // Recover gracefully from an invalid redeclaration.
9607       D.setRedeclaration(true);
9608     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9609             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9610            "previous declaration set still overloaded");
9611 
9612     // Diagnose no-prototype function declarations with calling conventions that
9613     // don't support variadic calls. Only do this in C and do it after merging
9614     // possibly prototyped redeclarations.
9615     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9616     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9617       CallingConv CC = FT->getExtInfo().getCC();
9618       if (!supportsVariadicCall(CC)) {
9619         // Windows system headers sometimes accidentally use stdcall without
9620         // (void) parameters, so we relax this to a warning.
9621         int DiagID =
9622             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9623         Diag(NewFD->getLocation(), DiagID)
9624             << FunctionType::getNameForCallConv(CC);
9625       }
9626     }
9627 
9628    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9629        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9630      checkNonTrivialCUnion(NewFD->getReturnType(),
9631                            NewFD->getReturnTypeSourceRange().getBegin(),
9632                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9633   } else {
9634     // C++11 [replacement.functions]p3:
9635     //  The program's definitions shall not be specified as inline.
9636     //
9637     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9638     //
9639     // Suppress the diagnostic if the function is __attribute__((used)), since
9640     // that forces an external definition to be emitted.
9641     if (D.getDeclSpec().isInlineSpecified() &&
9642         NewFD->isReplaceableGlobalAllocationFunction() &&
9643         !NewFD->hasAttr<UsedAttr>())
9644       Diag(D.getDeclSpec().getInlineSpecLoc(),
9645            diag::ext_operator_new_delete_declared_inline)
9646         << NewFD->getDeclName();
9647 
9648     // If the declarator is a template-id, translate the parser's template
9649     // argument list into our AST format.
9650     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9651       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9652       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9653       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9654       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9655                                          TemplateId->NumArgs);
9656       translateTemplateArguments(TemplateArgsPtr,
9657                                  TemplateArgs);
9658 
9659       HasExplicitTemplateArgs = true;
9660 
9661       if (NewFD->isInvalidDecl()) {
9662         HasExplicitTemplateArgs = false;
9663       } else if (FunctionTemplate) {
9664         // Function template with explicit template arguments.
9665         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9666           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9667 
9668         HasExplicitTemplateArgs = false;
9669       } else {
9670         assert((isFunctionTemplateSpecialization ||
9671                 D.getDeclSpec().isFriendSpecified()) &&
9672                "should have a 'template<>' for this decl");
9673         // "friend void foo<>(int);" is an implicit specialization decl.
9674         isFunctionTemplateSpecialization = true;
9675       }
9676     } else if (isFriend && isFunctionTemplateSpecialization) {
9677       // This combination is only possible in a recovery case;  the user
9678       // wrote something like:
9679       //   template <> friend void foo(int);
9680       // which we're recovering from as if the user had written:
9681       //   friend void foo<>(int);
9682       // Go ahead and fake up a template id.
9683       HasExplicitTemplateArgs = true;
9684       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9685       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9686     }
9687 
9688     // We do not add HD attributes to specializations here because
9689     // they may have different constexpr-ness compared to their
9690     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9691     // may end up with different effective targets. Instead, a
9692     // specialization inherits its target attributes from its template
9693     // in the CheckFunctionTemplateSpecialization() call below.
9694     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9695       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9696 
9697     // If it's a friend (and only if it's a friend), it's possible
9698     // that either the specialized function type or the specialized
9699     // template is dependent, and therefore matching will fail.  In
9700     // this case, don't check the specialization yet.
9701     if (isFunctionTemplateSpecialization && isFriend &&
9702         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9703          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9704              TemplateArgs.arguments()))) {
9705       assert(HasExplicitTemplateArgs &&
9706              "friend function specialization without template args");
9707       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9708                                                        Previous))
9709         NewFD->setInvalidDecl();
9710     } else if (isFunctionTemplateSpecialization) {
9711       if (CurContext->isDependentContext() && CurContext->isRecord()
9712           && !isFriend) {
9713         isDependentClassScopeExplicitSpecialization = true;
9714       } else if (!NewFD->isInvalidDecl() &&
9715                  CheckFunctionTemplateSpecialization(
9716                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9717                      Previous))
9718         NewFD->setInvalidDecl();
9719 
9720       // C++ [dcl.stc]p1:
9721       //   A storage-class-specifier shall not be specified in an explicit
9722       //   specialization (14.7.3)
9723       FunctionTemplateSpecializationInfo *Info =
9724           NewFD->getTemplateSpecializationInfo();
9725       if (Info && SC != SC_None) {
9726         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9727           Diag(NewFD->getLocation(),
9728                diag::err_explicit_specialization_inconsistent_storage_class)
9729             << SC
9730             << FixItHint::CreateRemoval(
9731                                       D.getDeclSpec().getStorageClassSpecLoc());
9732 
9733         else
9734           Diag(NewFD->getLocation(),
9735                diag::ext_explicit_specialization_storage_class)
9736             << FixItHint::CreateRemoval(
9737                                       D.getDeclSpec().getStorageClassSpecLoc());
9738       }
9739     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9740       if (CheckMemberSpecialization(NewFD, Previous))
9741           NewFD->setInvalidDecl();
9742     }
9743 
9744     // Perform semantic checking on the function declaration.
9745     if (!isDependentClassScopeExplicitSpecialization) {
9746       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9747         CheckMain(NewFD, D.getDeclSpec());
9748 
9749       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9750         CheckMSVCRTEntryPoint(NewFD);
9751 
9752       if (!NewFD->isInvalidDecl())
9753         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9754                                                     isMemberSpecialization));
9755       else if (!Previous.empty())
9756         // Recover gracefully from an invalid redeclaration.
9757         D.setRedeclaration(true);
9758     }
9759 
9760     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9761             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9762            "previous declaration set still overloaded");
9763 
9764     NamedDecl *PrincipalDecl = (FunctionTemplate
9765                                 ? cast<NamedDecl>(FunctionTemplate)
9766                                 : NewFD);
9767 
9768     if (isFriend && NewFD->getPreviousDecl()) {
9769       AccessSpecifier Access = AS_public;
9770       if (!NewFD->isInvalidDecl())
9771         Access = NewFD->getPreviousDecl()->getAccess();
9772 
9773       NewFD->setAccess(Access);
9774       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9775     }
9776 
9777     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9778         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9779       PrincipalDecl->setNonMemberOperator();
9780 
9781     // If we have a function template, check the template parameter
9782     // list. This will check and merge default template arguments.
9783     if (FunctionTemplate) {
9784       FunctionTemplateDecl *PrevTemplate =
9785                                      FunctionTemplate->getPreviousDecl();
9786       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9787                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9788                                     : nullptr,
9789                             D.getDeclSpec().isFriendSpecified()
9790                               ? (D.isFunctionDefinition()
9791                                    ? TPC_FriendFunctionTemplateDefinition
9792                                    : TPC_FriendFunctionTemplate)
9793                               : (D.getCXXScopeSpec().isSet() &&
9794                                  DC && DC->isRecord() &&
9795                                  DC->isDependentContext())
9796                                   ? TPC_ClassTemplateMember
9797                                   : TPC_FunctionTemplate);
9798     }
9799 
9800     if (NewFD->isInvalidDecl()) {
9801       // Ignore all the rest of this.
9802     } else if (!D.isRedeclaration()) {
9803       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9804                                        AddToScope };
9805       // Fake up an access specifier if it's supposed to be a class member.
9806       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9807         NewFD->setAccess(AS_public);
9808 
9809       // Qualified decls generally require a previous declaration.
9810       if (D.getCXXScopeSpec().isSet()) {
9811         // ...with the major exception of templated-scope or
9812         // dependent-scope friend declarations.
9813 
9814         // TODO: we currently also suppress this check in dependent
9815         // contexts because (1) the parameter depth will be off when
9816         // matching friend templates and (2) we might actually be
9817         // selecting a friend based on a dependent factor.  But there
9818         // are situations where these conditions don't apply and we
9819         // can actually do this check immediately.
9820         //
9821         // Unless the scope is dependent, it's always an error if qualified
9822         // redeclaration lookup found nothing at all. Diagnose that now;
9823         // nothing will diagnose that error later.
9824         if (isFriend &&
9825             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9826              (!Previous.empty() && CurContext->isDependentContext()))) {
9827           // ignore these
9828         } else if (NewFD->isCPUDispatchMultiVersion() ||
9829                    NewFD->isCPUSpecificMultiVersion()) {
9830           // ignore this, we allow the redeclaration behavior here to create new
9831           // versions of the function.
9832         } else {
9833           // The user tried to provide an out-of-line definition for a
9834           // function that is a member of a class or namespace, but there
9835           // was no such member function declared (C++ [class.mfct]p2,
9836           // C++ [namespace.memdef]p2). For example:
9837           //
9838           // class X {
9839           //   void f() const;
9840           // };
9841           //
9842           // void X::f() { } // ill-formed
9843           //
9844           // Complain about this problem, and attempt to suggest close
9845           // matches (e.g., those that differ only in cv-qualifiers and
9846           // whether the parameter types are references).
9847 
9848           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9849                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9850             AddToScope = ExtraArgs.AddToScope;
9851             return Result;
9852           }
9853         }
9854 
9855         // Unqualified local friend declarations are required to resolve
9856         // to something.
9857       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9858         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9859                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9860           AddToScope = ExtraArgs.AddToScope;
9861           return Result;
9862         }
9863       }
9864     } else if (!D.isFunctionDefinition() &&
9865                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9866                !isFriend && !isFunctionTemplateSpecialization &&
9867                !isMemberSpecialization) {
9868       // An out-of-line member function declaration must also be a
9869       // definition (C++ [class.mfct]p2).
9870       // Note that this is not the case for explicit specializations of
9871       // function templates or member functions of class templates, per
9872       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9873       // extension for compatibility with old SWIG code which likes to
9874       // generate them.
9875       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9876         << D.getCXXScopeSpec().getRange();
9877     }
9878   }
9879 
9880   // If this is the first declaration of a library builtin function, add
9881   // attributes as appropriate.
9882   if (!D.isRedeclaration() &&
9883       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9884     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9885       if (unsigned BuiltinID = II->getBuiltinID()) {
9886         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9887           // Validate the type matches unless this builtin is specified as
9888           // matching regardless of its declared type.
9889           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9890             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9891           } else {
9892             ASTContext::GetBuiltinTypeError Error;
9893             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9894             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9895 
9896             if (!Error && !BuiltinType.isNull() &&
9897                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9898                     NewFD->getType(), BuiltinType))
9899               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9900           }
9901         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9902                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9903           // FIXME: We should consider this a builtin only in the std namespace.
9904           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9905         }
9906       }
9907     }
9908   }
9909 
9910   ProcessPragmaWeak(S, NewFD);
9911   checkAttributesAfterMerging(*this, *NewFD);
9912 
9913   AddKnownFunctionAttributes(NewFD);
9914 
9915   if (NewFD->hasAttr<OverloadableAttr>() &&
9916       !NewFD->getType()->getAs<FunctionProtoType>()) {
9917     Diag(NewFD->getLocation(),
9918          diag::err_attribute_overloadable_no_prototype)
9919       << NewFD;
9920 
9921     // Turn this into a variadic function with no parameters.
9922     const auto *FT = NewFD->getType()->castAs<FunctionType>();
9923     FunctionProtoType::ExtProtoInfo EPI(
9924         Context.getDefaultCallingConvention(true, false));
9925     EPI.Variadic = true;
9926     EPI.ExtInfo = FT->getExtInfo();
9927 
9928     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9929     NewFD->setType(R);
9930   }
9931 
9932   // If there's a #pragma GCC visibility in scope, and this isn't a class
9933   // member, set the visibility of this function.
9934   if (!DC->isRecord() && NewFD->isExternallyVisible())
9935     AddPushedVisibilityAttribute(NewFD);
9936 
9937   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9938   // marking the function.
9939   AddCFAuditedAttribute(NewFD);
9940 
9941   // If this is a function definition, check if we have to apply optnone due to
9942   // a pragma.
9943   if(D.isFunctionDefinition())
9944     AddRangeBasedOptnone(NewFD);
9945 
9946   // If this is the first declaration of an extern C variable, update
9947   // the map of such variables.
9948   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9949       isIncompleteDeclExternC(*this, NewFD))
9950     RegisterLocallyScopedExternCDecl(NewFD, S);
9951 
9952   // Set this FunctionDecl's range up to the right paren.
9953   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9954 
9955   if (D.isRedeclaration() && !Previous.empty()) {
9956     NamedDecl *Prev = Previous.getRepresentativeDecl();
9957     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9958                                    isMemberSpecialization ||
9959                                        isFunctionTemplateSpecialization,
9960                                    D.isFunctionDefinition());
9961   }
9962 
9963   if (getLangOpts().CUDA) {
9964     IdentifierInfo *II = NewFD->getIdentifier();
9965     if (II && II->isStr(getCudaConfigureFuncName()) &&
9966         !NewFD->isInvalidDecl() &&
9967         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9968       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9969         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9970             << getCudaConfigureFuncName();
9971       Context.setcudaConfigureCallDecl(NewFD);
9972     }
9973 
9974     // Variadic functions, other than a *declaration* of printf, are not allowed
9975     // in device-side CUDA code, unless someone passed
9976     // -fcuda-allow-variadic-functions.
9977     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9978         (NewFD->hasAttr<CUDADeviceAttr>() ||
9979          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9980         !(II && II->isStr("printf") && NewFD->isExternC() &&
9981           !D.isFunctionDefinition())) {
9982       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9983     }
9984   }
9985 
9986   MarkUnusedFileScopedDecl(NewFD);
9987 
9988 
9989 
9990   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9991     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9992     if (SC == SC_Static) {
9993       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9994       D.setInvalidType();
9995     }
9996 
9997     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9998     if (!NewFD->getReturnType()->isVoidType()) {
9999       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10000       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10001           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10002                                 : FixItHint());
10003       D.setInvalidType();
10004     }
10005 
10006     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10007     for (auto Param : NewFD->parameters())
10008       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10009 
10010     if (getLangOpts().OpenCLCPlusPlus) {
10011       if (DC->isRecord()) {
10012         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10013         D.setInvalidType();
10014       }
10015       if (FunctionTemplate) {
10016         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10017         D.setInvalidType();
10018       }
10019     }
10020   }
10021 
10022   if (getLangOpts().CPlusPlus) {
10023     if (FunctionTemplate) {
10024       if (NewFD->isInvalidDecl())
10025         FunctionTemplate->setInvalidDecl();
10026       return FunctionTemplate;
10027     }
10028 
10029     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10030       CompleteMemberSpecialization(NewFD, Previous);
10031   }
10032 
10033   for (const ParmVarDecl *Param : NewFD->parameters()) {
10034     QualType PT = Param->getType();
10035 
10036     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10037     // types.
10038     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10039       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10040         QualType ElemTy = PipeTy->getElementType();
10041           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10042             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10043             D.setInvalidType();
10044           }
10045       }
10046     }
10047   }
10048 
10049   // Here we have an function template explicit specialization at class scope.
10050   // The actual specialization will be postponed to template instatiation
10051   // time via the ClassScopeFunctionSpecializationDecl node.
10052   if (isDependentClassScopeExplicitSpecialization) {
10053     ClassScopeFunctionSpecializationDecl *NewSpec =
10054                          ClassScopeFunctionSpecializationDecl::Create(
10055                                 Context, CurContext, NewFD->getLocation(),
10056                                 cast<CXXMethodDecl>(NewFD),
10057                                 HasExplicitTemplateArgs, TemplateArgs);
10058     CurContext->addDecl(NewSpec);
10059     AddToScope = false;
10060   }
10061 
10062   // Diagnose availability attributes. Availability cannot be used on functions
10063   // that are run during load/unload.
10064   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10065     if (NewFD->hasAttr<ConstructorAttr>()) {
10066       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10067           << 1;
10068       NewFD->dropAttr<AvailabilityAttr>();
10069     }
10070     if (NewFD->hasAttr<DestructorAttr>()) {
10071       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10072           << 2;
10073       NewFD->dropAttr<AvailabilityAttr>();
10074     }
10075   }
10076 
10077   // Diagnose no_builtin attribute on function declaration that are not a
10078   // definition.
10079   // FIXME: We should really be doing this in
10080   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10081   // the FunctionDecl and at this point of the code
10082   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10083   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10084   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10085     switch (D.getFunctionDefinitionKind()) {
10086     case FunctionDefinitionKind::Defaulted:
10087     case FunctionDefinitionKind::Deleted:
10088       Diag(NBA->getLocation(),
10089            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10090           << NBA->getSpelling();
10091       break;
10092     case FunctionDefinitionKind::Declaration:
10093       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10094           << NBA->getSpelling();
10095       break;
10096     case FunctionDefinitionKind::Definition:
10097       break;
10098     }
10099 
10100   return NewFD;
10101 }
10102 
10103 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10104 /// when __declspec(code_seg) "is applied to a class, all member functions of
10105 /// the class and nested classes -- this includes compiler-generated special
10106 /// member functions -- are put in the specified segment."
10107 /// The actual behavior is a little more complicated. The Microsoft compiler
10108 /// won't check outer classes if there is an active value from #pragma code_seg.
10109 /// The CodeSeg is always applied from the direct parent but only from outer
10110 /// classes when the #pragma code_seg stack is empty. See:
10111 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10112 /// available since MS has removed the page.
10113 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10114   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10115   if (!Method)
10116     return nullptr;
10117   const CXXRecordDecl *Parent = Method->getParent();
10118   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10119     Attr *NewAttr = SAttr->clone(S.getASTContext());
10120     NewAttr->setImplicit(true);
10121     return NewAttr;
10122   }
10123 
10124   // The Microsoft compiler won't check outer classes for the CodeSeg
10125   // when the #pragma code_seg stack is active.
10126   if (S.CodeSegStack.CurrentValue)
10127    return nullptr;
10128 
10129   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10130     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10131       Attr *NewAttr = SAttr->clone(S.getASTContext());
10132       NewAttr->setImplicit(true);
10133       return NewAttr;
10134     }
10135   }
10136   return nullptr;
10137 }
10138 
10139 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10140 /// containing class. Otherwise it will return implicit SectionAttr if the
10141 /// function is a definition and there is an active value on CodeSegStack
10142 /// (from the current #pragma code-seg value).
10143 ///
10144 /// \param FD Function being declared.
10145 /// \param IsDefinition Whether it is a definition or just a declarartion.
10146 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10147 ///          nullptr if no attribute should be added.
10148 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10149                                                        bool IsDefinition) {
10150   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10151     return A;
10152   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10153       CodeSegStack.CurrentValue)
10154     return SectionAttr::CreateImplicit(
10155         getASTContext(), CodeSegStack.CurrentValue->getString(),
10156         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10157         SectionAttr::Declspec_allocate);
10158   return nullptr;
10159 }
10160 
10161 /// Determines if we can perform a correct type check for \p D as a
10162 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10163 /// best-effort check.
10164 ///
10165 /// \param NewD The new declaration.
10166 /// \param OldD The old declaration.
10167 /// \param NewT The portion of the type of the new declaration to check.
10168 /// \param OldT The portion of the type of the old declaration to check.
10169 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10170                                           QualType NewT, QualType OldT) {
10171   if (!NewD->getLexicalDeclContext()->isDependentContext())
10172     return true;
10173 
10174   // For dependently-typed local extern declarations and friends, we can't
10175   // perform a correct type check in general until instantiation:
10176   //
10177   //   int f();
10178   //   template<typename T> void g() { T f(); }
10179   //
10180   // (valid if g() is only instantiated with T = int).
10181   if (NewT->isDependentType() &&
10182       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10183     return false;
10184 
10185   // Similarly, if the previous declaration was a dependent local extern
10186   // declaration, we don't really know its type yet.
10187   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10188     return false;
10189 
10190   return true;
10191 }
10192 
10193 /// Checks if the new declaration declared in dependent context must be
10194 /// put in the same redeclaration chain as the specified declaration.
10195 ///
10196 /// \param D Declaration that is checked.
10197 /// \param PrevDecl Previous declaration found with proper lookup method for the
10198 ///                 same declaration name.
10199 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10200 ///          belongs to.
10201 ///
10202 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10203   if (!D->getLexicalDeclContext()->isDependentContext())
10204     return true;
10205 
10206   // Don't chain dependent friend function definitions until instantiation, to
10207   // permit cases like
10208   //
10209   //   void func();
10210   //   template<typename T> class C1 { friend void func() {} };
10211   //   template<typename T> class C2 { friend void func() {} };
10212   //
10213   // ... which is valid if only one of C1 and C2 is ever instantiated.
10214   //
10215   // FIXME: This need only apply to function definitions. For now, we proxy
10216   // this by checking for a file-scope function. We do not want this to apply
10217   // to friend declarations nominating member functions, because that gets in
10218   // the way of access checks.
10219   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10220     return false;
10221 
10222   auto *VD = dyn_cast<ValueDecl>(D);
10223   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10224   return !VD || !PrevVD ||
10225          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10226                                         PrevVD->getType());
10227 }
10228 
10229 /// Check the target attribute of the function for MultiVersion
10230 /// validity.
10231 ///
10232 /// Returns true if there was an error, false otherwise.
10233 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10234   const auto *TA = FD->getAttr<TargetAttr>();
10235   assert(TA && "MultiVersion Candidate requires a target attribute");
10236   ParsedTargetAttr ParseInfo = TA->parse();
10237   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10238   enum ErrType { Feature = 0, Architecture = 1 };
10239 
10240   if (!ParseInfo.Architecture.empty() &&
10241       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10242     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10243         << Architecture << ParseInfo.Architecture;
10244     return true;
10245   }
10246 
10247   for (const auto &Feat : ParseInfo.Features) {
10248     auto BareFeat = StringRef{Feat}.substr(1);
10249     if (Feat[0] == '-') {
10250       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10251           << Feature << ("no-" + BareFeat).str();
10252       return true;
10253     }
10254 
10255     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10256         !TargetInfo.isValidFeatureName(BareFeat)) {
10257       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10258           << Feature << BareFeat;
10259       return true;
10260     }
10261   }
10262   return false;
10263 }
10264 
10265 // Provide a white-list of attributes that are allowed to be combined with
10266 // multiversion functions.
10267 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10268                                            MultiVersionKind MVType) {
10269   // Note: this list/diagnosis must match the list in
10270   // checkMultiversionAttributesAllSame.
10271   switch (Kind) {
10272   default:
10273     return false;
10274   case attr::Used:
10275     return MVType == MultiVersionKind::Target;
10276   case attr::NonNull:
10277   case attr::NoThrow:
10278     return true;
10279   }
10280 }
10281 
10282 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10283                                                  const FunctionDecl *FD,
10284                                                  const FunctionDecl *CausedFD,
10285                                                  MultiVersionKind MVType) {
10286   const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) {
10287     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10288         << static_cast<unsigned>(MVType) << A;
10289     if (CausedFD)
10290       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10291     return true;
10292   };
10293 
10294   for (const Attr *A : FD->attrs()) {
10295     switch (A->getKind()) {
10296     case attr::CPUDispatch:
10297     case attr::CPUSpecific:
10298       if (MVType != MultiVersionKind::CPUDispatch &&
10299           MVType != MultiVersionKind::CPUSpecific)
10300         return Diagnose(S, A);
10301       break;
10302     case attr::Target:
10303       if (MVType != MultiVersionKind::Target)
10304         return Diagnose(S, A);
10305       break;
10306     case attr::TargetClones:
10307       if (MVType != MultiVersionKind::TargetClones)
10308         return Diagnose(S, A);
10309       break;
10310     default:
10311       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10312         return Diagnose(S, A);
10313       break;
10314     }
10315   }
10316   return false;
10317 }
10318 
10319 bool Sema::areMultiversionVariantFunctionsCompatible(
10320     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10321     const PartialDiagnostic &NoProtoDiagID,
10322     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10323     const PartialDiagnosticAt &NoSupportDiagIDAt,
10324     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10325     bool ConstexprSupported, bool CLinkageMayDiffer) {
10326   enum DoesntSupport {
10327     FuncTemplates = 0,
10328     VirtFuncs = 1,
10329     DeducedReturn = 2,
10330     Constructors = 3,
10331     Destructors = 4,
10332     DeletedFuncs = 5,
10333     DefaultedFuncs = 6,
10334     ConstexprFuncs = 7,
10335     ConstevalFuncs = 8,
10336     Lambda = 9,
10337   };
10338   enum Different {
10339     CallingConv = 0,
10340     ReturnType = 1,
10341     ConstexprSpec = 2,
10342     InlineSpec = 3,
10343     Linkage = 4,
10344     LanguageLinkage = 5,
10345   };
10346 
10347   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10348       !OldFD->getType()->getAs<FunctionProtoType>()) {
10349     Diag(OldFD->getLocation(), NoProtoDiagID);
10350     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10351     return true;
10352   }
10353 
10354   if (NoProtoDiagID.getDiagID() != 0 &&
10355       !NewFD->getType()->getAs<FunctionProtoType>())
10356     return Diag(NewFD->getLocation(), NoProtoDiagID);
10357 
10358   if (!TemplatesSupported &&
10359       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10360     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10361            << FuncTemplates;
10362 
10363   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10364     if (NewCXXFD->isVirtual())
10365       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10366              << VirtFuncs;
10367 
10368     if (isa<CXXConstructorDecl>(NewCXXFD))
10369       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10370              << Constructors;
10371 
10372     if (isa<CXXDestructorDecl>(NewCXXFD))
10373       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10374              << Destructors;
10375   }
10376 
10377   if (NewFD->isDeleted())
10378     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10379            << DeletedFuncs;
10380 
10381   if (NewFD->isDefaulted())
10382     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10383            << DefaultedFuncs;
10384 
10385   if (!ConstexprSupported && NewFD->isConstexpr())
10386     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10387            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10388 
10389   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10390   const auto *NewType = cast<FunctionType>(NewQType);
10391   QualType NewReturnType = NewType->getReturnType();
10392 
10393   if (NewReturnType->isUndeducedType())
10394     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10395            << DeducedReturn;
10396 
10397   // Ensure the return type is identical.
10398   if (OldFD) {
10399     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10400     const auto *OldType = cast<FunctionType>(OldQType);
10401     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10402     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10403 
10404     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10405       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10406 
10407     QualType OldReturnType = OldType->getReturnType();
10408 
10409     if (OldReturnType != NewReturnType)
10410       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10411 
10412     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10413       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10414 
10415     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10416       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10417 
10418     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10419       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10420 
10421     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10422       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10423 
10424     if (CheckEquivalentExceptionSpec(
10425             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10426             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10427       return true;
10428   }
10429   return false;
10430 }
10431 
10432 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10433                                              const FunctionDecl *NewFD,
10434                                              bool CausesMV,
10435                                              MultiVersionKind MVType) {
10436   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10437     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10438     if (OldFD)
10439       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10440     return true;
10441   }
10442 
10443   bool IsCPUSpecificCPUDispatchMVType =
10444       MVType == MultiVersionKind::CPUDispatch ||
10445       MVType == MultiVersionKind::CPUSpecific;
10446 
10447   if (CausesMV && OldFD &&
10448       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10449     return true;
10450 
10451   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10452     return true;
10453 
10454   // Only allow transition to MultiVersion if it hasn't been used.
10455   if (OldFD && CausesMV && OldFD->isUsed(false))
10456     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10457 
10458   return S.areMultiversionVariantFunctionsCompatible(
10459       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10460       PartialDiagnosticAt(NewFD->getLocation(),
10461                           S.PDiag(diag::note_multiversioning_caused_here)),
10462       PartialDiagnosticAt(NewFD->getLocation(),
10463                           S.PDiag(diag::err_multiversion_doesnt_support)
10464                               << static_cast<unsigned>(MVType)),
10465       PartialDiagnosticAt(NewFD->getLocation(),
10466                           S.PDiag(diag::err_multiversion_diff)),
10467       /*TemplatesSupported=*/false,
10468       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10469       /*CLinkageMayDiffer=*/false);
10470 }
10471 
10472 /// Check the validity of a multiversion function declaration that is the
10473 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10474 ///
10475 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10476 ///
10477 /// Returns true if there was an error, false otherwise.
10478 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10479                                            MultiVersionKind MVType,
10480                                            const TargetAttr *TA) {
10481   assert(MVType != MultiVersionKind::None &&
10482          "Function lacks multiversion attribute");
10483 
10484   // Target only causes MV if it is default, otherwise this is a normal
10485   // function.
10486   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10487     return false;
10488 
10489   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10490     FD->setInvalidDecl();
10491     return true;
10492   }
10493 
10494   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10495     FD->setInvalidDecl();
10496     return true;
10497   }
10498 
10499   FD->setIsMultiVersion();
10500   return false;
10501 }
10502 
10503 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10504   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10505     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10506       return true;
10507   }
10508 
10509   return false;
10510 }
10511 
10512 static bool CheckTargetCausesMultiVersioning(
10513     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10514     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10515     LookupResult &Previous) {
10516   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10517   ParsedTargetAttr NewParsed = NewTA->parse();
10518   // Sort order doesn't matter, it just needs to be consistent.
10519   llvm::sort(NewParsed.Features);
10520 
10521   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10522   // to change, this is a simple redeclaration.
10523   if (!NewTA->isDefaultVersion() &&
10524       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10525     return false;
10526 
10527   // Otherwise, this decl causes MultiVersioning.
10528   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10529     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10530     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10531     NewFD->setInvalidDecl();
10532     return true;
10533   }
10534 
10535   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10536                                        MultiVersionKind::Target)) {
10537     NewFD->setInvalidDecl();
10538     return true;
10539   }
10540 
10541   if (CheckMultiVersionValue(S, NewFD)) {
10542     NewFD->setInvalidDecl();
10543     return true;
10544   }
10545 
10546   // If this is 'default', permit the forward declaration.
10547   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10548     Redeclaration = true;
10549     OldDecl = OldFD;
10550     OldFD->setIsMultiVersion();
10551     NewFD->setIsMultiVersion();
10552     return false;
10553   }
10554 
10555   if (CheckMultiVersionValue(S, OldFD)) {
10556     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10557     NewFD->setInvalidDecl();
10558     return true;
10559   }
10560 
10561   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10562 
10563   if (OldParsed == NewParsed) {
10564     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10565     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10566     NewFD->setInvalidDecl();
10567     return true;
10568   }
10569 
10570   for (const auto *FD : OldFD->redecls()) {
10571     const auto *CurTA = FD->getAttr<TargetAttr>();
10572     // We allow forward declarations before ANY multiversioning attributes, but
10573     // nothing after the fact.
10574     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10575         (!CurTA || CurTA->isInherited())) {
10576       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10577           << 0;
10578       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10579       NewFD->setInvalidDecl();
10580       return true;
10581     }
10582   }
10583 
10584   OldFD->setIsMultiVersion();
10585   NewFD->setIsMultiVersion();
10586   Redeclaration = false;
10587   MergeTypeWithPrevious = false;
10588   OldDecl = nullptr;
10589   Previous.clear();
10590   return false;
10591 }
10592 
10593 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10594                                         MultiVersionKind New) {
10595   if (Old == New || Old == MultiVersionKind::None ||
10596       New == MultiVersionKind::None)
10597     return true;
10598 
10599   return (Old == MultiVersionKind::CPUDispatch &&
10600           New == MultiVersionKind::CPUSpecific) ||
10601          (Old == MultiVersionKind::CPUSpecific &&
10602           New == MultiVersionKind::CPUDispatch);
10603 }
10604 
10605 /// Check the validity of a new function declaration being added to an existing
10606 /// multiversioned declaration collection.
10607 static bool CheckMultiVersionAdditionalDecl(
10608     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10609     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10610     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10611     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10612     bool &MergeTypeWithPrevious, LookupResult &Previous) {
10613 
10614   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10615   // Disallow mixing of multiversioning types.
10616   if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) {
10617     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10618     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10619     NewFD->setInvalidDecl();
10620     return true;
10621   }
10622 
10623   ParsedTargetAttr NewParsed;
10624   if (NewTA) {
10625     NewParsed = NewTA->parse();
10626     llvm::sort(NewParsed.Features);
10627   }
10628 
10629   bool UseMemberUsingDeclRules =
10630       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10631 
10632   // Next, check ALL non-overloads to see if this is a redeclaration of a
10633   // previous member of the MultiVersion set.
10634   for (NamedDecl *ND : Previous) {
10635     FunctionDecl *CurFD = ND->getAsFunction();
10636     if (!CurFD)
10637       continue;
10638     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10639       continue;
10640 
10641     switch (NewMVType) {
10642     case MultiVersionKind::None:
10643       assert(OldMVType == MultiVersionKind::TargetClones &&
10644              "Only target_clones can be omitted in subsequent declarations");
10645       break;
10646     case MultiVersionKind::Target: {
10647       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10648       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10649         NewFD->setIsMultiVersion();
10650         Redeclaration = true;
10651         OldDecl = ND;
10652         return false;
10653       }
10654 
10655       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10656       if (CurParsed == NewParsed) {
10657         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10658         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10659         NewFD->setInvalidDecl();
10660         return true;
10661       }
10662       break;
10663     }
10664     case MultiVersionKind::TargetClones: {
10665       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10666       Redeclaration = true;
10667       OldDecl = CurFD;
10668       MergeTypeWithPrevious = true;
10669       NewFD->setIsMultiVersion();
10670 
10671       if (CurClones && NewClones &&
10672           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10673            !std::equal(CurClones->featuresStrs_begin(),
10674                        CurClones->featuresStrs_end(),
10675                        NewClones->featuresStrs_begin()))) {
10676         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10677         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10678         NewFD->setInvalidDecl();
10679         return true;
10680       }
10681 
10682       return false;
10683     }
10684     case MultiVersionKind::CPUSpecific:
10685     case MultiVersionKind::CPUDispatch: {
10686       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10687       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10688       // Handle CPUDispatch/CPUSpecific versions.
10689       // Only 1 CPUDispatch function is allowed, this will make it go through
10690       // the redeclaration errors.
10691       if (NewMVType == MultiVersionKind::CPUDispatch &&
10692           CurFD->hasAttr<CPUDispatchAttr>()) {
10693         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10694             std::equal(
10695                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10696                 NewCPUDisp->cpus_begin(),
10697                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10698                   return Cur->getName() == New->getName();
10699                 })) {
10700           NewFD->setIsMultiVersion();
10701           Redeclaration = true;
10702           OldDecl = ND;
10703           return false;
10704         }
10705 
10706         // If the declarations don't match, this is an error condition.
10707         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10708         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10709         NewFD->setInvalidDecl();
10710         return true;
10711       }
10712       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10713 
10714         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10715             std::equal(
10716                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10717                 NewCPUSpec->cpus_begin(),
10718                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10719                   return Cur->getName() == New->getName();
10720                 })) {
10721           NewFD->setIsMultiVersion();
10722           Redeclaration = true;
10723           OldDecl = ND;
10724           return false;
10725         }
10726 
10727         // Only 1 version of CPUSpecific is allowed for each CPU.
10728         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10729           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10730             if (CurII == NewII) {
10731               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10732                   << NewII;
10733               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10734               NewFD->setInvalidDecl();
10735               return true;
10736             }
10737           }
10738         }
10739       }
10740       break;
10741     }
10742     }
10743   }
10744 
10745   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10746   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10747   // handled in the attribute adding step.
10748   if (NewMVType == MultiVersionKind::Target &&
10749       CheckMultiVersionValue(S, NewFD)) {
10750     NewFD->setInvalidDecl();
10751     return true;
10752   }
10753 
10754   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10755                                        !OldFD->isMultiVersion(), NewMVType)) {
10756     NewFD->setInvalidDecl();
10757     return true;
10758   }
10759 
10760   // Permit forward declarations in the case where these two are compatible.
10761   if (!OldFD->isMultiVersion()) {
10762     OldFD->setIsMultiVersion();
10763     NewFD->setIsMultiVersion();
10764     Redeclaration = true;
10765     OldDecl = OldFD;
10766     return false;
10767   }
10768 
10769   NewFD->setIsMultiVersion();
10770   Redeclaration = false;
10771   MergeTypeWithPrevious = false;
10772   OldDecl = nullptr;
10773   Previous.clear();
10774   return false;
10775 }
10776 
10777 /// Check the validity of a mulitversion function declaration.
10778 /// Also sets the multiversion'ness' of the function itself.
10779 ///
10780 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10781 ///
10782 /// Returns true if there was an error, false otherwise.
10783 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10784                                       bool &Redeclaration, NamedDecl *&OldDecl,
10785                                       bool &MergeTypeWithPrevious,
10786                                       LookupResult &Previous) {
10787   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10788   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10789   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10790   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10791   MultiVersionKind MVType = NewFD->getMultiVersionKind();
10792 
10793   // Main isn't allowed to become a multiversion function, however it IS
10794   // permitted to have 'main' be marked with the 'target' optimization hint.
10795   if (NewFD->isMain()) {
10796     if (MVType != MultiVersionKind::None &&
10797         !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10798       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10799       NewFD->setInvalidDecl();
10800       return true;
10801     }
10802     return false;
10803   }
10804 
10805   if (!OldDecl || !OldDecl->getAsFunction() ||
10806       OldDecl->getDeclContext()->getRedeclContext() !=
10807           NewFD->getDeclContext()->getRedeclContext()) {
10808     // If there's no previous declaration, AND this isn't attempting to cause
10809     // multiversioning, this isn't an error condition.
10810     if (MVType == MultiVersionKind::None)
10811       return false;
10812     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10813   }
10814 
10815   FunctionDecl *OldFD = OldDecl->getAsFunction();
10816 
10817   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10818     return false;
10819 
10820   // Multiversioned redeclarations aren't allowed to omit the attribute, except
10821   // for target_clones.
10822   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None &&
10823       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
10824     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10825         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10826     NewFD->setInvalidDecl();
10827     return true;
10828   }
10829 
10830   if (!OldFD->isMultiVersion()) {
10831     switch (MVType) {
10832     case MultiVersionKind::Target:
10833       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10834                                               Redeclaration, OldDecl,
10835                                               MergeTypeWithPrevious, Previous);
10836     case MultiVersionKind::TargetClones:
10837       if (OldFD->isUsed(false)) {
10838         NewFD->setInvalidDecl();
10839         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10840       }
10841       OldFD->setIsMultiVersion();
10842       break;
10843     case MultiVersionKind::CPUDispatch:
10844     case MultiVersionKind::CPUSpecific:
10845     case MultiVersionKind::None:
10846       break;
10847     }
10848   }
10849   // Handle the target potentially causes multiversioning case.
10850   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10851     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10852                                             Redeclaration, OldDecl,
10853                                             MergeTypeWithPrevious, Previous);
10854 
10855   // At this point, we have a multiversion function decl (in OldFD) AND an
10856   // appropriate attribute in the current function decl.  Resolve that these are
10857   // still compatible with previous declarations.
10858   return CheckMultiVersionAdditionalDecl(
10859       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones,
10860       Redeclaration, OldDecl, MergeTypeWithPrevious, Previous);
10861 }
10862 
10863 /// Perform semantic checking of a new function declaration.
10864 ///
10865 /// Performs semantic analysis of the new function declaration
10866 /// NewFD. This routine performs all semantic checking that does not
10867 /// require the actual declarator involved in the declaration, and is
10868 /// used both for the declaration of functions as they are parsed
10869 /// (called via ActOnDeclarator) and for the declaration of functions
10870 /// that have been instantiated via C++ template instantiation (called
10871 /// via InstantiateDecl).
10872 ///
10873 /// \param IsMemberSpecialization whether this new function declaration is
10874 /// a member specialization (that replaces any definition provided by the
10875 /// previous declaration).
10876 ///
10877 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10878 ///
10879 /// \returns true if the function declaration is a redeclaration.
10880 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10881                                     LookupResult &Previous,
10882                                     bool IsMemberSpecialization) {
10883   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10884          "Variably modified return types are not handled here");
10885 
10886   // Determine whether the type of this function should be merged with
10887   // a previous visible declaration. This never happens for functions in C++,
10888   // and always happens in C if the previous declaration was visible.
10889   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10890                                !Previous.isShadowed();
10891 
10892   bool Redeclaration = false;
10893   NamedDecl *OldDecl = nullptr;
10894   bool MayNeedOverloadableChecks = false;
10895 
10896   // Merge or overload the declaration with an existing declaration of
10897   // the same name, if appropriate.
10898   if (!Previous.empty()) {
10899     // Determine whether NewFD is an overload of PrevDecl or
10900     // a declaration that requires merging. If it's an overload,
10901     // there's no more work to do here; we'll just add the new
10902     // function to the scope.
10903     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10904       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10905       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10906         Redeclaration = true;
10907         OldDecl = Candidate;
10908       }
10909     } else {
10910       MayNeedOverloadableChecks = true;
10911       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10912                             /*NewIsUsingDecl*/ false)) {
10913       case Ovl_Match:
10914         Redeclaration = true;
10915         break;
10916 
10917       case Ovl_NonFunction:
10918         Redeclaration = true;
10919         break;
10920 
10921       case Ovl_Overload:
10922         Redeclaration = false;
10923         break;
10924       }
10925     }
10926   }
10927 
10928   // Check for a previous extern "C" declaration with this name.
10929   if (!Redeclaration &&
10930       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10931     if (!Previous.empty()) {
10932       // This is an extern "C" declaration with the same name as a previous
10933       // declaration, and thus redeclares that entity...
10934       Redeclaration = true;
10935       OldDecl = Previous.getFoundDecl();
10936       MergeTypeWithPrevious = false;
10937 
10938       // ... except in the presence of __attribute__((overloadable)).
10939       if (OldDecl->hasAttr<OverloadableAttr>() ||
10940           NewFD->hasAttr<OverloadableAttr>()) {
10941         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10942           MayNeedOverloadableChecks = true;
10943           Redeclaration = false;
10944           OldDecl = nullptr;
10945         }
10946       }
10947     }
10948   }
10949 
10950   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10951                                 MergeTypeWithPrevious, Previous))
10952     return Redeclaration;
10953 
10954   // PPC MMA non-pointer types are not allowed as function return types.
10955   if (Context.getTargetInfo().getTriple().isPPC64() &&
10956       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10957     NewFD->setInvalidDecl();
10958   }
10959 
10960   // C++11 [dcl.constexpr]p8:
10961   //   A constexpr specifier for a non-static member function that is not
10962   //   a constructor declares that member function to be const.
10963   //
10964   // This needs to be delayed until we know whether this is an out-of-line
10965   // definition of a static member function.
10966   //
10967   // This rule is not present in C++1y, so we produce a backwards
10968   // compatibility warning whenever it happens in C++11.
10969   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10970   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10971       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10972       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10973     CXXMethodDecl *OldMD = nullptr;
10974     if (OldDecl)
10975       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10976     if (!OldMD || !OldMD->isStatic()) {
10977       const FunctionProtoType *FPT =
10978         MD->getType()->castAs<FunctionProtoType>();
10979       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10980       EPI.TypeQuals.addConst();
10981       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10982                                           FPT->getParamTypes(), EPI));
10983 
10984       // Warn that we did this, if we're not performing template instantiation.
10985       // In that case, we'll have warned already when the template was defined.
10986       if (!inTemplateInstantiation()) {
10987         SourceLocation AddConstLoc;
10988         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10989                 .IgnoreParens().getAs<FunctionTypeLoc>())
10990           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10991 
10992         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10993           << FixItHint::CreateInsertion(AddConstLoc, " const");
10994       }
10995     }
10996   }
10997 
10998   if (Redeclaration) {
10999     // NewFD and OldDecl represent declarations that need to be
11000     // merged.
11001     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11002       NewFD->setInvalidDecl();
11003       return Redeclaration;
11004     }
11005 
11006     Previous.clear();
11007     Previous.addDecl(OldDecl);
11008 
11009     if (FunctionTemplateDecl *OldTemplateDecl =
11010             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11011       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11012       FunctionTemplateDecl *NewTemplateDecl
11013         = NewFD->getDescribedFunctionTemplate();
11014       assert(NewTemplateDecl && "Template/non-template mismatch");
11015 
11016       // The call to MergeFunctionDecl above may have created some state in
11017       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11018       // can add it as a redeclaration.
11019       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11020 
11021       NewFD->setPreviousDeclaration(OldFD);
11022       if (NewFD->isCXXClassMember()) {
11023         NewFD->setAccess(OldTemplateDecl->getAccess());
11024         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11025       }
11026 
11027       // If this is an explicit specialization of a member that is a function
11028       // template, mark it as a member specialization.
11029       if (IsMemberSpecialization &&
11030           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11031         NewTemplateDecl->setMemberSpecialization();
11032         assert(OldTemplateDecl->isMemberSpecialization());
11033         // Explicit specializations of a member template do not inherit deleted
11034         // status from the parent member template that they are specializing.
11035         if (OldFD->isDeleted()) {
11036           // FIXME: This assert will not hold in the presence of modules.
11037           assert(OldFD->getCanonicalDecl() == OldFD);
11038           // FIXME: We need an update record for this AST mutation.
11039           OldFD->setDeletedAsWritten(false);
11040         }
11041       }
11042 
11043     } else {
11044       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11045         auto *OldFD = cast<FunctionDecl>(OldDecl);
11046         // This needs to happen first so that 'inline' propagates.
11047         NewFD->setPreviousDeclaration(OldFD);
11048         if (NewFD->isCXXClassMember())
11049           NewFD->setAccess(OldFD->getAccess());
11050       }
11051     }
11052   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11053              !NewFD->getAttr<OverloadableAttr>()) {
11054     assert((Previous.empty() ||
11055             llvm::any_of(Previous,
11056                          [](const NamedDecl *ND) {
11057                            return ND->hasAttr<OverloadableAttr>();
11058                          })) &&
11059            "Non-redecls shouldn't happen without overloadable present");
11060 
11061     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11062       const auto *FD = dyn_cast<FunctionDecl>(ND);
11063       return FD && !FD->hasAttr<OverloadableAttr>();
11064     });
11065 
11066     if (OtherUnmarkedIter != Previous.end()) {
11067       Diag(NewFD->getLocation(),
11068            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11069       Diag((*OtherUnmarkedIter)->getLocation(),
11070            diag::note_attribute_overloadable_prev_overload)
11071           << false;
11072 
11073       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11074     }
11075   }
11076 
11077   if (LangOpts.OpenMP)
11078     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11079 
11080   // Semantic checking for this function declaration (in isolation).
11081 
11082   if (getLangOpts().CPlusPlus) {
11083     // C++-specific checks.
11084     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11085       CheckConstructor(Constructor);
11086     } else if (CXXDestructorDecl *Destructor =
11087                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11088       CXXRecordDecl *Record = Destructor->getParent();
11089       QualType ClassType = Context.getTypeDeclType(Record);
11090 
11091       // FIXME: Shouldn't we be able to perform this check even when the class
11092       // type is dependent? Both gcc and edg can handle that.
11093       if (!ClassType->isDependentType()) {
11094         DeclarationName Name
11095           = Context.DeclarationNames.getCXXDestructorName(
11096                                         Context.getCanonicalType(ClassType));
11097         if (NewFD->getDeclName() != Name) {
11098           Diag(NewFD->getLocation(), diag::err_destructor_name);
11099           NewFD->setInvalidDecl();
11100           return Redeclaration;
11101         }
11102       }
11103     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11104       if (auto *TD = Guide->getDescribedFunctionTemplate())
11105         CheckDeductionGuideTemplate(TD);
11106 
11107       // A deduction guide is not on the list of entities that can be
11108       // explicitly specialized.
11109       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11110         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11111             << /*explicit specialization*/ 1;
11112     }
11113 
11114     // Find any virtual functions that this function overrides.
11115     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11116       if (!Method->isFunctionTemplateSpecialization() &&
11117           !Method->getDescribedFunctionTemplate() &&
11118           Method->isCanonicalDecl()) {
11119         AddOverriddenMethods(Method->getParent(), Method);
11120       }
11121       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11122         // C++2a [class.virtual]p6
11123         // A virtual method shall not have a requires-clause.
11124         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11125              diag::err_constrained_virtual_method);
11126 
11127       if (Method->isStatic())
11128         checkThisInStaticMemberFunctionType(Method);
11129     }
11130 
11131     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11132       ActOnConversionDeclarator(Conversion);
11133 
11134     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11135     if (NewFD->isOverloadedOperator() &&
11136         CheckOverloadedOperatorDeclaration(NewFD)) {
11137       NewFD->setInvalidDecl();
11138       return Redeclaration;
11139     }
11140 
11141     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11142     if (NewFD->getLiteralIdentifier() &&
11143         CheckLiteralOperatorDeclaration(NewFD)) {
11144       NewFD->setInvalidDecl();
11145       return Redeclaration;
11146     }
11147 
11148     // In C++, check default arguments now that we have merged decls. Unless
11149     // the lexical context is the class, because in this case this is done
11150     // during delayed parsing anyway.
11151     if (!CurContext->isRecord())
11152       CheckCXXDefaultArguments(NewFD);
11153 
11154     // If this function is declared as being extern "C", then check to see if
11155     // the function returns a UDT (class, struct, or union type) that is not C
11156     // compatible, and if it does, warn the user.
11157     // But, issue any diagnostic on the first declaration only.
11158     if (Previous.empty() && NewFD->isExternC()) {
11159       QualType R = NewFD->getReturnType();
11160       if (R->isIncompleteType() && !R->isVoidType())
11161         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11162             << NewFD << R;
11163       else if (!R.isPODType(Context) && !R->isVoidType() &&
11164                !R->isObjCObjectPointerType())
11165         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11166     }
11167 
11168     // C++1z [dcl.fct]p6:
11169     //   [...] whether the function has a non-throwing exception-specification
11170     //   [is] part of the function type
11171     //
11172     // This results in an ABI break between C++14 and C++17 for functions whose
11173     // declared type includes an exception-specification in a parameter or
11174     // return type. (Exception specifications on the function itself are OK in
11175     // most cases, and exception specifications are not permitted in most other
11176     // contexts where they could make it into a mangling.)
11177     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11178       auto HasNoexcept = [&](QualType T) -> bool {
11179         // Strip off declarator chunks that could be between us and a function
11180         // type. We don't need to look far, exception specifications are very
11181         // restricted prior to C++17.
11182         if (auto *RT = T->getAs<ReferenceType>())
11183           T = RT->getPointeeType();
11184         else if (T->isAnyPointerType())
11185           T = T->getPointeeType();
11186         else if (auto *MPT = T->getAs<MemberPointerType>())
11187           T = MPT->getPointeeType();
11188         if (auto *FPT = T->getAs<FunctionProtoType>())
11189           if (FPT->isNothrow())
11190             return true;
11191         return false;
11192       };
11193 
11194       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11195       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11196       for (QualType T : FPT->param_types())
11197         AnyNoexcept |= HasNoexcept(T);
11198       if (AnyNoexcept)
11199         Diag(NewFD->getLocation(),
11200              diag::warn_cxx17_compat_exception_spec_in_signature)
11201             << NewFD;
11202     }
11203 
11204     if (!Redeclaration && LangOpts.CUDA)
11205       checkCUDATargetOverload(NewFD, Previous);
11206   }
11207   return Redeclaration;
11208 }
11209 
11210 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11211   // C++11 [basic.start.main]p3:
11212   //   A program that [...] declares main to be inline, static or
11213   //   constexpr is ill-formed.
11214   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11215   //   appear in a declaration of main.
11216   // static main is not an error under C99, but we should warn about it.
11217   // We accept _Noreturn main as an extension.
11218   if (FD->getStorageClass() == SC_Static)
11219     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11220          ? diag::err_static_main : diag::warn_static_main)
11221       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11222   if (FD->isInlineSpecified())
11223     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11224       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11225   if (DS.isNoreturnSpecified()) {
11226     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11227     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11228     Diag(NoreturnLoc, diag::ext_noreturn_main);
11229     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11230       << FixItHint::CreateRemoval(NoreturnRange);
11231   }
11232   if (FD->isConstexpr()) {
11233     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11234         << FD->isConsteval()
11235         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11236     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11237   }
11238 
11239   if (getLangOpts().OpenCL) {
11240     Diag(FD->getLocation(), diag::err_opencl_no_main)
11241         << FD->hasAttr<OpenCLKernelAttr>();
11242     FD->setInvalidDecl();
11243     return;
11244   }
11245 
11246   QualType T = FD->getType();
11247   assert(T->isFunctionType() && "function decl is not of function type");
11248   const FunctionType* FT = T->castAs<FunctionType>();
11249 
11250   // Set default calling convention for main()
11251   if (FT->getCallConv() != CC_C) {
11252     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11253     FD->setType(QualType(FT, 0));
11254     T = Context.getCanonicalType(FD->getType());
11255   }
11256 
11257   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11258     // In C with GNU extensions we allow main() to have non-integer return
11259     // type, but we should warn about the extension, and we disable the
11260     // implicit-return-zero rule.
11261 
11262     // GCC in C mode accepts qualified 'int'.
11263     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11264       FD->setHasImplicitReturnZero(true);
11265     else {
11266       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11267       SourceRange RTRange = FD->getReturnTypeSourceRange();
11268       if (RTRange.isValid())
11269         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11270             << FixItHint::CreateReplacement(RTRange, "int");
11271     }
11272   } else {
11273     // In C and C++, main magically returns 0 if you fall off the end;
11274     // set the flag which tells us that.
11275     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11276 
11277     // All the standards say that main() should return 'int'.
11278     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11279       FD->setHasImplicitReturnZero(true);
11280     else {
11281       // Otherwise, this is just a flat-out error.
11282       SourceRange RTRange = FD->getReturnTypeSourceRange();
11283       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11284           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11285                                 : FixItHint());
11286       FD->setInvalidDecl(true);
11287     }
11288   }
11289 
11290   // Treat protoless main() as nullary.
11291   if (isa<FunctionNoProtoType>(FT)) return;
11292 
11293   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11294   unsigned nparams = FTP->getNumParams();
11295   assert(FD->getNumParams() == nparams);
11296 
11297   bool HasExtraParameters = (nparams > 3);
11298 
11299   if (FTP->isVariadic()) {
11300     Diag(FD->getLocation(), diag::ext_variadic_main);
11301     // FIXME: if we had information about the location of the ellipsis, we
11302     // could add a FixIt hint to remove it as a parameter.
11303   }
11304 
11305   // Darwin passes an undocumented fourth argument of type char**.  If
11306   // other platforms start sprouting these, the logic below will start
11307   // getting shifty.
11308   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11309     HasExtraParameters = false;
11310 
11311   if (HasExtraParameters) {
11312     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11313     FD->setInvalidDecl(true);
11314     nparams = 3;
11315   }
11316 
11317   // FIXME: a lot of the following diagnostics would be improved
11318   // if we had some location information about types.
11319 
11320   QualType CharPP =
11321     Context.getPointerType(Context.getPointerType(Context.CharTy));
11322   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11323 
11324   for (unsigned i = 0; i < nparams; ++i) {
11325     QualType AT = FTP->getParamType(i);
11326 
11327     bool mismatch = true;
11328 
11329     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11330       mismatch = false;
11331     else if (Expected[i] == CharPP) {
11332       // As an extension, the following forms are okay:
11333       //   char const **
11334       //   char const * const *
11335       //   char * const *
11336 
11337       QualifierCollector qs;
11338       const PointerType* PT;
11339       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11340           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11341           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11342                               Context.CharTy)) {
11343         qs.removeConst();
11344         mismatch = !qs.empty();
11345       }
11346     }
11347 
11348     if (mismatch) {
11349       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11350       // TODO: suggest replacing given type with expected type
11351       FD->setInvalidDecl(true);
11352     }
11353   }
11354 
11355   if (nparams == 1 && !FD->isInvalidDecl()) {
11356     Diag(FD->getLocation(), diag::warn_main_one_arg);
11357   }
11358 
11359   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11360     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11361     FD->setInvalidDecl();
11362   }
11363 }
11364 
11365 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11366 
11367   // Default calling convention for main and wmain is __cdecl
11368   if (FD->getName() == "main" || FD->getName() == "wmain")
11369     return false;
11370 
11371   // Default calling convention for MinGW is __cdecl
11372   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11373   if (T.isWindowsGNUEnvironment())
11374     return false;
11375 
11376   // Default calling convention for WinMain, wWinMain and DllMain
11377   // is __stdcall on 32 bit Windows
11378   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11379     return true;
11380 
11381   return false;
11382 }
11383 
11384 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11385   QualType T = FD->getType();
11386   assert(T->isFunctionType() && "function decl is not of function type");
11387   const FunctionType *FT = T->castAs<FunctionType>();
11388 
11389   // Set an implicit return of 'zero' if the function can return some integral,
11390   // enumeration, pointer or nullptr type.
11391   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11392       FT->getReturnType()->isAnyPointerType() ||
11393       FT->getReturnType()->isNullPtrType())
11394     // DllMain is exempt because a return value of zero means it failed.
11395     if (FD->getName() != "DllMain")
11396       FD->setHasImplicitReturnZero(true);
11397 
11398   // Explicity specified calling conventions are applied to MSVC entry points
11399   if (!hasExplicitCallingConv(T)) {
11400     if (isDefaultStdCall(FD, *this)) {
11401       if (FT->getCallConv() != CC_X86StdCall) {
11402         FT = Context.adjustFunctionType(
11403             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11404         FD->setType(QualType(FT, 0));
11405       }
11406     } else if (FT->getCallConv() != CC_C) {
11407       FT = Context.adjustFunctionType(FT,
11408                                       FT->getExtInfo().withCallingConv(CC_C));
11409       FD->setType(QualType(FT, 0));
11410     }
11411   }
11412 
11413   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11414     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11415     FD->setInvalidDecl();
11416   }
11417 }
11418 
11419 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11420   // FIXME: Need strict checking.  In C89, we need to check for
11421   // any assignment, increment, decrement, function-calls, or
11422   // commas outside of a sizeof.  In C99, it's the same list,
11423   // except that the aforementioned are allowed in unevaluated
11424   // expressions.  Everything else falls under the
11425   // "may accept other forms of constant expressions" exception.
11426   //
11427   // Regular C++ code will not end up here (exceptions: language extensions,
11428   // OpenCL C++ etc), so the constant expression rules there don't matter.
11429   if (Init->isValueDependent()) {
11430     assert(Init->containsErrors() &&
11431            "Dependent code should only occur in error-recovery path.");
11432     return true;
11433   }
11434   const Expr *Culprit;
11435   if (Init->isConstantInitializer(Context, false, &Culprit))
11436     return false;
11437   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11438     << Culprit->getSourceRange();
11439   return true;
11440 }
11441 
11442 namespace {
11443   // Visits an initialization expression to see if OrigDecl is evaluated in
11444   // its own initialization and throws a warning if it does.
11445   class SelfReferenceChecker
11446       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11447     Sema &S;
11448     Decl *OrigDecl;
11449     bool isRecordType;
11450     bool isPODType;
11451     bool isReferenceType;
11452 
11453     bool isInitList;
11454     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11455 
11456   public:
11457     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11458 
11459     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11460                                                     S(S), OrigDecl(OrigDecl) {
11461       isPODType = false;
11462       isRecordType = false;
11463       isReferenceType = false;
11464       isInitList = false;
11465       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11466         isPODType = VD->getType().isPODType(S.Context);
11467         isRecordType = VD->getType()->isRecordType();
11468         isReferenceType = VD->getType()->isReferenceType();
11469       }
11470     }
11471 
11472     // For most expressions, just call the visitor.  For initializer lists,
11473     // track the index of the field being initialized since fields are
11474     // initialized in order allowing use of previously initialized fields.
11475     void CheckExpr(Expr *E) {
11476       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11477       if (!InitList) {
11478         Visit(E);
11479         return;
11480       }
11481 
11482       // Track and increment the index here.
11483       isInitList = true;
11484       InitFieldIndex.push_back(0);
11485       for (auto Child : InitList->children()) {
11486         CheckExpr(cast<Expr>(Child));
11487         ++InitFieldIndex.back();
11488       }
11489       InitFieldIndex.pop_back();
11490     }
11491 
11492     // Returns true if MemberExpr is checked and no further checking is needed.
11493     // Returns false if additional checking is required.
11494     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11495       llvm::SmallVector<FieldDecl*, 4> Fields;
11496       Expr *Base = E;
11497       bool ReferenceField = false;
11498 
11499       // Get the field members used.
11500       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11501         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11502         if (!FD)
11503           return false;
11504         Fields.push_back(FD);
11505         if (FD->getType()->isReferenceType())
11506           ReferenceField = true;
11507         Base = ME->getBase()->IgnoreParenImpCasts();
11508       }
11509 
11510       // Keep checking only if the base Decl is the same.
11511       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11512       if (!DRE || DRE->getDecl() != OrigDecl)
11513         return false;
11514 
11515       // A reference field can be bound to an unininitialized field.
11516       if (CheckReference && !ReferenceField)
11517         return true;
11518 
11519       // Convert FieldDecls to their index number.
11520       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11521       for (const FieldDecl *I : llvm::reverse(Fields))
11522         UsedFieldIndex.push_back(I->getFieldIndex());
11523 
11524       // See if a warning is needed by checking the first difference in index
11525       // numbers.  If field being used has index less than the field being
11526       // initialized, then the use is safe.
11527       for (auto UsedIter = UsedFieldIndex.begin(),
11528                 UsedEnd = UsedFieldIndex.end(),
11529                 OrigIter = InitFieldIndex.begin(),
11530                 OrigEnd = InitFieldIndex.end();
11531            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11532         if (*UsedIter < *OrigIter)
11533           return true;
11534         if (*UsedIter > *OrigIter)
11535           break;
11536       }
11537 
11538       // TODO: Add a different warning which will print the field names.
11539       HandleDeclRefExpr(DRE);
11540       return true;
11541     }
11542 
11543     // For most expressions, the cast is directly above the DeclRefExpr.
11544     // For conditional operators, the cast can be outside the conditional
11545     // operator if both expressions are DeclRefExpr's.
11546     void HandleValue(Expr *E) {
11547       E = E->IgnoreParens();
11548       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11549         HandleDeclRefExpr(DRE);
11550         return;
11551       }
11552 
11553       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11554         Visit(CO->getCond());
11555         HandleValue(CO->getTrueExpr());
11556         HandleValue(CO->getFalseExpr());
11557         return;
11558       }
11559 
11560       if (BinaryConditionalOperator *BCO =
11561               dyn_cast<BinaryConditionalOperator>(E)) {
11562         Visit(BCO->getCond());
11563         HandleValue(BCO->getFalseExpr());
11564         return;
11565       }
11566 
11567       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11568         HandleValue(OVE->getSourceExpr());
11569         return;
11570       }
11571 
11572       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11573         if (BO->getOpcode() == BO_Comma) {
11574           Visit(BO->getLHS());
11575           HandleValue(BO->getRHS());
11576           return;
11577         }
11578       }
11579 
11580       if (isa<MemberExpr>(E)) {
11581         if (isInitList) {
11582           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11583                                       false /*CheckReference*/))
11584             return;
11585         }
11586 
11587         Expr *Base = E->IgnoreParenImpCasts();
11588         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11589           // Check for static member variables and don't warn on them.
11590           if (!isa<FieldDecl>(ME->getMemberDecl()))
11591             return;
11592           Base = ME->getBase()->IgnoreParenImpCasts();
11593         }
11594         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11595           HandleDeclRefExpr(DRE);
11596         return;
11597       }
11598 
11599       Visit(E);
11600     }
11601 
11602     // Reference types not handled in HandleValue are handled here since all
11603     // uses of references are bad, not just r-value uses.
11604     void VisitDeclRefExpr(DeclRefExpr *E) {
11605       if (isReferenceType)
11606         HandleDeclRefExpr(E);
11607     }
11608 
11609     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11610       if (E->getCastKind() == CK_LValueToRValue) {
11611         HandleValue(E->getSubExpr());
11612         return;
11613       }
11614 
11615       Inherited::VisitImplicitCastExpr(E);
11616     }
11617 
11618     void VisitMemberExpr(MemberExpr *E) {
11619       if (isInitList) {
11620         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11621           return;
11622       }
11623 
11624       // Don't warn on arrays since they can be treated as pointers.
11625       if (E->getType()->canDecayToPointerType()) return;
11626 
11627       // Warn when a non-static method call is followed by non-static member
11628       // field accesses, which is followed by a DeclRefExpr.
11629       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11630       bool Warn = (MD && !MD->isStatic());
11631       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11632       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11633         if (!isa<FieldDecl>(ME->getMemberDecl()))
11634           Warn = false;
11635         Base = ME->getBase()->IgnoreParenImpCasts();
11636       }
11637 
11638       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11639         if (Warn)
11640           HandleDeclRefExpr(DRE);
11641         return;
11642       }
11643 
11644       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11645       // Visit that expression.
11646       Visit(Base);
11647     }
11648 
11649     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11650       Expr *Callee = E->getCallee();
11651 
11652       if (isa<UnresolvedLookupExpr>(Callee))
11653         return Inherited::VisitCXXOperatorCallExpr(E);
11654 
11655       Visit(Callee);
11656       for (auto Arg: E->arguments())
11657         HandleValue(Arg->IgnoreParenImpCasts());
11658     }
11659 
11660     void VisitUnaryOperator(UnaryOperator *E) {
11661       // For POD record types, addresses of its own members are well-defined.
11662       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11663           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11664         if (!isPODType)
11665           HandleValue(E->getSubExpr());
11666         return;
11667       }
11668 
11669       if (E->isIncrementDecrementOp()) {
11670         HandleValue(E->getSubExpr());
11671         return;
11672       }
11673 
11674       Inherited::VisitUnaryOperator(E);
11675     }
11676 
11677     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11678 
11679     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11680       if (E->getConstructor()->isCopyConstructor()) {
11681         Expr *ArgExpr = E->getArg(0);
11682         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11683           if (ILE->getNumInits() == 1)
11684             ArgExpr = ILE->getInit(0);
11685         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11686           if (ICE->getCastKind() == CK_NoOp)
11687             ArgExpr = ICE->getSubExpr();
11688         HandleValue(ArgExpr);
11689         return;
11690       }
11691       Inherited::VisitCXXConstructExpr(E);
11692     }
11693 
11694     void VisitCallExpr(CallExpr *E) {
11695       // Treat std::move as a use.
11696       if (E->isCallToStdMove()) {
11697         HandleValue(E->getArg(0));
11698         return;
11699       }
11700 
11701       Inherited::VisitCallExpr(E);
11702     }
11703 
11704     void VisitBinaryOperator(BinaryOperator *E) {
11705       if (E->isCompoundAssignmentOp()) {
11706         HandleValue(E->getLHS());
11707         Visit(E->getRHS());
11708         return;
11709       }
11710 
11711       Inherited::VisitBinaryOperator(E);
11712     }
11713 
11714     // A custom visitor for BinaryConditionalOperator is needed because the
11715     // regular visitor would check the condition and true expression separately
11716     // but both point to the same place giving duplicate diagnostics.
11717     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11718       Visit(E->getCond());
11719       Visit(E->getFalseExpr());
11720     }
11721 
11722     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11723       Decl* ReferenceDecl = DRE->getDecl();
11724       if (OrigDecl != ReferenceDecl) return;
11725       unsigned diag;
11726       if (isReferenceType) {
11727         diag = diag::warn_uninit_self_reference_in_reference_init;
11728       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11729         diag = diag::warn_static_self_reference_in_init;
11730       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11731                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11732                  DRE->getDecl()->getType()->isRecordType()) {
11733         diag = diag::warn_uninit_self_reference_in_init;
11734       } else {
11735         // Local variables will be handled by the CFG analysis.
11736         return;
11737       }
11738 
11739       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11740                             S.PDiag(diag)
11741                                 << DRE->getDecl() << OrigDecl->getLocation()
11742                                 << DRE->getSourceRange());
11743     }
11744   };
11745 
11746   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11747   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11748                                  bool DirectInit) {
11749     // Parameters arguments are occassionially constructed with itself,
11750     // for instance, in recursive functions.  Skip them.
11751     if (isa<ParmVarDecl>(OrigDecl))
11752       return;
11753 
11754     E = E->IgnoreParens();
11755 
11756     // Skip checking T a = a where T is not a record or reference type.
11757     // Doing so is a way to silence uninitialized warnings.
11758     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11759       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11760         if (ICE->getCastKind() == CK_LValueToRValue)
11761           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11762             if (DRE->getDecl() == OrigDecl)
11763               return;
11764 
11765     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11766   }
11767 } // end anonymous namespace
11768 
11769 namespace {
11770   // Simple wrapper to add the name of a variable or (if no variable is
11771   // available) a DeclarationName into a diagnostic.
11772   struct VarDeclOrName {
11773     VarDecl *VDecl;
11774     DeclarationName Name;
11775 
11776     friend const Sema::SemaDiagnosticBuilder &
11777     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11778       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11779     }
11780   };
11781 } // end anonymous namespace
11782 
11783 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11784                                             DeclarationName Name, QualType Type,
11785                                             TypeSourceInfo *TSI,
11786                                             SourceRange Range, bool DirectInit,
11787                                             Expr *Init) {
11788   bool IsInitCapture = !VDecl;
11789   assert((!VDecl || !VDecl->isInitCapture()) &&
11790          "init captures are expected to be deduced prior to initialization");
11791 
11792   VarDeclOrName VN{VDecl, Name};
11793 
11794   DeducedType *Deduced = Type->getContainedDeducedType();
11795   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11796 
11797   // C++11 [dcl.spec.auto]p3
11798   if (!Init) {
11799     assert(VDecl && "no init for init capture deduction?");
11800 
11801     // Except for class argument deduction, and then for an initializing
11802     // declaration only, i.e. no static at class scope or extern.
11803     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11804         VDecl->hasExternalStorage() ||
11805         VDecl->isStaticDataMember()) {
11806       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11807         << VDecl->getDeclName() << Type;
11808       return QualType();
11809     }
11810   }
11811 
11812   ArrayRef<Expr*> DeduceInits;
11813   if (Init)
11814     DeduceInits = Init;
11815 
11816   if (DirectInit) {
11817     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11818       DeduceInits = PL->exprs();
11819   }
11820 
11821   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11822     assert(VDecl && "non-auto type for init capture deduction?");
11823     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11824     InitializationKind Kind = InitializationKind::CreateForInit(
11825         VDecl->getLocation(), DirectInit, Init);
11826     // FIXME: Initialization should not be taking a mutable list of inits.
11827     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11828     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11829                                                        InitsCopy);
11830   }
11831 
11832   if (DirectInit) {
11833     if (auto *IL = dyn_cast<InitListExpr>(Init))
11834       DeduceInits = IL->inits();
11835   }
11836 
11837   // Deduction only works if we have exactly one source expression.
11838   if (DeduceInits.empty()) {
11839     // It isn't possible to write this directly, but it is possible to
11840     // end up in this situation with "auto x(some_pack...);"
11841     Diag(Init->getBeginLoc(), IsInitCapture
11842                                   ? diag::err_init_capture_no_expression
11843                                   : diag::err_auto_var_init_no_expression)
11844         << VN << Type << Range;
11845     return QualType();
11846   }
11847 
11848   if (DeduceInits.size() > 1) {
11849     Diag(DeduceInits[1]->getBeginLoc(),
11850          IsInitCapture ? diag::err_init_capture_multiple_expressions
11851                        : diag::err_auto_var_init_multiple_expressions)
11852         << VN << Type << Range;
11853     return QualType();
11854   }
11855 
11856   Expr *DeduceInit = DeduceInits[0];
11857   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11858     Diag(Init->getBeginLoc(), IsInitCapture
11859                                   ? diag::err_init_capture_paren_braces
11860                                   : diag::err_auto_var_init_paren_braces)
11861         << isa<InitListExpr>(Init) << VN << Type << Range;
11862     return QualType();
11863   }
11864 
11865   // Expressions default to 'id' when we're in a debugger.
11866   bool DefaultedAnyToId = false;
11867   if (getLangOpts().DebuggerCastResultToId &&
11868       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11869     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11870     if (Result.isInvalid()) {
11871       return QualType();
11872     }
11873     Init = Result.get();
11874     DefaultedAnyToId = true;
11875   }
11876 
11877   // C++ [dcl.decomp]p1:
11878   //   If the assignment-expression [...] has array type A and no ref-qualifier
11879   //   is present, e has type cv A
11880   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11881       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11882       DeduceInit->getType()->isConstantArrayType())
11883     return Context.getQualifiedType(DeduceInit->getType(),
11884                                     Type.getQualifiers());
11885 
11886   QualType DeducedType;
11887   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11888     if (!IsInitCapture)
11889       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11890     else if (isa<InitListExpr>(Init))
11891       Diag(Range.getBegin(),
11892            diag::err_init_capture_deduction_failure_from_init_list)
11893           << VN
11894           << (DeduceInit->getType().isNull() ? TSI->getType()
11895                                              : DeduceInit->getType())
11896           << DeduceInit->getSourceRange();
11897     else
11898       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11899           << VN << TSI->getType()
11900           << (DeduceInit->getType().isNull() ? TSI->getType()
11901                                              : DeduceInit->getType())
11902           << DeduceInit->getSourceRange();
11903   }
11904 
11905   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11906   // 'id' instead of a specific object type prevents most of our usual
11907   // checks.
11908   // We only want to warn outside of template instantiations, though:
11909   // inside a template, the 'id' could have come from a parameter.
11910   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11911       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11912     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11913     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11914   }
11915 
11916   return DeducedType;
11917 }
11918 
11919 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11920                                          Expr *Init) {
11921   assert(!Init || !Init->containsErrors());
11922   QualType DeducedType = deduceVarTypeFromInitializer(
11923       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11924       VDecl->getSourceRange(), DirectInit, Init);
11925   if (DeducedType.isNull()) {
11926     VDecl->setInvalidDecl();
11927     return true;
11928   }
11929 
11930   VDecl->setType(DeducedType);
11931   assert(VDecl->isLinkageValid());
11932 
11933   // In ARC, infer lifetime.
11934   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11935     VDecl->setInvalidDecl();
11936 
11937   if (getLangOpts().OpenCL)
11938     deduceOpenCLAddressSpace(VDecl);
11939 
11940   // If this is a redeclaration, check that the type we just deduced matches
11941   // the previously declared type.
11942   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11943     // We never need to merge the type, because we cannot form an incomplete
11944     // array of auto, nor deduce such a type.
11945     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11946   }
11947 
11948   // Check the deduced type is valid for a variable declaration.
11949   CheckVariableDeclarationType(VDecl);
11950   return VDecl->isInvalidDecl();
11951 }
11952 
11953 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11954                                               SourceLocation Loc) {
11955   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11956     Init = EWC->getSubExpr();
11957 
11958   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11959     Init = CE->getSubExpr();
11960 
11961   QualType InitType = Init->getType();
11962   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11963           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11964          "shouldn't be called if type doesn't have a non-trivial C struct");
11965   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11966     for (auto I : ILE->inits()) {
11967       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11968           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11969         continue;
11970       SourceLocation SL = I->getExprLoc();
11971       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11972     }
11973     return;
11974   }
11975 
11976   if (isa<ImplicitValueInitExpr>(Init)) {
11977     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11978       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11979                             NTCUK_Init);
11980   } else {
11981     // Assume all other explicit initializers involving copying some existing
11982     // object.
11983     // TODO: ignore any explicit initializers where we can guarantee
11984     // copy-elision.
11985     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11986       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11987   }
11988 }
11989 
11990 namespace {
11991 
11992 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11993   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11994   // in the source code or implicitly by the compiler if it is in a union
11995   // defined in a system header and has non-trivial ObjC ownership
11996   // qualifications. We don't want those fields to participate in determining
11997   // whether the containing union is non-trivial.
11998   return FD->hasAttr<UnavailableAttr>();
11999 }
12000 
12001 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12002     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12003                                     void> {
12004   using Super =
12005       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12006                                     void>;
12007 
12008   DiagNonTrivalCUnionDefaultInitializeVisitor(
12009       QualType OrigTy, SourceLocation OrigLoc,
12010       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12011       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12012 
12013   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12014                      const FieldDecl *FD, bool InNonTrivialUnion) {
12015     if (const auto *AT = S.Context.getAsArrayType(QT))
12016       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12017                                      InNonTrivialUnion);
12018     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12019   }
12020 
12021   void visitARCStrong(QualType QT, const FieldDecl *FD,
12022                       bool InNonTrivialUnion) {
12023     if (InNonTrivialUnion)
12024       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12025           << 1 << 0 << QT << FD->getName();
12026   }
12027 
12028   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12029     if (InNonTrivialUnion)
12030       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12031           << 1 << 0 << QT << FD->getName();
12032   }
12033 
12034   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12035     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12036     if (RD->isUnion()) {
12037       if (OrigLoc.isValid()) {
12038         bool IsUnion = false;
12039         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12040           IsUnion = OrigRD->isUnion();
12041         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12042             << 0 << OrigTy << IsUnion << UseContext;
12043         // Reset OrigLoc so that this diagnostic is emitted only once.
12044         OrigLoc = SourceLocation();
12045       }
12046       InNonTrivialUnion = true;
12047     }
12048 
12049     if (InNonTrivialUnion)
12050       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12051           << 0 << 0 << QT.getUnqualifiedType() << "";
12052 
12053     for (const FieldDecl *FD : RD->fields())
12054       if (!shouldIgnoreForRecordTriviality(FD))
12055         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12056   }
12057 
12058   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12059 
12060   // The non-trivial C union type or the struct/union type that contains a
12061   // non-trivial C union.
12062   QualType OrigTy;
12063   SourceLocation OrigLoc;
12064   Sema::NonTrivialCUnionContext UseContext;
12065   Sema &S;
12066 };
12067 
12068 struct DiagNonTrivalCUnionDestructedTypeVisitor
12069     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12070   using Super =
12071       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12072 
12073   DiagNonTrivalCUnionDestructedTypeVisitor(
12074       QualType OrigTy, SourceLocation OrigLoc,
12075       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12076       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12077 
12078   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12079                      const FieldDecl *FD, bool InNonTrivialUnion) {
12080     if (const auto *AT = S.Context.getAsArrayType(QT))
12081       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12082                                      InNonTrivialUnion);
12083     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12084   }
12085 
12086   void visitARCStrong(QualType QT, const FieldDecl *FD,
12087                       bool InNonTrivialUnion) {
12088     if (InNonTrivialUnion)
12089       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12090           << 1 << 1 << QT << FD->getName();
12091   }
12092 
12093   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12094     if (InNonTrivialUnion)
12095       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12096           << 1 << 1 << QT << FD->getName();
12097   }
12098 
12099   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12100     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12101     if (RD->isUnion()) {
12102       if (OrigLoc.isValid()) {
12103         bool IsUnion = false;
12104         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12105           IsUnion = OrigRD->isUnion();
12106         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12107             << 1 << OrigTy << IsUnion << UseContext;
12108         // Reset OrigLoc so that this diagnostic is emitted only once.
12109         OrigLoc = SourceLocation();
12110       }
12111       InNonTrivialUnion = true;
12112     }
12113 
12114     if (InNonTrivialUnion)
12115       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12116           << 0 << 1 << QT.getUnqualifiedType() << "";
12117 
12118     for (const FieldDecl *FD : RD->fields())
12119       if (!shouldIgnoreForRecordTriviality(FD))
12120         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12121   }
12122 
12123   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12124   void visitCXXDestructor(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 struct DiagNonTrivalCUnionCopyVisitor
12136     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12137   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12138 
12139   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12140                                  Sema::NonTrivialCUnionContext UseContext,
12141                                  Sema &S)
12142       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12143 
12144   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12145                      const FieldDecl *FD, bool InNonTrivialUnion) {
12146     if (const auto *AT = S.Context.getAsArrayType(QT))
12147       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12148                                      InNonTrivialUnion);
12149     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12150   }
12151 
12152   void visitARCStrong(QualType QT, const FieldDecl *FD,
12153                       bool InNonTrivialUnion) {
12154     if (InNonTrivialUnion)
12155       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12156           << 1 << 2 << QT << FD->getName();
12157   }
12158 
12159   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12160     if (InNonTrivialUnion)
12161       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12162           << 1 << 2 << QT << FD->getName();
12163   }
12164 
12165   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12166     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12167     if (RD->isUnion()) {
12168       if (OrigLoc.isValid()) {
12169         bool IsUnion = false;
12170         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12171           IsUnion = OrigRD->isUnion();
12172         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12173             << 2 << OrigTy << IsUnion << UseContext;
12174         // Reset OrigLoc so that this diagnostic is emitted only once.
12175         OrigLoc = SourceLocation();
12176       }
12177       InNonTrivialUnion = true;
12178     }
12179 
12180     if (InNonTrivialUnion)
12181       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12182           << 0 << 2 << QT.getUnqualifiedType() << "";
12183 
12184     for (const FieldDecl *FD : RD->fields())
12185       if (!shouldIgnoreForRecordTriviality(FD))
12186         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12187   }
12188 
12189   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12190                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12191   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12192   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12193                             bool InNonTrivialUnion) {}
12194 
12195   // The non-trivial C union type or the struct/union type that contains a
12196   // non-trivial C union.
12197   QualType OrigTy;
12198   SourceLocation OrigLoc;
12199   Sema::NonTrivialCUnionContext UseContext;
12200   Sema &S;
12201 };
12202 
12203 } // namespace
12204 
12205 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12206                                  NonTrivialCUnionContext UseContext,
12207                                  unsigned NonTrivialKind) {
12208   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12209           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12210           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12211          "shouldn't be called if type doesn't have a non-trivial C union");
12212 
12213   if ((NonTrivialKind & NTCUK_Init) &&
12214       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12215     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12216         .visit(QT, nullptr, false);
12217   if ((NonTrivialKind & NTCUK_Destruct) &&
12218       QT.hasNonTrivialToPrimitiveDestructCUnion())
12219     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12220         .visit(QT, nullptr, false);
12221   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12222     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12223         .visit(QT, nullptr, false);
12224 }
12225 
12226 /// AddInitializerToDecl - Adds the initializer Init to the
12227 /// declaration dcl. If DirectInit is true, this is C++ direct
12228 /// initialization rather than copy initialization.
12229 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12230   // If there is no declaration, there was an error parsing it.  Just ignore
12231   // the initializer.
12232   if (!RealDecl || RealDecl->isInvalidDecl()) {
12233     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12234     return;
12235   }
12236 
12237   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12238     // Pure-specifiers are handled in ActOnPureSpecifier.
12239     Diag(Method->getLocation(), diag::err_member_function_initialization)
12240       << Method->getDeclName() << Init->getSourceRange();
12241     Method->setInvalidDecl();
12242     return;
12243   }
12244 
12245   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12246   if (!VDecl) {
12247     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12248     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12249     RealDecl->setInvalidDecl();
12250     return;
12251   }
12252 
12253   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12254   if (VDecl->getType()->isUndeducedType()) {
12255     // Attempt typo correction early so that the type of the init expression can
12256     // be deduced based on the chosen correction if the original init contains a
12257     // TypoExpr.
12258     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12259     if (!Res.isUsable()) {
12260       // There are unresolved typos in Init, just drop them.
12261       // FIXME: improve the recovery strategy to preserve the Init.
12262       RealDecl->setInvalidDecl();
12263       return;
12264     }
12265     if (Res.get()->containsErrors()) {
12266       // Invalidate the decl as we don't know the type for recovery-expr yet.
12267       RealDecl->setInvalidDecl();
12268       VDecl->setInit(Res.get());
12269       return;
12270     }
12271     Init = Res.get();
12272 
12273     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12274       return;
12275   }
12276 
12277   // dllimport cannot be used on variable definitions.
12278   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12279     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12280     VDecl->setInvalidDecl();
12281     return;
12282   }
12283 
12284   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12285     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12286     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12287     VDecl->setInvalidDecl();
12288     return;
12289   }
12290 
12291   if (!VDecl->getType()->isDependentType()) {
12292     // A definition must end up with a complete type, which means it must be
12293     // complete with the restriction that an array type might be completed by
12294     // the initializer; note that later code assumes this restriction.
12295     QualType BaseDeclType = VDecl->getType();
12296     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12297       BaseDeclType = Array->getElementType();
12298     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12299                             diag::err_typecheck_decl_incomplete_type)) {
12300       RealDecl->setInvalidDecl();
12301       return;
12302     }
12303 
12304     // The variable can not have an abstract class type.
12305     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12306                                diag::err_abstract_type_in_decl,
12307                                AbstractVariableType))
12308       VDecl->setInvalidDecl();
12309   }
12310 
12311   // If adding the initializer will turn this declaration into a definition,
12312   // and we already have a definition for this variable, diagnose or otherwise
12313   // handle the situation.
12314   if (VarDecl *Def = VDecl->getDefinition())
12315     if (Def != VDecl &&
12316         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12317         !VDecl->isThisDeclarationADemotedDefinition() &&
12318         checkVarDeclRedefinition(Def, VDecl))
12319       return;
12320 
12321   if (getLangOpts().CPlusPlus) {
12322     // C++ [class.static.data]p4
12323     //   If a static data member is of const integral or const
12324     //   enumeration type, its declaration in the class definition can
12325     //   specify a constant-initializer which shall be an integral
12326     //   constant expression (5.19). In that case, the member can appear
12327     //   in integral constant expressions. The member shall still be
12328     //   defined in a namespace scope if it is used in the program and the
12329     //   namespace scope definition shall not contain an initializer.
12330     //
12331     // We already performed a redefinition check above, but for static
12332     // data members we also need to check whether there was an in-class
12333     // declaration with an initializer.
12334     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12335       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12336           << VDecl->getDeclName();
12337       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12338            diag::note_previous_initializer)
12339           << 0;
12340       return;
12341     }
12342 
12343     if (VDecl->hasLocalStorage())
12344       setFunctionHasBranchProtectedScope();
12345 
12346     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12347       VDecl->setInvalidDecl();
12348       return;
12349     }
12350   }
12351 
12352   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12353   // a kernel function cannot be initialized."
12354   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12355     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12356     VDecl->setInvalidDecl();
12357     return;
12358   }
12359 
12360   // The LoaderUninitialized attribute acts as a definition (of undef).
12361   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12362     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12363     VDecl->setInvalidDecl();
12364     return;
12365   }
12366 
12367   // Get the decls type and save a reference for later, since
12368   // CheckInitializerTypes may change it.
12369   QualType DclT = VDecl->getType(), SavT = DclT;
12370 
12371   // Expressions default to 'id' when we're in a debugger
12372   // and we are assigning it to a variable of Objective-C pointer type.
12373   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12374       Init->getType() == Context.UnknownAnyTy) {
12375     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12376     if (Result.isInvalid()) {
12377       VDecl->setInvalidDecl();
12378       return;
12379     }
12380     Init = Result.get();
12381   }
12382 
12383   // Perform the initialization.
12384   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12385   if (!VDecl->isInvalidDecl()) {
12386     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12387     InitializationKind Kind = InitializationKind::CreateForInit(
12388         VDecl->getLocation(), DirectInit, Init);
12389 
12390     MultiExprArg Args = Init;
12391     if (CXXDirectInit)
12392       Args = MultiExprArg(CXXDirectInit->getExprs(),
12393                           CXXDirectInit->getNumExprs());
12394 
12395     // Try to correct any TypoExprs in the initialization arguments.
12396     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12397       ExprResult Res = CorrectDelayedTyposInExpr(
12398           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12399           [this, Entity, Kind](Expr *E) {
12400             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12401             return Init.Failed() ? ExprError() : E;
12402           });
12403       if (Res.isInvalid()) {
12404         VDecl->setInvalidDecl();
12405       } else if (Res.get() != Args[Idx]) {
12406         Args[Idx] = Res.get();
12407       }
12408     }
12409     if (VDecl->isInvalidDecl())
12410       return;
12411 
12412     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12413                                    /*TopLevelOfInitList=*/false,
12414                                    /*TreatUnavailableAsInvalid=*/false);
12415     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12416     if (Result.isInvalid()) {
12417       // If the provided initializer fails to initialize the var decl,
12418       // we attach a recovery expr for better recovery.
12419       auto RecoveryExpr =
12420           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12421       if (RecoveryExpr.get())
12422         VDecl->setInit(RecoveryExpr.get());
12423       return;
12424     }
12425 
12426     Init = Result.getAs<Expr>();
12427   }
12428 
12429   // Check for self-references within variable initializers.
12430   // Variables declared within a function/method body (except for references)
12431   // are handled by a dataflow analysis.
12432   // This is undefined behavior in C++, but valid in C.
12433   if (getLangOpts().CPlusPlus)
12434     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12435         VDecl->getType()->isReferenceType())
12436       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12437 
12438   // If the type changed, it means we had an incomplete type that was
12439   // completed by the initializer. For example:
12440   //   int ary[] = { 1, 3, 5 };
12441   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12442   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12443     VDecl->setType(DclT);
12444 
12445   if (!VDecl->isInvalidDecl()) {
12446     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12447 
12448     if (VDecl->hasAttr<BlocksAttr>())
12449       checkRetainCycles(VDecl, Init);
12450 
12451     // It is safe to assign a weak reference into a strong variable.
12452     // Although this code can still have problems:
12453     //   id x = self.weakProp;
12454     //   id y = self.weakProp;
12455     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12456     // paths through the function. This should be revisited if
12457     // -Wrepeated-use-of-weak is made flow-sensitive.
12458     if (FunctionScopeInfo *FSI = getCurFunction())
12459       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12460            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12461           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12462                            Init->getBeginLoc()))
12463         FSI->markSafeWeakUse(Init);
12464   }
12465 
12466   // The initialization is usually a full-expression.
12467   //
12468   // FIXME: If this is a braced initialization of an aggregate, it is not
12469   // an expression, and each individual field initializer is a separate
12470   // full-expression. For instance, in:
12471   //
12472   //   struct Temp { ~Temp(); };
12473   //   struct S { S(Temp); };
12474   //   struct T { S a, b; } t = { Temp(), Temp() }
12475   //
12476   // we should destroy the first Temp before constructing the second.
12477   ExprResult Result =
12478       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12479                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12480   if (Result.isInvalid()) {
12481     VDecl->setInvalidDecl();
12482     return;
12483   }
12484   Init = Result.get();
12485 
12486   // Attach the initializer to the decl.
12487   VDecl->setInit(Init);
12488 
12489   if (VDecl->isLocalVarDecl()) {
12490     // Don't check the initializer if the declaration is malformed.
12491     if (VDecl->isInvalidDecl()) {
12492       // do nothing
12493 
12494     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12495     // This is true even in C++ for OpenCL.
12496     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12497       CheckForConstantInitializer(Init, DclT);
12498 
12499     // Otherwise, C++ does not restrict the initializer.
12500     } else if (getLangOpts().CPlusPlus) {
12501       // do nothing
12502 
12503     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12504     // static storage duration shall be constant expressions or string literals.
12505     } else if (VDecl->getStorageClass() == SC_Static) {
12506       CheckForConstantInitializer(Init, DclT);
12507 
12508     // C89 is stricter than C99 for aggregate initializers.
12509     // C89 6.5.7p3: All the expressions [...] in an initializer list
12510     // for an object that has aggregate or union type shall be
12511     // constant expressions.
12512     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12513                isa<InitListExpr>(Init)) {
12514       const Expr *Culprit;
12515       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12516         Diag(Culprit->getExprLoc(),
12517              diag::ext_aggregate_init_not_constant)
12518           << Culprit->getSourceRange();
12519       }
12520     }
12521 
12522     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12523       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12524         if (VDecl->hasLocalStorage())
12525           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12526   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12527              VDecl->getLexicalDeclContext()->isRecord()) {
12528     // This is an in-class initialization for a static data member, e.g.,
12529     //
12530     // struct S {
12531     //   static const int value = 17;
12532     // };
12533 
12534     // C++ [class.mem]p4:
12535     //   A member-declarator can contain a constant-initializer only
12536     //   if it declares a static member (9.4) of const integral or
12537     //   const enumeration type, see 9.4.2.
12538     //
12539     // C++11 [class.static.data]p3:
12540     //   If a non-volatile non-inline const static data member is of integral
12541     //   or enumeration type, its declaration in the class definition can
12542     //   specify a brace-or-equal-initializer in which every initializer-clause
12543     //   that is an assignment-expression is a constant expression. A static
12544     //   data member of literal type can be declared in the class definition
12545     //   with the constexpr specifier; if so, its declaration shall specify a
12546     //   brace-or-equal-initializer in which every initializer-clause that is
12547     //   an assignment-expression is a constant expression.
12548 
12549     // Do nothing on dependent types.
12550     if (DclT->isDependentType()) {
12551 
12552     // Allow any 'static constexpr' members, whether or not they are of literal
12553     // type. We separately check that every constexpr variable is of literal
12554     // type.
12555     } else if (VDecl->isConstexpr()) {
12556 
12557     // Require constness.
12558     } else if (!DclT.isConstQualified()) {
12559       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12560         << Init->getSourceRange();
12561       VDecl->setInvalidDecl();
12562 
12563     // We allow integer constant expressions in all cases.
12564     } else if (DclT->isIntegralOrEnumerationType()) {
12565       // Check whether the expression is a constant expression.
12566       SourceLocation Loc;
12567       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12568         // In C++11, a non-constexpr const static data member with an
12569         // in-class initializer cannot be volatile.
12570         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12571       else if (Init->isValueDependent())
12572         ; // Nothing to check.
12573       else if (Init->isIntegerConstantExpr(Context, &Loc))
12574         ; // Ok, it's an ICE!
12575       else if (Init->getType()->isScopedEnumeralType() &&
12576                Init->isCXX11ConstantExpr(Context))
12577         ; // Ok, it is a scoped-enum constant expression.
12578       else if (Init->isEvaluatable(Context)) {
12579         // If we can constant fold the initializer through heroics, accept it,
12580         // but report this as a use of an extension for -pedantic.
12581         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12582           << Init->getSourceRange();
12583       } else {
12584         // Otherwise, this is some crazy unknown case.  Report the issue at the
12585         // location provided by the isIntegerConstantExpr failed check.
12586         Diag(Loc, diag::err_in_class_initializer_non_constant)
12587           << Init->getSourceRange();
12588         VDecl->setInvalidDecl();
12589       }
12590 
12591     // We allow foldable floating-point constants as an extension.
12592     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12593       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12594       // it anyway and provide a fixit to add the 'constexpr'.
12595       if (getLangOpts().CPlusPlus11) {
12596         Diag(VDecl->getLocation(),
12597              diag::ext_in_class_initializer_float_type_cxx11)
12598             << DclT << Init->getSourceRange();
12599         Diag(VDecl->getBeginLoc(),
12600              diag::note_in_class_initializer_float_type_cxx11)
12601             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12602       } else {
12603         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12604           << DclT << Init->getSourceRange();
12605 
12606         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12607           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12608             << Init->getSourceRange();
12609           VDecl->setInvalidDecl();
12610         }
12611       }
12612 
12613     // Suggest adding 'constexpr' in C++11 for literal types.
12614     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12615       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12616           << DclT << Init->getSourceRange()
12617           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12618       VDecl->setConstexpr(true);
12619 
12620     } else {
12621       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12622         << DclT << Init->getSourceRange();
12623       VDecl->setInvalidDecl();
12624     }
12625   } else if (VDecl->isFileVarDecl()) {
12626     // In C, extern is typically used to avoid tentative definitions when
12627     // declaring variables in headers, but adding an intializer makes it a
12628     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12629     // In C++, extern is often used to give implictly static const variables
12630     // external linkage, so don't warn in that case. If selectany is present,
12631     // this might be header code intended for C and C++ inclusion, so apply the
12632     // C++ rules.
12633     if (VDecl->getStorageClass() == SC_Extern &&
12634         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12635          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12636         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12637         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12638       Diag(VDecl->getLocation(), diag::warn_extern_init);
12639 
12640     // In Microsoft C++ mode, a const variable defined in namespace scope has
12641     // external linkage by default if the variable is declared with
12642     // __declspec(dllexport).
12643     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12644         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12645         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12646       VDecl->setStorageClass(SC_Extern);
12647 
12648     // C99 6.7.8p4. All file scoped initializers need to be constant.
12649     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12650       CheckForConstantInitializer(Init, DclT);
12651   }
12652 
12653   QualType InitType = Init->getType();
12654   if (!InitType.isNull() &&
12655       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12656        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12657     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12658 
12659   // We will represent direct-initialization similarly to copy-initialization:
12660   //    int x(1);  -as-> int x = 1;
12661   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12662   //
12663   // Clients that want to distinguish between the two forms, can check for
12664   // direct initializer using VarDecl::getInitStyle().
12665   // A major benefit is that clients that don't particularly care about which
12666   // exactly form was it (like the CodeGen) can handle both cases without
12667   // special case code.
12668 
12669   // C++ 8.5p11:
12670   // The form of initialization (using parentheses or '=') is generally
12671   // insignificant, but does matter when the entity being initialized has a
12672   // class type.
12673   if (CXXDirectInit) {
12674     assert(DirectInit && "Call-style initializer must be direct init.");
12675     VDecl->setInitStyle(VarDecl::CallInit);
12676   } else if (DirectInit) {
12677     // This must be list-initialization. No other way is direct-initialization.
12678     VDecl->setInitStyle(VarDecl::ListInit);
12679   }
12680 
12681   if (LangOpts.OpenMP &&
12682       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12683       VDecl->isFileVarDecl())
12684     DeclsToCheckForDeferredDiags.insert(VDecl);
12685   CheckCompleteVariableDeclaration(VDecl);
12686 }
12687 
12688 /// ActOnInitializerError - Given that there was an error parsing an
12689 /// initializer for the given declaration, try to at least re-establish
12690 /// invariants such as whether a variable's type is either dependent or
12691 /// complete.
12692 void Sema::ActOnInitializerError(Decl *D) {
12693   // Our main concern here is re-establishing invariants like "a
12694   // variable's type is either dependent or complete".
12695   if (!D || D->isInvalidDecl()) return;
12696 
12697   VarDecl *VD = dyn_cast<VarDecl>(D);
12698   if (!VD) return;
12699 
12700   // Bindings are not usable if we can't make sense of the initializer.
12701   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12702     for (auto *BD : DD->bindings())
12703       BD->setInvalidDecl();
12704 
12705   // Auto types are meaningless if we can't make sense of the initializer.
12706   if (VD->getType()->isUndeducedType()) {
12707     D->setInvalidDecl();
12708     return;
12709   }
12710 
12711   QualType Ty = VD->getType();
12712   if (Ty->isDependentType()) return;
12713 
12714   // Require a complete type.
12715   if (RequireCompleteType(VD->getLocation(),
12716                           Context.getBaseElementType(Ty),
12717                           diag::err_typecheck_decl_incomplete_type)) {
12718     VD->setInvalidDecl();
12719     return;
12720   }
12721 
12722   // Require a non-abstract type.
12723   if (RequireNonAbstractType(VD->getLocation(), Ty,
12724                              diag::err_abstract_type_in_decl,
12725                              AbstractVariableType)) {
12726     VD->setInvalidDecl();
12727     return;
12728   }
12729 
12730   // Don't bother complaining about constructors or destructors,
12731   // though.
12732 }
12733 
12734 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12735   // If there is no declaration, there was an error parsing it. Just ignore it.
12736   if (!RealDecl)
12737     return;
12738 
12739   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12740     QualType Type = Var->getType();
12741 
12742     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12743     if (isa<DecompositionDecl>(RealDecl)) {
12744       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12745       Var->setInvalidDecl();
12746       return;
12747     }
12748 
12749     if (Type->isUndeducedType() &&
12750         DeduceVariableDeclarationType(Var, false, nullptr))
12751       return;
12752 
12753     // C++11 [class.static.data]p3: A static data member can be declared with
12754     // the constexpr specifier; if so, its declaration shall specify
12755     // a brace-or-equal-initializer.
12756     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12757     // the definition of a variable [...] or the declaration of a static data
12758     // member.
12759     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12760         !Var->isThisDeclarationADemotedDefinition()) {
12761       if (Var->isStaticDataMember()) {
12762         // C++1z removes the relevant rule; the in-class declaration is always
12763         // a definition there.
12764         if (!getLangOpts().CPlusPlus17 &&
12765             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12766           Diag(Var->getLocation(),
12767                diag::err_constexpr_static_mem_var_requires_init)
12768               << Var;
12769           Var->setInvalidDecl();
12770           return;
12771         }
12772       } else {
12773         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12774         Var->setInvalidDecl();
12775         return;
12776       }
12777     }
12778 
12779     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12780     // be initialized.
12781     if (!Var->isInvalidDecl() &&
12782         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12783         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12784       bool HasConstExprDefaultConstructor = false;
12785       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12786         for (auto *Ctor : RD->ctors()) {
12787           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12788               Ctor->getMethodQualifiers().getAddressSpace() ==
12789                   LangAS::opencl_constant) {
12790             HasConstExprDefaultConstructor = true;
12791           }
12792         }
12793       }
12794       if (!HasConstExprDefaultConstructor) {
12795         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12796         Var->setInvalidDecl();
12797         return;
12798       }
12799     }
12800 
12801     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12802       if (Var->getStorageClass() == SC_Extern) {
12803         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12804             << Var;
12805         Var->setInvalidDecl();
12806         return;
12807       }
12808       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12809                               diag::err_typecheck_decl_incomplete_type)) {
12810         Var->setInvalidDecl();
12811         return;
12812       }
12813       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12814         if (!RD->hasTrivialDefaultConstructor()) {
12815           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12816           Var->setInvalidDecl();
12817           return;
12818         }
12819       }
12820       // The declaration is unitialized, no need for further checks.
12821       return;
12822     }
12823 
12824     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12825     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12826         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12827       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12828                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12829 
12830 
12831     switch (DefKind) {
12832     case VarDecl::Definition:
12833       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12834         break;
12835 
12836       // We have an out-of-line definition of a static data member
12837       // that has an in-class initializer, so we type-check this like
12838       // a declaration.
12839       //
12840       LLVM_FALLTHROUGH;
12841 
12842     case VarDecl::DeclarationOnly:
12843       // It's only a declaration.
12844 
12845       // Block scope. C99 6.7p7: If an identifier for an object is
12846       // declared with no linkage (C99 6.2.2p6), the type for the
12847       // object shall be complete.
12848       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12849           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12850           RequireCompleteType(Var->getLocation(), Type,
12851                               diag::err_typecheck_decl_incomplete_type))
12852         Var->setInvalidDecl();
12853 
12854       // Make sure that the type is not abstract.
12855       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12856           RequireNonAbstractType(Var->getLocation(), Type,
12857                                  diag::err_abstract_type_in_decl,
12858                                  AbstractVariableType))
12859         Var->setInvalidDecl();
12860       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12861           Var->getStorageClass() == SC_PrivateExtern) {
12862         Diag(Var->getLocation(), diag::warn_private_extern);
12863         Diag(Var->getLocation(), diag::note_private_extern);
12864       }
12865 
12866       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12867           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12868         ExternalDeclarations.push_back(Var);
12869 
12870       return;
12871 
12872     case VarDecl::TentativeDefinition:
12873       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12874       // object that has file scope without an initializer, and without a
12875       // storage-class specifier or with the storage-class specifier "static",
12876       // constitutes a tentative definition. Note: A tentative definition with
12877       // external linkage is valid (C99 6.2.2p5).
12878       if (!Var->isInvalidDecl()) {
12879         if (const IncompleteArrayType *ArrayT
12880                                     = Context.getAsIncompleteArrayType(Type)) {
12881           if (RequireCompleteSizedType(
12882                   Var->getLocation(), ArrayT->getElementType(),
12883                   diag::err_array_incomplete_or_sizeless_type))
12884             Var->setInvalidDecl();
12885         } else if (Var->getStorageClass() == SC_Static) {
12886           // C99 6.9.2p3: If the declaration of an identifier for an object is
12887           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12888           // declared type shall not be an incomplete type.
12889           // NOTE: code such as the following
12890           //     static struct s;
12891           //     struct s { int a; };
12892           // is accepted by gcc. Hence here we issue a warning instead of
12893           // an error and we do not invalidate the static declaration.
12894           // NOTE: to avoid multiple warnings, only check the first declaration.
12895           if (Var->isFirstDecl())
12896             RequireCompleteType(Var->getLocation(), Type,
12897                                 diag::ext_typecheck_decl_incomplete_type);
12898         }
12899       }
12900 
12901       // Record the tentative definition; we're done.
12902       if (!Var->isInvalidDecl())
12903         TentativeDefinitions.push_back(Var);
12904       return;
12905     }
12906 
12907     // Provide a specific diagnostic for uninitialized variable
12908     // definitions with incomplete array type.
12909     if (Type->isIncompleteArrayType()) {
12910       Diag(Var->getLocation(),
12911            diag::err_typecheck_incomplete_array_needs_initializer);
12912       Var->setInvalidDecl();
12913       return;
12914     }
12915 
12916     // Provide a specific diagnostic for uninitialized variable
12917     // definitions with reference type.
12918     if (Type->isReferenceType()) {
12919       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12920           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12921       Var->setInvalidDecl();
12922       return;
12923     }
12924 
12925     // Do not attempt to type-check the default initializer for a
12926     // variable with dependent type.
12927     if (Type->isDependentType())
12928       return;
12929 
12930     if (Var->isInvalidDecl())
12931       return;
12932 
12933     if (!Var->hasAttr<AliasAttr>()) {
12934       if (RequireCompleteType(Var->getLocation(),
12935                               Context.getBaseElementType(Type),
12936                               diag::err_typecheck_decl_incomplete_type)) {
12937         Var->setInvalidDecl();
12938         return;
12939       }
12940     } else {
12941       return;
12942     }
12943 
12944     // The variable can not have an abstract class type.
12945     if (RequireNonAbstractType(Var->getLocation(), Type,
12946                                diag::err_abstract_type_in_decl,
12947                                AbstractVariableType)) {
12948       Var->setInvalidDecl();
12949       return;
12950     }
12951 
12952     // Check for jumps past the implicit initializer.  C++0x
12953     // clarifies that this applies to a "variable with automatic
12954     // storage duration", not a "local variable".
12955     // C++11 [stmt.dcl]p3
12956     //   A program that jumps from a point where a variable with automatic
12957     //   storage duration is not in scope to a point where it is in scope is
12958     //   ill-formed unless the variable has scalar type, class type with a
12959     //   trivial default constructor and a trivial destructor, a cv-qualified
12960     //   version of one of these types, or an array of one of the preceding
12961     //   types and is declared without an initializer.
12962     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12963       if (const RecordType *Record
12964             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12965         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12966         // Mark the function (if we're in one) for further checking even if the
12967         // looser rules of C++11 do not require such checks, so that we can
12968         // diagnose incompatibilities with C++98.
12969         if (!CXXRecord->isPOD())
12970           setFunctionHasBranchProtectedScope();
12971       }
12972     }
12973     // In OpenCL, we can't initialize objects in the __local address space,
12974     // even implicitly, so don't synthesize an implicit initializer.
12975     if (getLangOpts().OpenCL &&
12976         Var->getType().getAddressSpace() == LangAS::opencl_local)
12977       return;
12978     // C++03 [dcl.init]p9:
12979     //   If no initializer is specified for an object, and the
12980     //   object is of (possibly cv-qualified) non-POD class type (or
12981     //   array thereof), the object shall be default-initialized; if
12982     //   the object is of const-qualified type, the underlying class
12983     //   type shall have a user-declared default
12984     //   constructor. Otherwise, if no initializer is specified for
12985     //   a non- static object, the object and its subobjects, if
12986     //   any, have an indeterminate initial value); if the object
12987     //   or any of its subobjects are of const-qualified type, the
12988     //   program is ill-formed.
12989     // C++0x [dcl.init]p11:
12990     //   If no initializer is specified for an object, the object is
12991     //   default-initialized; [...].
12992     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12993     InitializationKind Kind
12994       = InitializationKind::CreateDefault(Var->getLocation());
12995 
12996     InitializationSequence InitSeq(*this, Entity, Kind, None);
12997     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12998 
12999     if (Init.get()) {
13000       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13001       // This is important for template substitution.
13002       Var->setInitStyle(VarDecl::CallInit);
13003     } else if (Init.isInvalid()) {
13004       // If default-init fails, attach a recovery-expr initializer to track
13005       // that initialization was attempted and failed.
13006       auto RecoveryExpr =
13007           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13008       if (RecoveryExpr.get())
13009         Var->setInit(RecoveryExpr.get());
13010     }
13011 
13012     CheckCompleteVariableDeclaration(Var);
13013   }
13014 }
13015 
13016 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13017   // If there is no declaration, there was an error parsing it. Ignore it.
13018   if (!D)
13019     return;
13020 
13021   VarDecl *VD = dyn_cast<VarDecl>(D);
13022   if (!VD) {
13023     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13024     D->setInvalidDecl();
13025     return;
13026   }
13027 
13028   VD->setCXXForRangeDecl(true);
13029 
13030   // for-range-declaration cannot be given a storage class specifier.
13031   int Error = -1;
13032   switch (VD->getStorageClass()) {
13033   case SC_None:
13034     break;
13035   case SC_Extern:
13036     Error = 0;
13037     break;
13038   case SC_Static:
13039     Error = 1;
13040     break;
13041   case SC_PrivateExtern:
13042     Error = 2;
13043     break;
13044   case SC_Auto:
13045     Error = 3;
13046     break;
13047   case SC_Register:
13048     Error = 4;
13049     break;
13050   }
13051 
13052   // for-range-declaration cannot be given a storage class specifier con't.
13053   switch (VD->getTSCSpec()) {
13054   case TSCS_thread_local:
13055     Error = 6;
13056     break;
13057   case TSCS___thread:
13058   case TSCS__Thread_local:
13059   case TSCS_unspecified:
13060     break;
13061   }
13062 
13063   if (Error != -1) {
13064     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13065         << VD << Error;
13066     D->setInvalidDecl();
13067   }
13068 }
13069 
13070 StmtResult
13071 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13072                                  IdentifierInfo *Ident,
13073                                  ParsedAttributes &Attrs,
13074                                  SourceLocation AttrEnd) {
13075   // C++1y [stmt.iter]p1:
13076   //   A range-based for statement of the form
13077   //      for ( for-range-identifier : for-range-initializer ) statement
13078   //   is equivalent to
13079   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13080   DeclSpec DS(Attrs.getPool().getFactory());
13081 
13082   const char *PrevSpec;
13083   unsigned DiagID;
13084   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13085                      getPrintingPolicy());
13086 
13087   Declarator D(DS, DeclaratorContext::ForInit);
13088   D.SetIdentifier(Ident, IdentLoc);
13089   D.takeAttributes(Attrs, AttrEnd);
13090 
13091   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13092                 IdentLoc);
13093   Decl *Var = ActOnDeclarator(S, D);
13094   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13095   FinalizeDeclaration(Var);
13096   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13097                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13098 }
13099 
13100 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13101   if (var->isInvalidDecl()) return;
13102 
13103   MaybeAddCUDAConstantAttr(var);
13104 
13105   if (getLangOpts().OpenCL) {
13106     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13107     // initialiser
13108     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13109         !var->hasInit()) {
13110       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13111           << 1 /*Init*/;
13112       var->setInvalidDecl();
13113       return;
13114     }
13115   }
13116 
13117   // In Objective-C, don't allow jumps past the implicit initialization of a
13118   // local retaining variable.
13119   if (getLangOpts().ObjC &&
13120       var->hasLocalStorage()) {
13121     switch (var->getType().getObjCLifetime()) {
13122     case Qualifiers::OCL_None:
13123     case Qualifiers::OCL_ExplicitNone:
13124     case Qualifiers::OCL_Autoreleasing:
13125       break;
13126 
13127     case Qualifiers::OCL_Weak:
13128     case Qualifiers::OCL_Strong:
13129       setFunctionHasBranchProtectedScope();
13130       break;
13131     }
13132   }
13133 
13134   if (var->hasLocalStorage() &&
13135       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13136     setFunctionHasBranchProtectedScope();
13137 
13138   // Warn about externally-visible variables being defined without a
13139   // prior declaration.  We only want to do this for global
13140   // declarations, but we also specifically need to avoid doing it for
13141   // class members because the linkage of an anonymous class can
13142   // change if it's later given a typedef name.
13143   if (var->isThisDeclarationADefinition() &&
13144       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13145       var->isExternallyVisible() && var->hasLinkage() &&
13146       !var->isInline() && !var->getDescribedVarTemplate() &&
13147       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13148       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13149       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13150                                   var->getLocation())) {
13151     // Find a previous declaration that's not a definition.
13152     VarDecl *prev = var->getPreviousDecl();
13153     while (prev && prev->isThisDeclarationADefinition())
13154       prev = prev->getPreviousDecl();
13155 
13156     if (!prev) {
13157       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13158       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13159           << /* variable */ 0;
13160     }
13161   }
13162 
13163   // Cache the result of checking for constant initialization.
13164   Optional<bool> CacheHasConstInit;
13165   const Expr *CacheCulprit = nullptr;
13166   auto checkConstInit = [&]() mutable {
13167     if (!CacheHasConstInit)
13168       CacheHasConstInit = var->getInit()->isConstantInitializer(
13169             Context, var->getType()->isReferenceType(), &CacheCulprit);
13170     return *CacheHasConstInit;
13171   };
13172 
13173   if (var->getTLSKind() == VarDecl::TLS_Static) {
13174     if (var->getType().isDestructedType()) {
13175       // GNU C++98 edits for __thread, [basic.start.term]p3:
13176       //   The type of an object with thread storage duration shall not
13177       //   have a non-trivial destructor.
13178       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13179       if (getLangOpts().CPlusPlus11)
13180         Diag(var->getLocation(), diag::note_use_thread_local);
13181     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13182       if (!checkConstInit()) {
13183         // GNU C++98 edits for __thread, [basic.start.init]p4:
13184         //   An object of thread storage duration shall not require dynamic
13185         //   initialization.
13186         // FIXME: Need strict checking here.
13187         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13188           << CacheCulprit->getSourceRange();
13189         if (getLangOpts().CPlusPlus11)
13190           Diag(var->getLocation(), diag::note_use_thread_local);
13191       }
13192     }
13193   }
13194 
13195 
13196   if (!var->getType()->isStructureType() && var->hasInit() &&
13197       isa<InitListExpr>(var->getInit())) {
13198     const auto *ILE = cast<InitListExpr>(var->getInit());
13199     unsigned NumInits = ILE->getNumInits();
13200     if (NumInits > 2)
13201       for (unsigned I = 0; I < NumInits; ++I) {
13202         const auto *Init = ILE->getInit(I);
13203         if (!Init)
13204           break;
13205         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13206         if (!SL)
13207           break;
13208 
13209         unsigned NumConcat = SL->getNumConcatenated();
13210         // Diagnose missing comma in string array initialization.
13211         // Do not warn when all the elements in the initializer are concatenated
13212         // together. Do not warn for macros too.
13213         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13214           bool OnlyOneMissingComma = true;
13215           for (unsigned J = I + 1; J < NumInits; ++J) {
13216             const auto *Init = ILE->getInit(J);
13217             if (!Init)
13218               break;
13219             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13220             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13221               OnlyOneMissingComma = false;
13222               break;
13223             }
13224           }
13225 
13226           if (OnlyOneMissingComma) {
13227             SmallVector<FixItHint, 1> Hints;
13228             for (unsigned i = 0; i < NumConcat - 1; ++i)
13229               Hints.push_back(FixItHint::CreateInsertion(
13230                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13231 
13232             Diag(SL->getStrTokenLoc(1),
13233                  diag::warn_concatenated_literal_array_init)
13234                 << Hints;
13235             Diag(SL->getBeginLoc(),
13236                  diag::note_concatenated_string_literal_silence);
13237           }
13238           // In any case, stop now.
13239           break;
13240         }
13241       }
13242   }
13243 
13244 
13245   QualType type = var->getType();
13246 
13247   if (var->hasAttr<BlocksAttr>())
13248     getCurFunction()->addByrefBlockVar(var);
13249 
13250   Expr *Init = var->getInit();
13251   bool GlobalStorage = var->hasGlobalStorage();
13252   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13253   QualType baseType = Context.getBaseElementType(type);
13254   bool HasConstInit = true;
13255 
13256   // Check whether the initializer is sufficiently constant.
13257   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13258       !Init->isValueDependent() &&
13259       (GlobalStorage || var->isConstexpr() ||
13260        var->mightBeUsableInConstantExpressions(Context))) {
13261     // If this variable might have a constant initializer or might be usable in
13262     // constant expressions, check whether or not it actually is now.  We can't
13263     // do this lazily, because the result might depend on things that change
13264     // later, such as which constexpr functions happen to be defined.
13265     SmallVector<PartialDiagnosticAt, 8> Notes;
13266     if (!getLangOpts().CPlusPlus11) {
13267       // Prior to C++11, in contexts where a constant initializer is required,
13268       // the set of valid constant initializers is described by syntactic rules
13269       // in [expr.const]p2-6.
13270       // FIXME: Stricter checking for these rules would be useful for constinit /
13271       // -Wglobal-constructors.
13272       HasConstInit = checkConstInit();
13273 
13274       // Compute and cache the constant value, and remember that we have a
13275       // constant initializer.
13276       if (HasConstInit) {
13277         (void)var->checkForConstantInitialization(Notes);
13278         Notes.clear();
13279       } else if (CacheCulprit) {
13280         Notes.emplace_back(CacheCulprit->getExprLoc(),
13281                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13282         Notes.back().second << CacheCulprit->getSourceRange();
13283       }
13284     } else {
13285       // Evaluate the initializer to see if it's a constant initializer.
13286       HasConstInit = var->checkForConstantInitialization(Notes);
13287     }
13288 
13289     if (HasConstInit) {
13290       // FIXME: Consider replacing the initializer with a ConstantExpr.
13291     } else if (var->isConstexpr()) {
13292       SourceLocation DiagLoc = var->getLocation();
13293       // If the note doesn't add any useful information other than a source
13294       // location, fold it into the primary diagnostic.
13295       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13296                                    diag::note_invalid_subexpr_in_const_expr) {
13297         DiagLoc = Notes[0].first;
13298         Notes.clear();
13299       }
13300       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13301           << var << Init->getSourceRange();
13302       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13303         Diag(Notes[I].first, Notes[I].second);
13304     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13305       auto *Attr = var->getAttr<ConstInitAttr>();
13306       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13307           << Init->getSourceRange();
13308       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13309           << Attr->getRange() << Attr->isConstinit();
13310       for (auto &it : Notes)
13311         Diag(it.first, it.second);
13312     } else if (IsGlobal &&
13313                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13314                                            var->getLocation())) {
13315       // Warn about globals which don't have a constant initializer.  Don't
13316       // warn about globals with a non-trivial destructor because we already
13317       // warned about them.
13318       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13319       if (!(RD && !RD->hasTrivialDestructor())) {
13320         // checkConstInit() here permits trivial default initialization even in
13321         // C++11 onwards, where such an initializer is not a constant initializer
13322         // but nonetheless doesn't require a global constructor.
13323         if (!checkConstInit())
13324           Diag(var->getLocation(), diag::warn_global_constructor)
13325               << Init->getSourceRange();
13326       }
13327     }
13328   }
13329 
13330   // Apply section attributes and pragmas to global variables.
13331   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13332       !inTemplateInstantiation()) {
13333     PragmaStack<StringLiteral *> *Stack = nullptr;
13334     int SectionFlags = ASTContext::PSF_Read;
13335     if (var->getType().isConstQualified()) {
13336       if (HasConstInit)
13337         Stack = &ConstSegStack;
13338       else {
13339         Stack = &BSSSegStack;
13340         SectionFlags |= ASTContext::PSF_Write;
13341       }
13342     } else if (var->hasInit() && HasConstInit) {
13343       Stack = &DataSegStack;
13344       SectionFlags |= ASTContext::PSF_Write;
13345     } else {
13346       Stack = &BSSSegStack;
13347       SectionFlags |= ASTContext::PSF_Write;
13348     }
13349     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13350       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13351         SectionFlags |= ASTContext::PSF_Implicit;
13352       UnifySection(SA->getName(), SectionFlags, var);
13353     } else if (Stack->CurrentValue) {
13354       SectionFlags |= ASTContext::PSF_Implicit;
13355       auto SectionName = Stack->CurrentValue->getString();
13356       var->addAttr(SectionAttr::CreateImplicit(
13357           Context, SectionName, Stack->CurrentPragmaLocation,
13358           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13359       if (UnifySection(SectionName, SectionFlags, var))
13360         var->dropAttr<SectionAttr>();
13361     }
13362 
13363     // Apply the init_seg attribute if this has an initializer.  If the
13364     // initializer turns out to not be dynamic, we'll end up ignoring this
13365     // attribute.
13366     if (CurInitSeg && var->getInit())
13367       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13368                                                CurInitSegLoc,
13369                                                AttributeCommonInfo::AS_Pragma));
13370   }
13371 
13372   // All the following checks are C++ only.
13373   if (!getLangOpts().CPlusPlus) {
13374     // If this variable must be emitted, add it as an initializer for the
13375     // current module.
13376     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13377       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13378     return;
13379   }
13380 
13381   // Require the destructor.
13382   if (!type->isDependentType())
13383     if (const RecordType *recordType = baseType->getAs<RecordType>())
13384       FinalizeVarWithDestructor(var, recordType);
13385 
13386   // If this variable must be emitted, add it as an initializer for the current
13387   // module.
13388   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13389     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13390 
13391   // Build the bindings if this is a structured binding declaration.
13392   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13393     CheckCompleteDecompositionDeclaration(DD);
13394 }
13395 
13396 /// Check if VD needs to be dllexport/dllimport due to being in a
13397 /// dllexport/import function.
13398 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13399   assert(VD->isStaticLocal());
13400 
13401   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13402 
13403   // Find outermost function when VD is in lambda function.
13404   while (FD && !getDLLAttr(FD) &&
13405          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13406          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13407     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13408   }
13409 
13410   if (!FD)
13411     return;
13412 
13413   // Static locals inherit dll attributes from their function.
13414   if (Attr *A = getDLLAttr(FD)) {
13415     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13416     NewAttr->setInherited(true);
13417     VD->addAttr(NewAttr);
13418   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13419     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13420     NewAttr->setInherited(true);
13421     VD->addAttr(NewAttr);
13422 
13423     // Export this function to enforce exporting this static variable even
13424     // if it is not used in this compilation unit.
13425     if (!FD->hasAttr<DLLExportAttr>())
13426       FD->addAttr(NewAttr);
13427 
13428   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13429     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13430     NewAttr->setInherited(true);
13431     VD->addAttr(NewAttr);
13432   }
13433 }
13434 
13435 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13436 /// any semantic actions necessary after any initializer has been attached.
13437 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13438   // Note that we are no longer parsing the initializer for this declaration.
13439   ParsingInitForAutoVars.erase(ThisDecl);
13440 
13441   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13442   if (!VD)
13443     return;
13444 
13445   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13446   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13447       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13448     if (PragmaClangBSSSection.Valid)
13449       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13450           Context, PragmaClangBSSSection.SectionName,
13451           PragmaClangBSSSection.PragmaLocation,
13452           AttributeCommonInfo::AS_Pragma));
13453     if (PragmaClangDataSection.Valid)
13454       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13455           Context, PragmaClangDataSection.SectionName,
13456           PragmaClangDataSection.PragmaLocation,
13457           AttributeCommonInfo::AS_Pragma));
13458     if (PragmaClangRodataSection.Valid)
13459       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13460           Context, PragmaClangRodataSection.SectionName,
13461           PragmaClangRodataSection.PragmaLocation,
13462           AttributeCommonInfo::AS_Pragma));
13463     if (PragmaClangRelroSection.Valid)
13464       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13465           Context, PragmaClangRelroSection.SectionName,
13466           PragmaClangRelroSection.PragmaLocation,
13467           AttributeCommonInfo::AS_Pragma));
13468   }
13469 
13470   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13471     for (auto *BD : DD->bindings()) {
13472       FinalizeDeclaration(BD);
13473     }
13474   }
13475 
13476   checkAttributesAfterMerging(*this, *VD);
13477 
13478   // Perform TLS alignment check here after attributes attached to the variable
13479   // which may affect the alignment have been processed. Only perform the check
13480   // if the target has a maximum TLS alignment (zero means no constraints).
13481   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13482     // Protect the check so that it's not performed on dependent types and
13483     // dependent alignments (we can't determine the alignment in that case).
13484     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13485       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13486       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13487         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13488           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13489           << (unsigned)MaxAlignChars.getQuantity();
13490       }
13491     }
13492   }
13493 
13494   if (VD->isStaticLocal())
13495     CheckStaticLocalForDllExport(VD);
13496 
13497   // Perform check for initializers of device-side global variables.
13498   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13499   // 7.5). We must also apply the same checks to all __shared__
13500   // variables whether they are local or not. CUDA also allows
13501   // constant initializers for __constant__ and __device__ variables.
13502   if (getLangOpts().CUDA)
13503     checkAllowedCUDAInitializer(VD);
13504 
13505   // Grab the dllimport or dllexport attribute off of the VarDecl.
13506   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13507 
13508   // Imported static data members cannot be defined out-of-line.
13509   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13510     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13511         VD->isThisDeclarationADefinition()) {
13512       // We allow definitions of dllimport class template static data members
13513       // with a warning.
13514       CXXRecordDecl *Context =
13515         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13516       bool IsClassTemplateMember =
13517           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13518           Context->getDescribedClassTemplate();
13519 
13520       Diag(VD->getLocation(),
13521            IsClassTemplateMember
13522                ? diag::warn_attribute_dllimport_static_field_definition
13523                : diag::err_attribute_dllimport_static_field_definition);
13524       Diag(IA->getLocation(), diag::note_attribute);
13525       if (!IsClassTemplateMember)
13526         VD->setInvalidDecl();
13527     }
13528   }
13529 
13530   // dllimport/dllexport variables cannot be thread local, their TLS index
13531   // isn't exported with the variable.
13532   if (DLLAttr && VD->getTLSKind()) {
13533     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13534     if (F && getDLLAttr(F)) {
13535       assert(VD->isStaticLocal());
13536       // But if this is a static local in a dlimport/dllexport function, the
13537       // function will never be inlined, which means the var would never be
13538       // imported, so having it marked import/export is safe.
13539     } else {
13540       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13541                                                                     << DLLAttr;
13542       VD->setInvalidDecl();
13543     }
13544   }
13545 
13546   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13547     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13548       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13549           << Attr;
13550       VD->dropAttr<UsedAttr>();
13551     }
13552   }
13553   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13554     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13555       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13556           << Attr;
13557       VD->dropAttr<RetainAttr>();
13558     }
13559   }
13560 
13561   const DeclContext *DC = VD->getDeclContext();
13562   // If there's a #pragma GCC visibility in scope, and this isn't a class
13563   // member, set the visibility of this variable.
13564   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13565     AddPushedVisibilityAttribute(VD);
13566 
13567   // FIXME: Warn on unused var template partial specializations.
13568   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13569     MarkUnusedFileScopedDecl(VD);
13570 
13571   // Now we have parsed the initializer and can update the table of magic
13572   // tag values.
13573   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13574       !VD->getType()->isIntegralOrEnumerationType())
13575     return;
13576 
13577   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13578     const Expr *MagicValueExpr = VD->getInit();
13579     if (!MagicValueExpr) {
13580       continue;
13581     }
13582     Optional<llvm::APSInt> MagicValueInt;
13583     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13584       Diag(I->getRange().getBegin(),
13585            diag::err_type_tag_for_datatype_not_ice)
13586         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13587       continue;
13588     }
13589     if (MagicValueInt->getActiveBits() > 64) {
13590       Diag(I->getRange().getBegin(),
13591            diag::err_type_tag_for_datatype_too_large)
13592         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13593       continue;
13594     }
13595     uint64_t MagicValue = MagicValueInt->getZExtValue();
13596     RegisterTypeTagForDatatype(I->getArgumentKind(),
13597                                MagicValue,
13598                                I->getMatchingCType(),
13599                                I->getLayoutCompatible(),
13600                                I->getMustBeNull());
13601   }
13602 }
13603 
13604 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13605   auto *VD = dyn_cast<VarDecl>(DD);
13606   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13607 }
13608 
13609 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13610                                                    ArrayRef<Decl *> Group) {
13611   SmallVector<Decl*, 8> Decls;
13612 
13613   if (DS.isTypeSpecOwned())
13614     Decls.push_back(DS.getRepAsDecl());
13615 
13616   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13617   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13618   bool DiagnosedMultipleDecomps = false;
13619   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13620   bool DiagnosedNonDeducedAuto = false;
13621 
13622   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13623     if (Decl *D = Group[i]) {
13624       // For declarators, there are some additional syntactic-ish checks we need
13625       // to perform.
13626       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13627         if (!FirstDeclaratorInGroup)
13628           FirstDeclaratorInGroup = DD;
13629         if (!FirstDecompDeclaratorInGroup)
13630           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13631         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13632             !hasDeducedAuto(DD))
13633           FirstNonDeducedAutoInGroup = DD;
13634 
13635         if (FirstDeclaratorInGroup != DD) {
13636           // A decomposition declaration cannot be combined with any other
13637           // declaration in the same group.
13638           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13639             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13640                  diag::err_decomp_decl_not_alone)
13641                 << FirstDeclaratorInGroup->getSourceRange()
13642                 << DD->getSourceRange();
13643             DiagnosedMultipleDecomps = true;
13644           }
13645 
13646           // A declarator that uses 'auto' in any way other than to declare a
13647           // variable with a deduced type cannot be combined with any other
13648           // declarator in the same group.
13649           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13650             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13651                  diag::err_auto_non_deduced_not_alone)
13652                 << FirstNonDeducedAutoInGroup->getType()
13653                        ->hasAutoForTrailingReturnType()
13654                 << FirstDeclaratorInGroup->getSourceRange()
13655                 << DD->getSourceRange();
13656             DiagnosedNonDeducedAuto = true;
13657           }
13658         }
13659       }
13660 
13661       Decls.push_back(D);
13662     }
13663   }
13664 
13665   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13666     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13667       handleTagNumbering(Tag, S);
13668       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13669           getLangOpts().CPlusPlus)
13670         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13671     }
13672   }
13673 
13674   return BuildDeclaratorGroup(Decls);
13675 }
13676 
13677 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13678 /// group, performing any necessary semantic checking.
13679 Sema::DeclGroupPtrTy
13680 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13681   // C++14 [dcl.spec.auto]p7: (DR1347)
13682   //   If the type that replaces the placeholder type is not the same in each
13683   //   deduction, the program is ill-formed.
13684   if (Group.size() > 1) {
13685     QualType Deduced;
13686     VarDecl *DeducedDecl = nullptr;
13687     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13688       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13689       if (!D || D->isInvalidDecl())
13690         break;
13691       DeducedType *DT = D->getType()->getContainedDeducedType();
13692       if (!DT || DT->getDeducedType().isNull())
13693         continue;
13694       if (Deduced.isNull()) {
13695         Deduced = DT->getDeducedType();
13696         DeducedDecl = D;
13697       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13698         auto *AT = dyn_cast<AutoType>(DT);
13699         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13700                         diag::err_auto_different_deductions)
13701                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13702                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13703                    << D->getDeclName();
13704         if (DeducedDecl->hasInit())
13705           Dia << DeducedDecl->getInit()->getSourceRange();
13706         if (D->getInit())
13707           Dia << D->getInit()->getSourceRange();
13708         D->setInvalidDecl();
13709         break;
13710       }
13711     }
13712   }
13713 
13714   ActOnDocumentableDecls(Group);
13715 
13716   return DeclGroupPtrTy::make(
13717       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13718 }
13719 
13720 void Sema::ActOnDocumentableDecl(Decl *D) {
13721   ActOnDocumentableDecls(D);
13722 }
13723 
13724 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13725   // Don't parse the comment if Doxygen diagnostics are ignored.
13726   if (Group.empty() || !Group[0])
13727     return;
13728 
13729   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13730                       Group[0]->getLocation()) &&
13731       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13732                       Group[0]->getLocation()))
13733     return;
13734 
13735   if (Group.size() >= 2) {
13736     // This is a decl group.  Normally it will contain only declarations
13737     // produced from declarator list.  But in case we have any definitions or
13738     // additional declaration references:
13739     //   'typedef struct S {} S;'
13740     //   'typedef struct S *S;'
13741     //   'struct S *pS;'
13742     // FinalizeDeclaratorGroup adds these as separate declarations.
13743     Decl *MaybeTagDecl = Group[0];
13744     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13745       Group = Group.slice(1);
13746     }
13747   }
13748 
13749   // FIMXE: We assume every Decl in the group is in the same file.
13750   // This is false when preprocessor constructs the group from decls in
13751   // different files (e. g. macros or #include).
13752   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13753 }
13754 
13755 /// Common checks for a parameter-declaration that should apply to both function
13756 /// parameters and non-type template parameters.
13757 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13758   // Check that there are no default arguments inside the type of this
13759   // parameter.
13760   if (getLangOpts().CPlusPlus)
13761     CheckExtraCXXDefaultArguments(D);
13762 
13763   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13764   if (D.getCXXScopeSpec().isSet()) {
13765     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13766       << D.getCXXScopeSpec().getRange();
13767   }
13768 
13769   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13770   // simple identifier except [...irrelevant cases...].
13771   switch (D.getName().getKind()) {
13772   case UnqualifiedIdKind::IK_Identifier:
13773     break;
13774 
13775   case UnqualifiedIdKind::IK_OperatorFunctionId:
13776   case UnqualifiedIdKind::IK_ConversionFunctionId:
13777   case UnqualifiedIdKind::IK_LiteralOperatorId:
13778   case UnqualifiedIdKind::IK_ConstructorName:
13779   case UnqualifiedIdKind::IK_DestructorName:
13780   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13781   case UnqualifiedIdKind::IK_DeductionGuideName:
13782     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13783       << GetNameForDeclarator(D).getName();
13784     break;
13785 
13786   case UnqualifiedIdKind::IK_TemplateId:
13787   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13788     // GetNameForDeclarator would not produce a useful name in this case.
13789     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13790     break;
13791   }
13792 }
13793 
13794 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13795 /// to introduce parameters into function prototype scope.
13796 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13797   const DeclSpec &DS = D.getDeclSpec();
13798 
13799   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13800 
13801   // C++03 [dcl.stc]p2 also permits 'auto'.
13802   StorageClass SC = SC_None;
13803   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13804     SC = SC_Register;
13805     // In C++11, the 'register' storage class specifier is deprecated.
13806     // In C++17, it is not allowed, but we tolerate it as an extension.
13807     if (getLangOpts().CPlusPlus11) {
13808       Diag(DS.getStorageClassSpecLoc(),
13809            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13810                                      : diag::warn_deprecated_register)
13811         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13812     }
13813   } else if (getLangOpts().CPlusPlus &&
13814              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13815     SC = SC_Auto;
13816   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13817     Diag(DS.getStorageClassSpecLoc(),
13818          diag::err_invalid_storage_class_in_func_decl);
13819     D.getMutableDeclSpec().ClearStorageClassSpecs();
13820   }
13821 
13822   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13823     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13824       << DeclSpec::getSpecifierName(TSCS);
13825   if (DS.isInlineSpecified())
13826     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13827         << getLangOpts().CPlusPlus17;
13828   if (DS.hasConstexprSpecifier())
13829     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13830         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13831 
13832   DiagnoseFunctionSpecifiers(DS);
13833 
13834   CheckFunctionOrTemplateParamDeclarator(S, D);
13835 
13836   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13837   QualType parmDeclType = TInfo->getType();
13838 
13839   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13840   IdentifierInfo *II = D.getIdentifier();
13841   if (II) {
13842     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13843                    ForVisibleRedeclaration);
13844     LookupName(R, S);
13845     if (R.isSingleResult()) {
13846       NamedDecl *PrevDecl = R.getFoundDecl();
13847       if (PrevDecl->isTemplateParameter()) {
13848         // Maybe we will complain about the shadowed template parameter.
13849         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13850         // Just pretend that we didn't see the previous declaration.
13851         PrevDecl = nullptr;
13852       } else if (S->isDeclScope(PrevDecl)) {
13853         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13854         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13855 
13856         // Recover by removing the name
13857         II = nullptr;
13858         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13859         D.setInvalidType(true);
13860       }
13861     }
13862   }
13863 
13864   // Temporarily put parameter variables in the translation unit, not
13865   // the enclosing context.  This prevents them from accidentally
13866   // looking like class members in C++.
13867   ParmVarDecl *New =
13868       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13869                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13870 
13871   if (D.isInvalidType())
13872     New->setInvalidDecl();
13873 
13874   assert(S->isFunctionPrototypeScope());
13875   assert(S->getFunctionPrototypeDepth() >= 1);
13876   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13877                     S->getNextFunctionPrototypeIndex());
13878 
13879   // Add the parameter declaration into this scope.
13880   S->AddDecl(New);
13881   if (II)
13882     IdResolver.AddDecl(New);
13883 
13884   ProcessDeclAttributes(S, New, D);
13885 
13886   if (D.getDeclSpec().isModulePrivateSpecified())
13887     Diag(New->getLocation(), diag::err_module_private_local)
13888         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13889         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13890 
13891   if (New->hasAttr<BlocksAttr>()) {
13892     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13893   }
13894 
13895   if (getLangOpts().OpenCL)
13896     deduceOpenCLAddressSpace(New);
13897 
13898   return New;
13899 }
13900 
13901 /// Synthesizes a variable for a parameter arising from a
13902 /// typedef.
13903 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13904                                               SourceLocation Loc,
13905                                               QualType T) {
13906   /* FIXME: setting StartLoc == Loc.
13907      Would it be worth to modify callers so as to provide proper source
13908      location for the unnamed parameters, embedding the parameter's type? */
13909   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13910                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13911                                            SC_None, nullptr);
13912   Param->setImplicit();
13913   return Param;
13914 }
13915 
13916 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13917   // Don't diagnose unused-parameter errors in template instantiations; we
13918   // will already have done so in the template itself.
13919   if (inTemplateInstantiation())
13920     return;
13921 
13922   for (const ParmVarDecl *Parameter : Parameters) {
13923     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13924         !Parameter->hasAttr<UnusedAttr>()) {
13925       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13926         << Parameter->getDeclName();
13927     }
13928   }
13929 }
13930 
13931 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13932     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13933   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13934     return;
13935 
13936   // Warn if the return value is pass-by-value and larger than the specified
13937   // threshold.
13938   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13939     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13940     if (Size > LangOpts.NumLargeByValueCopy)
13941       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13942   }
13943 
13944   // Warn if any parameter is pass-by-value and larger than the specified
13945   // threshold.
13946   for (const ParmVarDecl *Parameter : Parameters) {
13947     QualType T = Parameter->getType();
13948     if (T->isDependentType() || !T.isPODType(Context))
13949       continue;
13950     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13951     if (Size > LangOpts.NumLargeByValueCopy)
13952       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13953           << Parameter << Size;
13954   }
13955 }
13956 
13957 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13958                                   SourceLocation NameLoc, IdentifierInfo *Name,
13959                                   QualType T, TypeSourceInfo *TSInfo,
13960                                   StorageClass SC) {
13961   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13962   if (getLangOpts().ObjCAutoRefCount &&
13963       T.getObjCLifetime() == Qualifiers::OCL_None &&
13964       T->isObjCLifetimeType()) {
13965 
13966     Qualifiers::ObjCLifetime lifetime;
13967 
13968     // Special cases for arrays:
13969     //   - if it's const, use __unsafe_unretained
13970     //   - otherwise, it's an error
13971     if (T->isArrayType()) {
13972       if (!T.isConstQualified()) {
13973         if (DelayedDiagnostics.shouldDelayDiagnostics())
13974           DelayedDiagnostics.add(
13975               sema::DelayedDiagnostic::makeForbiddenType(
13976               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13977         else
13978           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13979               << TSInfo->getTypeLoc().getSourceRange();
13980       }
13981       lifetime = Qualifiers::OCL_ExplicitNone;
13982     } else {
13983       lifetime = T->getObjCARCImplicitLifetime();
13984     }
13985     T = Context.getLifetimeQualifiedType(T, lifetime);
13986   }
13987 
13988   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13989                                          Context.getAdjustedParameterType(T),
13990                                          TSInfo, SC, nullptr);
13991 
13992   // Make a note if we created a new pack in the scope of a lambda, so that
13993   // we know that references to that pack must also be expanded within the
13994   // lambda scope.
13995   if (New->isParameterPack())
13996     if (auto *LSI = getEnclosingLambda())
13997       LSI->LocalPacks.push_back(New);
13998 
13999   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14000       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14001     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14002                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14003 
14004   // Parameters can not be abstract class types.
14005   // For record types, this is done by the AbstractClassUsageDiagnoser once
14006   // the class has been completely parsed.
14007   if (!CurContext->isRecord() &&
14008       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14009                              AbstractParamType))
14010     New->setInvalidDecl();
14011 
14012   // Parameter declarators cannot be interface types. All ObjC objects are
14013   // passed by reference.
14014   if (T->isObjCObjectType()) {
14015     SourceLocation TypeEndLoc =
14016         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14017     Diag(NameLoc,
14018          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14019       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14020     T = Context.getObjCObjectPointerType(T);
14021     New->setType(T);
14022   }
14023 
14024   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14025   // duration shall not be qualified by an address-space qualifier."
14026   // Since all parameters have automatic store duration, they can not have
14027   // an address space.
14028   if (T.getAddressSpace() != LangAS::Default &&
14029       // OpenCL allows function arguments declared to be an array of a type
14030       // to be qualified with an address space.
14031       !(getLangOpts().OpenCL &&
14032         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14033     Diag(NameLoc, diag::err_arg_with_address_space);
14034     New->setInvalidDecl();
14035   }
14036 
14037   // PPC MMA non-pointer types are not allowed as function argument types.
14038   if (Context.getTargetInfo().getTriple().isPPC64() &&
14039       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14040     New->setInvalidDecl();
14041   }
14042 
14043   return New;
14044 }
14045 
14046 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14047                                            SourceLocation LocAfterDecls) {
14048   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14049 
14050   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14051   // for a K&R function.
14052   if (!FTI.hasPrototype) {
14053     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14054       --i;
14055       if (FTI.Params[i].Param == nullptr) {
14056         SmallString<256> Code;
14057         llvm::raw_svector_ostream(Code)
14058             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14059         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14060             << FTI.Params[i].Ident
14061             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14062 
14063         // Implicitly declare the argument as type 'int' for lack of a better
14064         // type.
14065         AttributeFactory attrs;
14066         DeclSpec DS(attrs);
14067         const char* PrevSpec; // unused
14068         unsigned DiagID; // unused
14069         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14070                            DiagID, Context.getPrintingPolicy());
14071         // Use the identifier location for the type source range.
14072         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14073         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14074         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14075         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14076         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14077       }
14078     }
14079   }
14080 }
14081 
14082 Decl *
14083 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14084                               MultiTemplateParamsArg TemplateParameterLists,
14085                               SkipBodyInfo *SkipBody) {
14086   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14087   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14088   Scope *ParentScope = FnBodyScope->getParent();
14089 
14090   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14091   // we define a non-templated function definition, we will create a declaration
14092   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14093   // The base function declaration will have the equivalent of an `omp declare
14094   // variant` annotation which specifies the mangled definition as a
14095   // specialization function under the OpenMP context defined as part of the
14096   // `omp begin declare variant`.
14097   SmallVector<FunctionDecl *, 4> Bases;
14098   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14099     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14100         ParentScope, D, TemplateParameterLists, Bases);
14101 
14102   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14103   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14104   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14105 
14106   if (!Bases.empty())
14107     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14108 
14109   return Dcl;
14110 }
14111 
14112 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14113   Consumer.HandleInlineFunctionDefinition(D);
14114 }
14115 
14116 static bool
14117 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14118                                 const FunctionDecl *&PossiblePrototype) {
14119   // Don't warn about invalid declarations.
14120   if (FD->isInvalidDecl())
14121     return false;
14122 
14123   // Or declarations that aren't global.
14124   if (!FD->isGlobal())
14125     return false;
14126 
14127   // Don't warn about C++ member functions.
14128   if (isa<CXXMethodDecl>(FD))
14129     return false;
14130 
14131   // Don't warn about 'main'.
14132   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14133     if (IdentifierInfo *II = FD->getIdentifier())
14134       if (II->isStr("main") || II->isStr("efi_main"))
14135         return false;
14136 
14137   // Don't warn about inline functions.
14138   if (FD->isInlined())
14139     return false;
14140 
14141   // Don't warn about function templates.
14142   if (FD->getDescribedFunctionTemplate())
14143     return false;
14144 
14145   // Don't warn about function template specializations.
14146   if (FD->isFunctionTemplateSpecialization())
14147     return false;
14148 
14149   // Don't warn for OpenCL kernels.
14150   if (FD->hasAttr<OpenCLKernelAttr>())
14151     return false;
14152 
14153   // Don't warn on explicitly deleted functions.
14154   if (FD->isDeleted())
14155     return false;
14156 
14157   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14158        Prev; Prev = Prev->getPreviousDecl()) {
14159     // Ignore any declarations that occur in function or method
14160     // scope, because they aren't visible from the header.
14161     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14162       continue;
14163 
14164     PossiblePrototype = Prev;
14165     return Prev->getType()->isFunctionNoProtoType();
14166   }
14167 
14168   return true;
14169 }
14170 
14171 void
14172 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14173                                    const FunctionDecl *EffectiveDefinition,
14174                                    SkipBodyInfo *SkipBody) {
14175   const FunctionDecl *Definition = EffectiveDefinition;
14176   if (!Definition &&
14177       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14178     return;
14179 
14180   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14181     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14182       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14183         // A merged copy of the same function, instantiated as a member of
14184         // the same class, is OK.
14185         if (declaresSameEntity(OrigFD, OrigDef) &&
14186             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14187                                cast<Decl>(FD->getLexicalDeclContext())))
14188           return;
14189       }
14190     }
14191   }
14192 
14193   if (canRedefineFunction(Definition, getLangOpts()))
14194     return;
14195 
14196   // Don't emit an error when this is redefinition of a typo-corrected
14197   // definition.
14198   if (TypoCorrectedFunctionDefinitions.count(Definition))
14199     return;
14200 
14201   // If we don't have a visible definition of the function, and it's inline or
14202   // a template, skip the new definition.
14203   if (SkipBody && !hasVisibleDefinition(Definition) &&
14204       (Definition->getFormalLinkage() == InternalLinkage ||
14205        Definition->isInlined() ||
14206        Definition->getDescribedFunctionTemplate() ||
14207        Definition->getNumTemplateParameterLists())) {
14208     SkipBody->ShouldSkip = true;
14209     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14210     if (auto *TD = Definition->getDescribedFunctionTemplate())
14211       makeMergedDefinitionVisible(TD);
14212     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14213     return;
14214   }
14215 
14216   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14217       Definition->getStorageClass() == SC_Extern)
14218     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14219         << FD << getLangOpts().CPlusPlus;
14220   else
14221     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14222 
14223   Diag(Definition->getLocation(), diag::note_previous_definition);
14224   FD->setInvalidDecl();
14225 }
14226 
14227 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14228                                    Sema &S) {
14229   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14230 
14231   LambdaScopeInfo *LSI = S.PushLambdaScope();
14232   LSI->CallOperator = CallOperator;
14233   LSI->Lambda = LambdaClass;
14234   LSI->ReturnType = CallOperator->getReturnType();
14235   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14236 
14237   if (LCD == LCD_None)
14238     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14239   else if (LCD == LCD_ByCopy)
14240     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14241   else if (LCD == LCD_ByRef)
14242     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14243   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14244 
14245   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14246   LSI->Mutable = !CallOperator->isConst();
14247 
14248   // Add the captures to the LSI so they can be noted as already
14249   // captured within tryCaptureVar.
14250   auto I = LambdaClass->field_begin();
14251   for (const auto &C : LambdaClass->captures()) {
14252     if (C.capturesVariable()) {
14253       VarDecl *VD = C.getCapturedVar();
14254       if (VD->isInitCapture())
14255         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14256       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14257       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14258           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14259           /*EllipsisLoc*/C.isPackExpansion()
14260                          ? C.getEllipsisLoc() : SourceLocation(),
14261           I->getType(), /*Invalid*/false);
14262 
14263     } else if (C.capturesThis()) {
14264       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14265                           C.getCaptureKind() == LCK_StarThis);
14266     } else {
14267       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14268                              I->getType());
14269     }
14270     ++I;
14271   }
14272 }
14273 
14274 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14275                                     SkipBodyInfo *SkipBody) {
14276   if (!D) {
14277     // Parsing the function declaration failed in some way. Push on a fake scope
14278     // anyway so we can try to parse the function body.
14279     PushFunctionScope();
14280     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14281     return D;
14282   }
14283 
14284   FunctionDecl *FD = nullptr;
14285 
14286   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14287     FD = FunTmpl->getTemplatedDecl();
14288   else
14289     FD = cast<FunctionDecl>(D);
14290 
14291   // Do not push if it is a lambda because one is already pushed when building
14292   // the lambda in ActOnStartOfLambdaDefinition().
14293   if (!isLambdaCallOperator(FD))
14294     PushExpressionEvaluationContext(
14295         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14296                           : ExprEvalContexts.back().Context);
14297 
14298   // Check for defining attributes before the check for redefinition.
14299   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14300     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14301     FD->dropAttr<AliasAttr>();
14302     FD->setInvalidDecl();
14303   }
14304   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14305     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14306     FD->dropAttr<IFuncAttr>();
14307     FD->setInvalidDecl();
14308   }
14309 
14310   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14311     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14312         Ctor->isDefaultConstructor() &&
14313         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14314       // If this is an MS ABI dllexport default constructor, instantiate any
14315       // default arguments.
14316       InstantiateDefaultCtorDefaultArgs(Ctor);
14317     }
14318   }
14319 
14320   // See if this is a redefinition. If 'will have body' (or similar) is already
14321   // set, then these checks were already performed when it was set.
14322   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14323       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14324     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14325 
14326     // If we're skipping the body, we're done. Don't enter the scope.
14327     if (SkipBody && SkipBody->ShouldSkip)
14328       return D;
14329   }
14330 
14331   // Mark this function as "will have a body eventually".  This lets users to
14332   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14333   // this function.
14334   FD->setWillHaveBody();
14335 
14336   // If we are instantiating a generic lambda call operator, push
14337   // a LambdaScopeInfo onto the function stack.  But use the information
14338   // that's already been calculated (ActOnLambdaExpr) to prime the current
14339   // LambdaScopeInfo.
14340   // When the template operator is being specialized, the LambdaScopeInfo,
14341   // has to be properly restored so that tryCaptureVariable doesn't try
14342   // and capture any new variables. In addition when calculating potential
14343   // captures during transformation of nested lambdas, it is necessary to
14344   // have the LSI properly restored.
14345   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14346     assert(inTemplateInstantiation() &&
14347            "There should be an active template instantiation on the stack "
14348            "when instantiating a generic lambda!");
14349     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14350   } else {
14351     // Enter a new function scope
14352     PushFunctionScope();
14353   }
14354 
14355   // Builtin functions cannot be defined.
14356   if (unsigned BuiltinID = FD->getBuiltinID()) {
14357     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14358         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14359       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14360       FD->setInvalidDecl();
14361     }
14362   }
14363 
14364   // The return type of a function definition must be complete
14365   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14366   QualType ResultType = FD->getReturnType();
14367   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14368       !FD->isInvalidDecl() &&
14369       RequireCompleteType(FD->getLocation(), ResultType,
14370                           diag::err_func_def_incomplete_result))
14371     FD->setInvalidDecl();
14372 
14373   if (FnBodyScope)
14374     PushDeclContext(FnBodyScope, FD);
14375 
14376   // Check the validity of our function parameters
14377   CheckParmsForFunctionDef(FD->parameters(),
14378                            /*CheckParameterNames=*/true);
14379 
14380   // Add non-parameter declarations already in the function to the current
14381   // scope.
14382   if (FnBodyScope) {
14383     for (Decl *NPD : FD->decls()) {
14384       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14385       if (!NonParmDecl)
14386         continue;
14387       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14388              "parameters should not be in newly created FD yet");
14389 
14390       // If the decl has a name, make it accessible in the current scope.
14391       if (NonParmDecl->getDeclName())
14392         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14393 
14394       // Similarly, dive into enums and fish their constants out, making them
14395       // accessible in this scope.
14396       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14397         for (auto *EI : ED->enumerators())
14398           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14399       }
14400     }
14401   }
14402 
14403   // Introduce our parameters into the function scope
14404   for (auto Param : FD->parameters()) {
14405     Param->setOwningFunction(FD);
14406 
14407     // If this has an identifier, add it to the scope stack.
14408     if (Param->getIdentifier() && FnBodyScope) {
14409       CheckShadow(FnBodyScope, Param);
14410 
14411       PushOnScopeChains(Param, FnBodyScope);
14412     }
14413   }
14414 
14415   // Ensure that the function's exception specification is instantiated.
14416   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14417     ResolveExceptionSpec(D->getLocation(), FPT);
14418 
14419   // dllimport cannot be applied to non-inline function definitions.
14420   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14421       !FD->isTemplateInstantiation()) {
14422     assert(!FD->hasAttr<DLLExportAttr>());
14423     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14424     FD->setInvalidDecl();
14425     return D;
14426   }
14427   // We want to attach documentation to original Decl (which might be
14428   // a function template).
14429   ActOnDocumentableDecl(D);
14430   if (getCurLexicalContext()->isObjCContainer() &&
14431       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14432       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14433     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14434 
14435   return D;
14436 }
14437 
14438 /// Given the set of return statements within a function body,
14439 /// compute the variables that are subject to the named return value
14440 /// optimization.
14441 ///
14442 /// Each of the variables that is subject to the named return value
14443 /// optimization will be marked as NRVO variables in the AST, and any
14444 /// return statement that has a marked NRVO variable as its NRVO candidate can
14445 /// use the named return value optimization.
14446 ///
14447 /// This function applies a very simplistic algorithm for NRVO: if every return
14448 /// statement in the scope of a variable has the same NRVO candidate, that
14449 /// candidate is an NRVO variable.
14450 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14451   ReturnStmt **Returns = Scope->Returns.data();
14452 
14453   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14454     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14455       if (!NRVOCandidate->isNRVOVariable())
14456         Returns[I]->setNRVOCandidate(nullptr);
14457     }
14458   }
14459 }
14460 
14461 bool Sema::canDelayFunctionBody(const Declarator &D) {
14462   // We can't delay parsing the body of a constexpr function template (yet).
14463   if (D.getDeclSpec().hasConstexprSpecifier())
14464     return false;
14465 
14466   // We can't delay parsing the body of a function template with a deduced
14467   // return type (yet).
14468   if (D.getDeclSpec().hasAutoTypeSpec()) {
14469     // If the placeholder introduces a non-deduced trailing return type,
14470     // we can still delay parsing it.
14471     if (D.getNumTypeObjects()) {
14472       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14473       if (Outer.Kind == DeclaratorChunk::Function &&
14474           Outer.Fun.hasTrailingReturnType()) {
14475         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14476         return Ty.isNull() || !Ty->isUndeducedType();
14477       }
14478     }
14479     return false;
14480   }
14481 
14482   return true;
14483 }
14484 
14485 bool Sema::canSkipFunctionBody(Decl *D) {
14486   // We cannot skip the body of a function (or function template) which is
14487   // constexpr, since we may need to evaluate its body in order to parse the
14488   // rest of the file.
14489   // We cannot skip the body of a function with an undeduced return type,
14490   // because any callers of that function need to know the type.
14491   if (const FunctionDecl *FD = D->getAsFunction()) {
14492     if (FD->isConstexpr())
14493       return false;
14494     // We can't simply call Type::isUndeducedType here, because inside template
14495     // auto can be deduced to a dependent type, which is not considered
14496     // "undeduced".
14497     if (FD->getReturnType()->getContainedDeducedType())
14498       return false;
14499   }
14500   return Consumer.shouldSkipFunctionBody(D);
14501 }
14502 
14503 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14504   if (!Decl)
14505     return nullptr;
14506   if (FunctionDecl *FD = Decl->getAsFunction())
14507     FD->setHasSkippedBody();
14508   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14509     MD->setHasSkippedBody();
14510   return Decl;
14511 }
14512 
14513 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14514   return ActOnFinishFunctionBody(D, BodyArg, false);
14515 }
14516 
14517 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14518 /// body.
14519 class ExitFunctionBodyRAII {
14520 public:
14521   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14522   ~ExitFunctionBodyRAII() {
14523     if (!IsLambda)
14524       S.PopExpressionEvaluationContext();
14525   }
14526 
14527 private:
14528   Sema &S;
14529   bool IsLambda = false;
14530 };
14531 
14532 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14533   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14534 
14535   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14536     if (EscapeInfo.count(BD))
14537       return EscapeInfo[BD];
14538 
14539     bool R = false;
14540     const BlockDecl *CurBD = BD;
14541 
14542     do {
14543       R = !CurBD->doesNotEscape();
14544       if (R)
14545         break;
14546       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14547     } while (CurBD);
14548 
14549     return EscapeInfo[BD] = R;
14550   };
14551 
14552   // If the location where 'self' is implicitly retained is inside a escaping
14553   // block, emit a diagnostic.
14554   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14555        S.ImplicitlyRetainedSelfLocs)
14556     if (IsOrNestedInEscapingBlock(P.second))
14557       S.Diag(P.first, diag::warn_implicitly_retains_self)
14558           << FixItHint::CreateInsertion(P.first, "self->");
14559 }
14560 
14561 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14562                                     bool IsInstantiation) {
14563   FunctionScopeInfo *FSI = getCurFunction();
14564   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14565 
14566   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14567     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14568 
14569   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14570   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14571 
14572   if (getLangOpts().Coroutines && FSI->isCoroutine())
14573     CheckCompletedCoroutineBody(FD, Body);
14574 
14575   {
14576     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14577     // one is already popped when finishing the lambda in BuildLambdaExpr().
14578     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14579     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14580 
14581     if (FD) {
14582       FD->setBody(Body);
14583       FD->setWillHaveBody(false);
14584 
14585       if (getLangOpts().CPlusPlus14) {
14586         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14587             FD->getReturnType()->isUndeducedType()) {
14588           // If the function has a deduced result type but contains no 'return'
14589           // statements, the result type as written must be exactly 'auto', and
14590           // the deduced result type is 'void'.
14591           if (!FD->getReturnType()->getAs<AutoType>()) {
14592             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14593                 << FD->getReturnType();
14594             FD->setInvalidDecl();
14595           } else {
14596             // Substitute 'void' for the 'auto' in the type.
14597             TypeLoc ResultType = getReturnTypeLoc(FD);
14598             Context.adjustDeducedFunctionResultType(
14599                 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14600           }
14601         }
14602       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14603         // In C++11, we don't use 'auto' deduction rules for lambda call
14604         // operators because we don't support return type deduction.
14605         auto *LSI = getCurLambda();
14606         if (LSI->HasImplicitReturnType) {
14607           deduceClosureReturnType(*LSI);
14608 
14609           // C++11 [expr.prim.lambda]p4:
14610           //   [...] if there are no return statements in the compound-statement
14611           //   [the deduced type is] the type void
14612           QualType RetType =
14613               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14614 
14615           // Update the return type to the deduced type.
14616           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14617           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14618                                               Proto->getExtProtoInfo()));
14619         }
14620       }
14621 
14622       // If the function implicitly returns zero (like 'main') or is naked,
14623       // don't complain about missing return statements.
14624       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14625         WP.disableCheckFallThrough();
14626 
14627       // MSVC permits the use of pure specifier (=0) on function definition,
14628       // defined at class scope, warn about this non-standard construct.
14629       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14630         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14631 
14632       if (!FD->isInvalidDecl()) {
14633         // Don't diagnose unused parameters of defaulted or deleted functions.
14634         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14635           DiagnoseUnusedParameters(FD->parameters());
14636         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14637                                                FD->getReturnType(), FD);
14638 
14639         // If this is a structor, we need a vtable.
14640         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14641           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14642         else if (CXXDestructorDecl *Destructor =
14643                      dyn_cast<CXXDestructorDecl>(FD))
14644           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14645 
14646         // Try to apply the named return value optimization. We have to check
14647         // if we can do this here because lambdas keep return statements around
14648         // to deduce an implicit return type.
14649         if (FD->getReturnType()->isRecordType() &&
14650             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14651           computeNRVO(Body, FSI);
14652       }
14653 
14654       // GNU warning -Wmissing-prototypes:
14655       //   Warn if a global function is defined without a previous
14656       //   prototype declaration. This warning is issued even if the
14657       //   definition itself provides a prototype. The aim is to detect
14658       //   global functions that fail to be declared in header files.
14659       const FunctionDecl *PossiblePrototype = nullptr;
14660       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14661         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14662 
14663         if (PossiblePrototype) {
14664           // We found a declaration that is not a prototype,
14665           // but that could be a zero-parameter prototype
14666           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14667             TypeLoc TL = TI->getTypeLoc();
14668             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14669               Diag(PossiblePrototype->getLocation(),
14670                    diag::note_declaration_not_a_prototype)
14671                   << (FD->getNumParams() != 0)
14672                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14673                                                     FTL.getRParenLoc(), "void")
14674                                               : FixItHint{});
14675           }
14676         } else {
14677           // Returns true if the token beginning at this Loc is `const`.
14678           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14679                                   const LangOptions &LangOpts) {
14680             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14681             if (LocInfo.first.isInvalid())
14682               return false;
14683 
14684             bool Invalid = false;
14685             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14686             if (Invalid)
14687               return false;
14688 
14689             if (LocInfo.second > Buffer.size())
14690               return false;
14691 
14692             const char *LexStart = Buffer.data() + LocInfo.second;
14693             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14694 
14695             return StartTok.consume_front("const") &&
14696                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14697                     StartTok.startswith("/*") || StartTok.startswith("//"));
14698           };
14699 
14700           auto findBeginLoc = [&]() {
14701             // If the return type has `const` qualifier, we want to insert
14702             // `static` before `const` (and not before the typename).
14703             if ((FD->getReturnType()->isAnyPointerType() &&
14704                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14705                 FD->getReturnType().isConstQualified()) {
14706               // But only do this if we can determine where the `const` is.
14707 
14708               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14709                                getLangOpts()))
14710 
14711                 return FD->getBeginLoc();
14712             }
14713             return FD->getTypeSpecStartLoc();
14714           };
14715           Diag(FD->getTypeSpecStartLoc(),
14716                diag::note_static_for_internal_linkage)
14717               << /* function */ 1
14718               << (FD->getStorageClass() == SC_None
14719                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14720                       : FixItHint{});
14721         }
14722 
14723         // GNU warning -Wstrict-prototypes
14724         //   Warn if K&R function is defined without a previous declaration.
14725         //   This warning is issued only if the definition itself does not
14726         //   provide a prototype. Only K&R definitions do not provide a
14727         //   prototype.
14728         if (!FD->hasWrittenPrototype()) {
14729           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14730           TypeLoc TL = TI->getTypeLoc();
14731           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14732           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14733         }
14734       }
14735 
14736       // Warn on CPUDispatch with an actual body.
14737       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14738         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14739           if (!CmpndBody->body_empty())
14740             Diag(CmpndBody->body_front()->getBeginLoc(),
14741                  diag::warn_dispatch_body_ignored);
14742 
14743       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14744         const CXXMethodDecl *KeyFunction;
14745         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14746             MD->isVirtual() &&
14747             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14748             MD == KeyFunction->getCanonicalDecl()) {
14749           // Update the key-function state if necessary for this ABI.
14750           if (FD->isInlined() &&
14751               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14752             Context.setNonKeyFunction(MD);
14753 
14754             // If the newly-chosen key function is already defined, then we
14755             // need to mark the vtable as used retroactively.
14756             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14757             const FunctionDecl *Definition;
14758             if (KeyFunction && KeyFunction->isDefined(Definition))
14759               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14760           } else {
14761             // We just defined they key function; mark the vtable as used.
14762             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14763           }
14764         }
14765       }
14766 
14767       assert(
14768           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14769           "Function parsing confused");
14770     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14771       assert(MD == getCurMethodDecl() && "Method parsing confused");
14772       MD->setBody(Body);
14773       if (!MD->isInvalidDecl()) {
14774         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14775                                                MD->getReturnType(), MD);
14776 
14777         if (Body)
14778           computeNRVO(Body, FSI);
14779       }
14780       if (FSI->ObjCShouldCallSuper) {
14781         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14782             << MD->getSelector().getAsString();
14783         FSI->ObjCShouldCallSuper = false;
14784       }
14785       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14786         const ObjCMethodDecl *InitMethod = nullptr;
14787         bool isDesignated =
14788             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14789         assert(isDesignated && InitMethod);
14790         (void)isDesignated;
14791 
14792         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14793           auto IFace = MD->getClassInterface();
14794           if (!IFace)
14795             return false;
14796           auto SuperD = IFace->getSuperClass();
14797           if (!SuperD)
14798             return false;
14799           return SuperD->getIdentifier() ==
14800                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14801         };
14802         // Don't issue this warning for unavailable inits or direct subclasses
14803         // of NSObject.
14804         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14805           Diag(MD->getLocation(),
14806                diag::warn_objc_designated_init_missing_super_call);
14807           Diag(InitMethod->getLocation(),
14808                diag::note_objc_designated_init_marked_here);
14809         }
14810         FSI->ObjCWarnForNoDesignatedInitChain = false;
14811       }
14812       if (FSI->ObjCWarnForNoInitDelegation) {
14813         // Don't issue this warning for unavaialable inits.
14814         if (!MD->isUnavailable())
14815           Diag(MD->getLocation(),
14816                diag::warn_objc_secondary_init_missing_init_call);
14817         FSI->ObjCWarnForNoInitDelegation = false;
14818       }
14819 
14820       diagnoseImplicitlyRetainedSelf(*this);
14821     } else {
14822       // Parsing the function declaration failed in some way. Pop the fake scope
14823       // we pushed on.
14824       PopFunctionScopeInfo(ActivePolicy, dcl);
14825       return nullptr;
14826     }
14827 
14828     if (Body && FSI->HasPotentialAvailabilityViolations)
14829       DiagnoseUnguardedAvailabilityViolations(dcl);
14830 
14831     assert(!FSI->ObjCShouldCallSuper &&
14832            "This should only be set for ObjC methods, which should have been "
14833            "handled in the block above.");
14834 
14835     // Verify and clean out per-function state.
14836     if (Body && (!FD || !FD->isDefaulted())) {
14837       // C++ constructors that have function-try-blocks can't have return
14838       // statements in the handlers of that block. (C++ [except.handle]p14)
14839       // Verify this.
14840       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14841         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14842 
14843       // Verify that gotos and switch cases don't jump into scopes illegally.
14844       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14845         DiagnoseInvalidJumps(Body);
14846 
14847       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14848         if (!Destructor->getParent()->isDependentType())
14849           CheckDestructor(Destructor);
14850 
14851         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14852                                                Destructor->getParent());
14853       }
14854 
14855       // If any errors have occurred, clear out any temporaries that may have
14856       // been leftover. This ensures that these temporaries won't be picked up
14857       // for deletion in some later function.
14858       if (hasUncompilableErrorOccurred() ||
14859           getDiagnostics().getSuppressAllDiagnostics()) {
14860         DiscardCleanupsInEvaluationContext();
14861       }
14862       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14863         // Since the body is valid, issue any analysis-based warnings that are
14864         // enabled.
14865         ActivePolicy = &WP;
14866       }
14867 
14868       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14869           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14870         FD->setInvalidDecl();
14871 
14872       if (FD && FD->hasAttr<NakedAttr>()) {
14873         for (const Stmt *S : Body->children()) {
14874           // Allow local register variables without initializer as they don't
14875           // require prologue.
14876           bool RegisterVariables = false;
14877           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14878             for (const auto *Decl : DS->decls()) {
14879               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14880                 RegisterVariables =
14881                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14882                 if (!RegisterVariables)
14883                   break;
14884               }
14885             }
14886           }
14887           if (RegisterVariables)
14888             continue;
14889           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14890             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14891             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14892             FD->setInvalidDecl();
14893             break;
14894           }
14895         }
14896       }
14897 
14898       assert(ExprCleanupObjects.size() ==
14899                  ExprEvalContexts.back().NumCleanupObjects &&
14900              "Leftover temporaries in function");
14901       assert(!Cleanup.exprNeedsCleanups() &&
14902              "Unaccounted cleanups in function");
14903       assert(MaybeODRUseExprs.empty() &&
14904              "Leftover expressions for odr-use checking");
14905     }
14906   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
14907     // the declaration context below. Otherwise, we're unable to transform
14908     // 'this' expressions when transforming immediate context functions.
14909 
14910   if (!IsInstantiation)
14911     PopDeclContext();
14912 
14913   PopFunctionScopeInfo(ActivePolicy, dcl);
14914   // If any errors have occurred, clear out any temporaries that may have
14915   // been leftover. This ensures that these temporaries won't be picked up for
14916   // deletion in some later function.
14917   if (hasUncompilableErrorOccurred()) {
14918     DiscardCleanupsInEvaluationContext();
14919   }
14920 
14921   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
14922                                   !LangOpts.OMPTargetTriples.empty())) ||
14923              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14924     auto ES = getEmissionStatus(FD);
14925     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14926         ES == Sema::FunctionEmissionStatus::Unknown)
14927       DeclsToCheckForDeferredDiags.insert(FD);
14928   }
14929 
14930   if (FD && !FD->isDeleted())
14931     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
14932 
14933   return dcl;
14934 }
14935 
14936 /// When we finish delayed parsing of an attribute, we must attach it to the
14937 /// relevant Decl.
14938 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14939                                        ParsedAttributes &Attrs) {
14940   // Always attach attributes to the underlying decl.
14941   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14942     D = TD->getTemplatedDecl();
14943   ProcessDeclAttributeList(S, D, Attrs);
14944 
14945   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14946     if (Method->isStatic())
14947       checkThisInStaticMemberFunctionAttributes(Method);
14948 }
14949 
14950 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14951 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14952 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14953                                           IdentifierInfo &II, Scope *S) {
14954   // Find the scope in which the identifier is injected and the corresponding
14955   // DeclContext.
14956   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14957   // In that case, we inject the declaration into the translation unit scope
14958   // instead.
14959   Scope *BlockScope = S;
14960   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14961     BlockScope = BlockScope->getParent();
14962 
14963   Scope *ContextScope = BlockScope;
14964   while (!ContextScope->getEntity())
14965     ContextScope = ContextScope->getParent();
14966   ContextRAII SavedContext(*this, ContextScope->getEntity());
14967 
14968   // Before we produce a declaration for an implicitly defined
14969   // function, see whether there was a locally-scoped declaration of
14970   // this name as a function or variable. If so, use that
14971   // (non-visible) declaration, and complain about it.
14972   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14973   if (ExternCPrev) {
14974     // We still need to inject the function into the enclosing block scope so
14975     // that later (non-call) uses can see it.
14976     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14977 
14978     // C89 footnote 38:
14979     //   If in fact it is not defined as having type "function returning int",
14980     //   the behavior is undefined.
14981     if (!isa<FunctionDecl>(ExternCPrev) ||
14982         !Context.typesAreCompatible(
14983             cast<FunctionDecl>(ExternCPrev)->getType(),
14984             Context.getFunctionNoProtoType(Context.IntTy))) {
14985       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14986           << ExternCPrev << !getLangOpts().C99;
14987       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14988       return ExternCPrev;
14989     }
14990   }
14991 
14992   // Extension in C99.  Legal in C90, but warn about it.
14993   unsigned diag_id;
14994   if (II.getName().startswith("__builtin_"))
14995     diag_id = diag::warn_builtin_unknown;
14996   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14997   else if (getLangOpts().OpenCL)
14998     diag_id = diag::err_opencl_implicit_function_decl;
14999   else if (getLangOpts().C99)
15000     diag_id = diag::ext_implicit_function_decl;
15001   else
15002     diag_id = diag::warn_implicit_function_decl;
15003 
15004   TypoCorrection Corrected;
15005   // Because typo correction is expensive, only do it if the implicit
15006   // function declaration is going to be treated as an error.
15007   //
15008   // Perform the corection before issuing the main diagnostic, as some consumers
15009   // use typo-correction callbacks to enhance the main diagnostic.
15010   if (S && !ExternCPrev &&
15011       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15012     DeclFilterCCC<FunctionDecl> CCC{};
15013     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15014                             S, nullptr, CCC, CTK_NonError);
15015   }
15016 
15017   Diag(Loc, diag_id) << &II;
15018   if (Corrected)
15019     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15020                  /*ErrorRecovery*/ false);
15021 
15022   // If we found a prior declaration of this function, don't bother building
15023   // another one. We've already pushed that one into scope, so there's nothing
15024   // more to do.
15025   if (ExternCPrev)
15026     return ExternCPrev;
15027 
15028   // Set a Declarator for the implicit definition: int foo();
15029   const char *Dummy;
15030   AttributeFactory attrFactory;
15031   DeclSpec DS(attrFactory);
15032   unsigned DiagID;
15033   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15034                                   Context.getPrintingPolicy());
15035   (void)Error; // Silence warning.
15036   assert(!Error && "Error setting up implicit decl!");
15037   SourceLocation NoLoc;
15038   Declarator D(DS, DeclaratorContext::Block);
15039   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15040                                              /*IsAmbiguous=*/false,
15041                                              /*LParenLoc=*/NoLoc,
15042                                              /*Params=*/nullptr,
15043                                              /*NumParams=*/0,
15044                                              /*EllipsisLoc=*/NoLoc,
15045                                              /*RParenLoc=*/NoLoc,
15046                                              /*RefQualifierIsLvalueRef=*/true,
15047                                              /*RefQualifierLoc=*/NoLoc,
15048                                              /*MutableLoc=*/NoLoc, EST_None,
15049                                              /*ESpecRange=*/SourceRange(),
15050                                              /*Exceptions=*/nullptr,
15051                                              /*ExceptionRanges=*/nullptr,
15052                                              /*NumExceptions=*/0,
15053                                              /*NoexceptExpr=*/nullptr,
15054                                              /*ExceptionSpecTokens=*/nullptr,
15055                                              /*DeclsInPrototype=*/None, Loc,
15056                                              Loc, D),
15057                 std::move(DS.getAttributes()), SourceLocation());
15058   D.SetIdentifier(&II, Loc);
15059 
15060   // Insert this function into the enclosing block scope.
15061   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15062   FD->setImplicit();
15063 
15064   AddKnownFunctionAttributes(FD);
15065 
15066   return FD;
15067 }
15068 
15069 /// If this function is a C++ replaceable global allocation function
15070 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15071 /// adds any function attributes that we know a priori based on the standard.
15072 ///
15073 /// We need to check for duplicate attributes both here and where user-written
15074 /// attributes are applied to declarations.
15075 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15076     FunctionDecl *FD) {
15077   if (FD->isInvalidDecl())
15078     return;
15079 
15080   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15081       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15082     return;
15083 
15084   Optional<unsigned> AlignmentParam;
15085   bool IsNothrow = false;
15086   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15087     return;
15088 
15089   // C++2a [basic.stc.dynamic.allocation]p4:
15090   //   An allocation function that has a non-throwing exception specification
15091   //   indicates failure by returning a null pointer value. Any other allocation
15092   //   function never returns a null pointer value and indicates failure only by
15093   //   throwing an exception [...]
15094   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15095     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15096 
15097   // C++2a [basic.stc.dynamic.allocation]p2:
15098   //   An allocation function attempts to allocate the requested amount of
15099   //   storage. [...] If the request succeeds, the value returned by a
15100   //   replaceable allocation function is a [...] pointer value p0 different
15101   //   from any previously returned value p1 [...]
15102   //
15103   // However, this particular information is being added in codegen,
15104   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15105 
15106   // C++2a [basic.stc.dynamic.allocation]p2:
15107   //   An allocation function attempts to allocate the requested amount of
15108   //   storage. If it is successful, it returns the address of the start of a
15109   //   block of storage whose length in bytes is at least as large as the
15110   //   requested size.
15111   if (!FD->hasAttr<AllocSizeAttr>()) {
15112     FD->addAttr(AllocSizeAttr::CreateImplicit(
15113         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15114         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15115   }
15116 
15117   // C++2a [basic.stc.dynamic.allocation]p3:
15118   //   For an allocation function [...], the pointer returned on a successful
15119   //   call shall represent the address of storage that is aligned as follows:
15120   //   (3.1) If the allocation function takes an argument of type
15121   //         std​::​align_­val_­t, the storage will have the alignment
15122   //         specified by the value of this argument.
15123   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15124     FD->addAttr(AllocAlignAttr::CreateImplicit(
15125         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15126   }
15127 
15128   // FIXME:
15129   // C++2a [basic.stc.dynamic.allocation]p3:
15130   //   For an allocation function [...], the pointer returned on a successful
15131   //   call shall represent the address of storage that is aligned as follows:
15132   //   (3.2) Otherwise, if the allocation function is named operator new[],
15133   //         the storage is aligned for any object that does not have
15134   //         new-extended alignment ([basic.align]) and is no larger than the
15135   //         requested size.
15136   //   (3.3) Otherwise, the storage is aligned for any object that does not
15137   //         have new-extended alignment and is of the requested size.
15138 }
15139 
15140 /// Adds any function attributes that we know a priori based on
15141 /// the declaration of this function.
15142 ///
15143 /// These attributes can apply both to implicitly-declared builtins
15144 /// (like __builtin___printf_chk) or to library-declared functions
15145 /// like NSLog or printf.
15146 ///
15147 /// We need to check for duplicate attributes both here and where user-written
15148 /// attributes are applied to declarations.
15149 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15150   if (FD->isInvalidDecl())
15151     return;
15152 
15153   // If this is a built-in function, map its builtin attributes to
15154   // actual attributes.
15155   if (unsigned BuiltinID = FD->getBuiltinID()) {
15156     // Handle printf-formatting attributes.
15157     unsigned FormatIdx;
15158     bool HasVAListArg;
15159     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15160       if (!FD->hasAttr<FormatAttr>()) {
15161         const char *fmt = "printf";
15162         unsigned int NumParams = FD->getNumParams();
15163         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15164             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15165           fmt = "NSString";
15166         FD->addAttr(FormatAttr::CreateImplicit(Context,
15167                                                &Context.Idents.get(fmt),
15168                                                FormatIdx+1,
15169                                                HasVAListArg ? 0 : FormatIdx+2,
15170                                                FD->getLocation()));
15171       }
15172     }
15173     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15174                                              HasVAListArg)) {
15175      if (!FD->hasAttr<FormatAttr>())
15176        FD->addAttr(FormatAttr::CreateImplicit(Context,
15177                                               &Context.Idents.get("scanf"),
15178                                               FormatIdx+1,
15179                                               HasVAListArg ? 0 : FormatIdx+2,
15180                                               FD->getLocation()));
15181     }
15182 
15183     // Handle automatically recognized callbacks.
15184     SmallVector<int, 4> Encoding;
15185     if (!FD->hasAttr<CallbackAttr>() &&
15186         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15187       FD->addAttr(CallbackAttr::CreateImplicit(
15188           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15189 
15190     // Mark const if we don't care about errno and that is the only thing
15191     // preventing the function from being const. This allows IRgen to use LLVM
15192     // intrinsics for such functions.
15193     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15194         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15195       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15196 
15197     // We make "fma" on GNU or Windows const because we know it does not set
15198     // errno in those environments even though it could set errno based on the
15199     // C standard.
15200     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15201     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15202         !FD->hasAttr<ConstAttr>()) {
15203       switch (BuiltinID) {
15204       case Builtin::BI__builtin_fma:
15205       case Builtin::BI__builtin_fmaf:
15206       case Builtin::BI__builtin_fmal:
15207       case Builtin::BIfma:
15208       case Builtin::BIfmaf:
15209       case Builtin::BIfmal:
15210         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15211         break;
15212       default:
15213         break;
15214       }
15215     }
15216 
15217     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15218         !FD->hasAttr<ReturnsTwiceAttr>())
15219       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15220                                          FD->getLocation()));
15221     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15222       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15223     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15224       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15225     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15226       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15227     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15228         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15229       // Add the appropriate attribute, depending on the CUDA compilation mode
15230       // and which target the builtin belongs to. For example, during host
15231       // compilation, aux builtins are __device__, while the rest are __host__.
15232       if (getLangOpts().CUDAIsDevice !=
15233           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15234         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15235       else
15236         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15237     }
15238 
15239     // Add known guaranteed alignment for allocation functions.
15240     switch (BuiltinID) {
15241     case Builtin::BIaligned_alloc:
15242       if (!FD->hasAttr<AllocAlignAttr>())
15243         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15244                                                    FD->getLocation()));
15245       LLVM_FALLTHROUGH;
15246     case Builtin::BIcalloc:
15247     case Builtin::BImalloc:
15248     case Builtin::BImemalign:
15249     case Builtin::BIrealloc:
15250     case Builtin::BIstrdup:
15251     case Builtin::BIstrndup: {
15252       if (!FD->hasAttr<AssumeAlignedAttr>()) {
15253         unsigned NewAlign = Context.getTargetInfo().getNewAlign() /
15254                             Context.getTargetInfo().getCharWidth();
15255         IntegerLiteral *Alignment = IntegerLiteral::Create(
15256             Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy),
15257             Context.UnsignedIntTy, FD->getLocation());
15258         FD->addAttr(AssumeAlignedAttr::CreateImplicit(
15259             Context, Alignment, /*Offset=*/nullptr, FD->getLocation()));
15260       }
15261       break;
15262     }
15263     default:
15264       break;
15265     }
15266   }
15267 
15268   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15269 
15270   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15271   // throw, add an implicit nothrow attribute to any extern "C" function we come
15272   // across.
15273   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15274       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15275     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15276     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15277       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15278   }
15279 
15280   IdentifierInfo *Name = FD->getIdentifier();
15281   if (!Name)
15282     return;
15283   if ((!getLangOpts().CPlusPlus &&
15284        FD->getDeclContext()->isTranslationUnit()) ||
15285       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15286        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15287        LinkageSpecDecl::lang_c)) {
15288     // Okay: this could be a libc/libm/Objective-C function we know
15289     // about.
15290   } else
15291     return;
15292 
15293   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15294     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15295     // target-specific builtins, perhaps?
15296     if (!FD->hasAttr<FormatAttr>())
15297       FD->addAttr(FormatAttr::CreateImplicit(Context,
15298                                              &Context.Idents.get("printf"), 2,
15299                                              Name->isStr("vasprintf") ? 0 : 3,
15300                                              FD->getLocation()));
15301   }
15302 
15303   if (Name->isStr("__CFStringMakeConstantString")) {
15304     // We already have a __builtin___CFStringMakeConstantString,
15305     // but builds that use -fno-constant-cfstrings don't go through that.
15306     if (!FD->hasAttr<FormatArgAttr>())
15307       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15308                                                 FD->getLocation()));
15309   }
15310 }
15311 
15312 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15313                                     TypeSourceInfo *TInfo) {
15314   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15315   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15316 
15317   if (!TInfo) {
15318     assert(D.isInvalidType() && "no declarator info for valid type");
15319     TInfo = Context.getTrivialTypeSourceInfo(T);
15320   }
15321 
15322   // Scope manipulation handled by caller.
15323   TypedefDecl *NewTD =
15324       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15325                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15326 
15327   // Bail out immediately if we have an invalid declaration.
15328   if (D.isInvalidType()) {
15329     NewTD->setInvalidDecl();
15330     return NewTD;
15331   }
15332 
15333   if (D.getDeclSpec().isModulePrivateSpecified()) {
15334     if (CurContext->isFunctionOrMethod())
15335       Diag(NewTD->getLocation(), diag::err_module_private_local)
15336           << 2 << NewTD
15337           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15338           << FixItHint::CreateRemoval(
15339                  D.getDeclSpec().getModulePrivateSpecLoc());
15340     else
15341       NewTD->setModulePrivate();
15342   }
15343 
15344   // C++ [dcl.typedef]p8:
15345   //   If the typedef declaration defines an unnamed class (or
15346   //   enum), the first typedef-name declared by the declaration
15347   //   to be that class type (or enum type) is used to denote the
15348   //   class type (or enum type) for linkage purposes only.
15349   // We need to check whether the type was declared in the declaration.
15350   switch (D.getDeclSpec().getTypeSpecType()) {
15351   case TST_enum:
15352   case TST_struct:
15353   case TST_interface:
15354   case TST_union:
15355   case TST_class: {
15356     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15357     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15358     break;
15359   }
15360 
15361   default:
15362     break;
15363   }
15364 
15365   return NewTD;
15366 }
15367 
15368 /// Check that this is a valid underlying type for an enum declaration.
15369 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15370   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15371   QualType T = TI->getType();
15372 
15373   if (T->isDependentType())
15374     return false;
15375 
15376   // This doesn't use 'isIntegralType' despite the error message mentioning
15377   // integral type because isIntegralType would also allow enum types in C.
15378   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15379     if (BT->isInteger())
15380       return false;
15381 
15382   if (T->isBitIntType())
15383     return false;
15384 
15385   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15386 }
15387 
15388 /// Check whether this is a valid redeclaration of a previous enumeration.
15389 /// \return true if the redeclaration was invalid.
15390 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15391                                   QualType EnumUnderlyingTy, bool IsFixed,
15392                                   const EnumDecl *Prev) {
15393   if (IsScoped != Prev->isScoped()) {
15394     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15395       << Prev->isScoped();
15396     Diag(Prev->getLocation(), diag::note_previous_declaration);
15397     return true;
15398   }
15399 
15400   if (IsFixed && Prev->isFixed()) {
15401     if (!EnumUnderlyingTy->isDependentType() &&
15402         !Prev->getIntegerType()->isDependentType() &&
15403         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15404                                         Prev->getIntegerType())) {
15405       // TODO: Highlight the underlying type of the redeclaration.
15406       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15407         << EnumUnderlyingTy << Prev->getIntegerType();
15408       Diag(Prev->getLocation(), diag::note_previous_declaration)
15409           << Prev->getIntegerTypeRange();
15410       return true;
15411     }
15412   } else if (IsFixed != Prev->isFixed()) {
15413     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15414       << Prev->isFixed();
15415     Diag(Prev->getLocation(), diag::note_previous_declaration);
15416     return true;
15417   }
15418 
15419   return false;
15420 }
15421 
15422 /// Get diagnostic %select index for tag kind for
15423 /// redeclaration diagnostic message.
15424 /// WARNING: Indexes apply to particular diagnostics only!
15425 ///
15426 /// \returns diagnostic %select index.
15427 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15428   switch (Tag) {
15429   case TTK_Struct: return 0;
15430   case TTK_Interface: return 1;
15431   case TTK_Class:  return 2;
15432   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15433   }
15434 }
15435 
15436 /// Determine if tag kind is a class-key compatible with
15437 /// class for redeclaration (class, struct, or __interface).
15438 ///
15439 /// \returns true iff the tag kind is compatible.
15440 static bool isClassCompatTagKind(TagTypeKind Tag)
15441 {
15442   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15443 }
15444 
15445 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15446                                              TagTypeKind TTK) {
15447   if (isa<TypedefDecl>(PrevDecl))
15448     return NTK_Typedef;
15449   else if (isa<TypeAliasDecl>(PrevDecl))
15450     return NTK_TypeAlias;
15451   else if (isa<ClassTemplateDecl>(PrevDecl))
15452     return NTK_Template;
15453   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15454     return NTK_TypeAliasTemplate;
15455   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15456     return NTK_TemplateTemplateArgument;
15457   switch (TTK) {
15458   case TTK_Struct:
15459   case TTK_Interface:
15460   case TTK_Class:
15461     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15462   case TTK_Union:
15463     return NTK_NonUnion;
15464   case TTK_Enum:
15465     return NTK_NonEnum;
15466   }
15467   llvm_unreachable("invalid TTK");
15468 }
15469 
15470 /// Determine whether a tag with a given kind is acceptable
15471 /// as a redeclaration of the given tag declaration.
15472 ///
15473 /// \returns true if the new tag kind is acceptable, false otherwise.
15474 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15475                                         TagTypeKind NewTag, bool isDefinition,
15476                                         SourceLocation NewTagLoc,
15477                                         const IdentifierInfo *Name) {
15478   // C++ [dcl.type.elab]p3:
15479   //   The class-key or enum keyword present in the
15480   //   elaborated-type-specifier shall agree in kind with the
15481   //   declaration to which the name in the elaborated-type-specifier
15482   //   refers. This rule also applies to the form of
15483   //   elaborated-type-specifier that declares a class-name or
15484   //   friend class since it can be construed as referring to the
15485   //   definition of the class. Thus, in any
15486   //   elaborated-type-specifier, the enum keyword shall be used to
15487   //   refer to an enumeration (7.2), the union class-key shall be
15488   //   used to refer to a union (clause 9), and either the class or
15489   //   struct class-key shall be used to refer to a class (clause 9)
15490   //   declared using the class or struct class-key.
15491   TagTypeKind OldTag = Previous->getTagKind();
15492   if (OldTag != NewTag &&
15493       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15494     return false;
15495 
15496   // Tags are compatible, but we might still want to warn on mismatched tags.
15497   // Non-class tags can't be mismatched at this point.
15498   if (!isClassCompatTagKind(NewTag))
15499     return true;
15500 
15501   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15502   // by our warning analysis. We don't want to warn about mismatches with (eg)
15503   // declarations in system headers that are designed to be specialized, but if
15504   // a user asks us to warn, we should warn if their code contains mismatched
15505   // declarations.
15506   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15507     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15508                                       Loc);
15509   };
15510   if (IsIgnoredLoc(NewTagLoc))
15511     return true;
15512 
15513   auto IsIgnored = [&](const TagDecl *Tag) {
15514     return IsIgnoredLoc(Tag->getLocation());
15515   };
15516   while (IsIgnored(Previous)) {
15517     Previous = Previous->getPreviousDecl();
15518     if (!Previous)
15519       return true;
15520     OldTag = Previous->getTagKind();
15521   }
15522 
15523   bool isTemplate = false;
15524   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15525     isTemplate = Record->getDescribedClassTemplate();
15526 
15527   if (inTemplateInstantiation()) {
15528     if (OldTag != NewTag) {
15529       // In a template instantiation, do not offer fix-its for tag mismatches
15530       // since they usually mess up the template instead of fixing the problem.
15531       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15532         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15533         << getRedeclDiagFromTagKind(OldTag);
15534       // FIXME: Note previous location?
15535     }
15536     return true;
15537   }
15538 
15539   if (isDefinition) {
15540     // On definitions, check all previous tags and issue a fix-it for each
15541     // one that doesn't match the current tag.
15542     if (Previous->getDefinition()) {
15543       // Don't suggest fix-its for redefinitions.
15544       return true;
15545     }
15546 
15547     bool previousMismatch = false;
15548     for (const TagDecl *I : Previous->redecls()) {
15549       if (I->getTagKind() != NewTag) {
15550         // Ignore previous declarations for which the warning was disabled.
15551         if (IsIgnored(I))
15552           continue;
15553 
15554         if (!previousMismatch) {
15555           previousMismatch = true;
15556           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15557             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15558             << getRedeclDiagFromTagKind(I->getTagKind());
15559         }
15560         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15561           << getRedeclDiagFromTagKind(NewTag)
15562           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15563                TypeWithKeyword::getTagTypeKindName(NewTag));
15564       }
15565     }
15566     return true;
15567   }
15568 
15569   // Identify the prevailing tag kind: this is the kind of the definition (if
15570   // there is a non-ignored definition), or otherwise the kind of the prior
15571   // (non-ignored) declaration.
15572   const TagDecl *PrevDef = Previous->getDefinition();
15573   if (PrevDef && IsIgnored(PrevDef))
15574     PrevDef = nullptr;
15575   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15576   if (Redecl->getTagKind() != NewTag) {
15577     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15578       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15579       << getRedeclDiagFromTagKind(OldTag);
15580     Diag(Redecl->getLocation(), diag::note_previous_use);
15581 
15582     // If there is a previous definition, suggest a fix-it.
15583     if (PrevDef) {
15584       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15585         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15586         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15587              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15588     }
15589   }
15590 
15591   return true;
15592 }
15593 
15594 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15595 /// from an outer enclosing namespace or file scope inside a friend declaration.
15596 /// This should provide the commented out code in the following snippet:
15597 ///   namespace N {
15598 ///     struct X;
15599 ///     namespace M {
15600 ///       struct Y { friend struct /*N::*/ X; };
15601 ///     }
15602 ///   }
15603 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15604                                          SourceLocation NameLoc) {
15605   // While the decl is in a namespace, do repeated lookup of that name and see
15606   // if we get the same namespace back.  If we do not, continue until
15607   // translation unit scope, at which point we have a fully qualified NNS.
15608   SmallVector<IdentifierInfo *, 4> Namespaces;
15609   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15610   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15611     // This tag should be declared in a namespace, which can only be enclosed by
15612     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15613     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15614     if (!Namespace || Namespace->isAnonymousNamespace())
15615       return FixItHint();
15616     IdentifierInfo *II = Namespace->getIdentifier();
15617     Namespaces.push_back(II);
15618     NamedDecl *Lookup = SemaRef.LookupSingleName(
15619         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15620     if (Lookup == Namespace)
15621       break;
15622   }
15623 
15624   // Once we have all the namespaces, reverse them to go outermost first, and
15625   // build an NNS.
15626   SmallString<64> Insertion;
15627   llvm::raw_svector_ostream OS(Insertion);
15628   if (DC->isTranslationUnit())
15629     OS << "::";
15630   std::reverse(Namespaces.begin(), Namespaces.end());
15631   for (auto *II : Namespaces)
15632     OS << II->getName() << "::";
15633   return FixItHint::CreateInsertion(NameLoc, Insertion);
15634 }
15635 
15636 /// Determine whether a tag originally declared in context \p OldDC can
15637 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15638 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15639 /// using-declaration).
15640 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15641                                          DeclContext *NewDC) {
15642   OldDC = OldDC->getRedeclContext();
15643   NewDC = NewDC->getRedeclContext();
15644 
15645   if (OldDC->Equals(NewDC))
15646     return true;
15647 
15648   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15649   // encloses the other).
15650   if (S.getLangOpts().MSVCCompat &&
15651       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15652     return true;
15653 
15654   return false;
15655 }
15656 
15657 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15658 /// former case, Name will be non-null.  In the later case, Name will be null.
15659 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15660 /// reference/declaration/definition of a tag.
15661 ///
15662 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15663 /// trailing-type-specifier) other than one in an alias-declaration.
15664 ///
15665 /// \param SkipBody If non-null, will be set to indicate if the caller should
15666 /// skip the definition of this tag and treat it as if it were a declaration.
15667 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15668                      SourceLocation KWLoc, CXXScopeSpec &SS,
15669                      IdentifierInfo *Name, SourceLocation NameLoc,
15670                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15671                      SourceLocation ModulePrivateLoc,
15672                      MultiTemplateParamsArg TemplateParameterLists,
15673                      bool &OwnedDecl, bool &IsDependent,
15674                      SourceLocation ScopedEnumKWLoc,
15675                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15676                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15677                      SkipBodyInfo *SkipBody) {
15678   // If this is not a definition, it must have a name.
15679   IdentifierInfo *OrigName = Name;
15680   assert((Name != nullptr || TUK == TUK_Definition) &&
15681          "Nameless record must be a definition!");
15682   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15683 
15684   OwnedDecl = false;
15685   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15686   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15687 
15688   // FIXME: Check member specializations more carefully.
15689   bool isMemberSpecialization = false;
15690   bool Invalid = false;
15691 
15692   // We only need to do this matching if we have template parameters
15693   // or a scope specifier, which also conveniently avoids this work
15694   // for non-C++ cases.
15695   if (TemplateParameterLists.size() > 0 ||
15696       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15697     if (TemplateParameterList *TemplateParams =
15698             MatchTemplateParametersToScopeSpecifier(
15699                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15700                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15701       if (Kind == TTK_Enum) {
15702         Diag(KWLoc, diag::err_enum_template);
15703         return nullptr;
15704       }
15705 
15706       if (TemplateParams->size() > 0) {
15707         // This is a declaration or definition of a class template (which may
15708         // be a member of another template).
15709 
15710         if (Invalid)
15711           return nullptr;
15712 
15713         OwnedDecl = false;
15714         DeclResult Result = CheckClassTemplate(
15715             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15716             AS, ModulePrivateLoc,
15717             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15718             TemplateParameterLists.data(), SkipBody);
15719         return Result.get();
15720       } else {
15721         // The "template<>" header is extraneous.
15722         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15723           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15724         isMemberSpecialization = true;
15725       }
15726     }
15727 
15728     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15729         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15730       return nullptr;
15731   }
15732 
15733   // Figure out the underlying type if this a enum declaration. We need to do
15734   // this early, because it's needed to detect if this is an incompatible
15735   // redeclaration.
15736   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15737   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15738 
15739   if (Kind == TTK_Enum) {
15740     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15741       // No underlying type explicitly specified, or we failed to parse the
15742       // type, default to int.
15743       EnumUnderlying = Context.IntTy.getTypePtr();
15744     } else if (UnderlyingType.get()) {
15745       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15746       // integral type; any cv-qualification is ignored.
15747       TypeSourceInfo *TI = nullptr;
15748       GetTypeFromParser(UnderlyingType.get(), &TI);
15749       EnumUnderlying = TI;
15750 
15751       if (CheckEnumUnderlyingType(TI))
15752         // Recover by falling back to int.
15753         EnumUnderlying = Context.IntTy.getTypePtr();
15754 
15755       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15756                                           UPPC_FixedUnderlyingType))
15757         EnumUnderlying = Context.IntTy.getTypePtr();
15758 
15759     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15760       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15761       // of 'int'. However, if this is an unfixed forward declaration, don't set
15762       // the underlying type unless the user enables -fms-compatibility. This
15763       // makes unfixed forward declared enums incomplete and is more conforming.
15764       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15765         EnumUnderlying = Context.IntTy.getTypePtr();
15766     }
15767   }
15768 
15769   DeclContext *SearchDC = CurContext;
15770   DeclContext *DC = CurContext;
15771   bool isStdBadAlloc = false;
15772   bool isStdAlignValT = false;
15773 
15774   RedeclarationKind Redecl = forRedeclarationInCurContext();
15775   if (TUK == TUK_Friend || TUK == TUK_Reference)
15776     Redecl = NotForRedeclaration;
15777 
15778   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15779   /// implemented asks for structural equivalence checking, the returned decl
15780   /// here is passed back to the parser, allowing the tag body to be parsed.
15781   auto createTagFromNewDecl = [&]() -> TagDecl * {
15782     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15783     // If there is an identifier, use the location of the identifier as the
15784     // location of the decl, otherwise use the location of the struct/union
15785     // keyword.
15786     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15787     TagDecl *New = nullptr;
15788 
15789     if (Kind == TTK_Enum) {
15790       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15791                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15792       // If this is an undefined enum, bail.
15793       if (TUK != TUK_Definition && !Invalid)
15794         return nullptr;
15795       if (EnumUnderlying) {
15796         EnumDecl *ED = cast<EnumDecl>(New);
15797         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15798           ED->setIntegerTypeSourceInfo(TI);
15799         else
15800           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15801         ED->setPromotionType(ED->getIntegerType());
15802       }
15803     } else { // struct/union
15804       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15805                                nullptr);
15806     }
15807 
15808     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15809       // Add alignment attributes if necessary; these attributes are checked
15810       // when the ASTContext lays out the structure.
15811       //
15812       // It is important for implementing the correct semantics that this
15813       // happen here (in ActOnTag). The #pragma pack stack is
15814       // maintained as a result of parser callbacks which can occur at
15815       // many points during the parsing of a struct declaration (because
15816       // the #pragma tokens are effectively skipped over during the
15817       // parsing of the struct).
15818       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15819         AddAlignmentAttributesForRecord(RD);
15820         AddMsStructLayoutForRecord(RD);
15821       }
15822     }
15823     New->setLexicalDeclContext(CurContext);
15824     return New;
15825   };
15826 
15827   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15828   if (Name && SS.isNotEmpty()) {
15829     // We have a nested-name tag ('struct foo::bar').
15830 
15831     // Check for invalid 'foo::'.
15832     if (SS.isInvalid()) {
15833       Name = nullptr;
15834       goto CreateNewDecl;
15835     }
15836 
15837     // If this is a friend or a reference to a class in a dependent
15838     // context, don't try to make a decl for it.
15839     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15840       DC = computeDeclContext(SS, false);
15841       if (!DC) {
15842         IsDependent = true;
15843         return nullptr;
15844       }
15845     } else {
15846       DC = computeDeclContext(SS, true);
15847       if (!DC) {
15848         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15849           << SS.getRange();
15850         return nullptr;
15851       }
15852     }
15853 
15854     if (RequireCompleteDeclContext(SS, DC))
15855       return nullptr;
15856 
15857     SearchDC = DC;
15858     // Look-up name inside 'foo::'.
15859     LookupQualifiedName(Previous, DC);
15860 
15861     if (Previous.isAmbiguous())
15862       return nullptr;
15863 
15864     if (Previous.empty()) {
15865       // Name lookup did not find anything. However, if the
15866       // nested-name-specifier refers to the current instantiation,
15867       // and that current instantiation has any dependent base
15868       // classes, we might find something at instantiation time: treat
15869       // this as a dependent elaborated-type-specifier.
15870       // But this only makes any sense for reference-like lookups.
15871       if (Previous.wasNotFoundInCurrentInstantiation() &&
15872           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15873         IsDependent = true;
15874         return nullptr;
15875       }
15876 
15877       // A tag 'foo::bar' must already exist.
15878       Diag(NameLoc, diag::err_not_tag_in_scope)
15879         << Kind << Name << DC << SS.getRange();
15880       Name = nullptr;
15881       Invalid = true;
15882       goto CreateNewDecl;
15883     }
15884   } else if (Name) {
15885     // C++14 [class.mem]p14:
15886     //   If T is the name of a class, then each of the following shall have a
15887     //   name different from T:
15888     //    -- every member of class T that is itself a type
15889     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15890         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15891       return nullptr;
15892 
15893     // If this is a named struct, check to see if there was a previous forward
15894     // declaration or definition.
15895     // FIXME: We're looking into outer scopes here, even when we
15896     // shouldn't be. Doing so can result in ambiguities that we
15897     // shouldn't be diagnosing.
15898     LookupName(Previous, S);
15899 
15900     // When declaring or defining a tag, ignore ambiguities introduced
15901     // by types using'ed into this scope.
15902     if (Previous.isAmbiguous() &&
15903         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15904       LookupResult::Filter F = Previous.makeFilter();
15905       while (F.hasNext()) {
15906         NamedDecl *ND = F.next();
15907         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15908                 SearchDC->getRedeclContext()))
15909           F.erase();
15910       }
15911       F.done();
15912     }
15913 
15914     // C++11 [namespace.memdef]p3:
15915     //   If the name in a friend declaration is neither qualified nor
15916     //   a template-id and the declaration is a function or an
15917     //   elaborated-type-specifier, the lookup to determine whether
15918     //   the entity has been previously declared shall not consider
15919     //   any scopes outside the innermost enclosing namespace.
15920     //
15921     // MSVC doesn't implement the above rule for types, so a friend tag
15922     // declaration may be a redeclaration of a type declared in an enclosing
15923     // scope.  They do implement this rule for friend functions.
15924     //
15925     // Does it matter that this should be by scope instead of by
15926     // semantic context?
15927     if (!Previous.empty() && TUK == TUK_Friend) {
15928       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15929       LookupResult::Filter F = Previous.makeFilter();
15930       bool FriendSawTagOutsideEnclosingNamespace = false;
15931       while (F.hasNext()) {
15932         NamedDecl *ND = F.next();
15933         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15934         if (DC->isFileContext() &&
15935             !EnclosingNS->Encloses(ND->getDeclContext())) {
15936           if (getLangOpts().MSVCCompat)
15937             FriendSawTagOutsideEnclosingNamespace = true;
15938           else
15939             F.erase();
15940         }
15941       }
15942       F.done();
15943 
15944       // Diagnose this MSVC extension in the easy case where lookup would have
15945       // unambiguously found something outside the enclosing namespace.
15946       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15947         NamedDecl *ND = Previous.getFoundDecl();
15948         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15949             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15950       }
15951     }
15952 
15953     // Note:  there used to be some attempt at recovery here.
15954     if (Previous.isAmbiguous())
15955       return nullptr;
15956 
15957     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15958       // FIXME: This makes sure that we ignore the contexts associated
15959       // with C structs, unions, and enums when looking for a matching
15960       // tag declaration or definition. See the similar lookup tweak
15961       // in Sema::LookupName; is there a better way to deal with this?
15962       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15963         SearchDC = SearchDC->getParent();
15964     }
15965   }
15966 
15967   if (Previous.isSingleResult() &&
15968       Previous.getFoundDecl()->isTemplateParameter()) {
15969     // Maybe we will complain about the shadowed template parameter.
15970     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15971     // Just pretend that we didn't see the previous declaration.
15972     Previous.clear();
15973   }
15974 
15975   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15976       DC->Equals(getStdNamespace())) {
15977     if (Name->isStr("bad_alloc")) {
15978       // This is a declaration of or a reference to "std::bad_alloc".
15979       isStdBadAlloc = true;
15980 
15981       // If std::bad_alloc has been implicitly declared (but made invisible to
15982       // name lookup), fill in this implicit declaration as the previous
15983       // declaration, so that the declarations get chained appropriately.
15984       if (Previous.empty() && StdBadAlloc)
15985         Previous.addDecl(getStdBadAlloc());
15986     } else if (Name->isStr("align_val_t")) {
15987       isStdAlignValT = true;
15988       if (Previous.empty() && StdAlignValT)
15989         Previous.addDecl(getStdAlignValT());
15990     }
15991   }
15992 
15993   // If we didn't find a previous declaration, and this is a reference
15994   // (or friend reference), move to the correct scope.  In C++, we
15995   // also need to do a redeclaration lookup there, just in case
15996   // there's a shadow friend decl.
15997   if (Name && Previous.empty() &&
15998       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15999     if (Invalid) goto CreateNewDecl;
16000     assert(SS.isEmpty());
16001 
16002     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16003       // C++ [basic.scope.pdecl]p5:
16004       //   -- for an elaborated-type-specifier of the form
16005       //
16006       //          class-key identifier
16007       //
16008       //      if the elaborated-type-specifier is used in the
16009       //      decl-specifier-seq or parameter-declaration-clause of a
16010       //      function defined in namespace scope, the identifier is
16011       //      declared as a class-name in the namespace that contains
16012       //      the declaration; otherwise, except as a friend
16013       //      declaration, the identifier is declared in the smallest
16014       //      non-class, non-function-prototype scope that contains the
16015       //      declaration.
16016       //
16017       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16018       // C structs and unions.
16019       //
16020       // It is an error in C++ to declare (rather than define) an enum
16021       // type, including via an elaborated type specifier.  We'll
16022       // diagnose that later; for now, declare the enum in the same
16023       // scope as we would have picked for any other tag type.
16024       //
16025       // GNU C also supports this behavior as part of its incomplete
16026       // enum types extension, while GNU C++ does not.
16027       //
16028       // Find the context where we'll be declaring the tag.
16029       // FIXME: We would like to maintain the current DeclContext as the
16030       // lexical context,
16031       SearchDC = getTagInjectionContext(SearchDC);
16032 
16033       // Find the scope where we'll be declaring the tag.
16034       S = getTagInjectionScope(S, getLangOpts());
16035     } else {
16036       assert(TUK == TUK_Friend);
16037       // C++ [namespace.memdef]p3:
16038       //   If a friend declaration in a non-local class first declares a
16039       //   class or function, the friend class or function is a member of
16040       //   the innermost enclosing namespace.
16041       SearchDC = SearchDC->getEnclosingNamespaceContext();
16042     }
16043 
16044     // In C++, we need to do a redeclaration lookup to properly
16045     // diagnose some problems.
16046     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16047     // hidden declaration so that we don't get ambiguity errors when using a
16048     // type declared by an elaborated-type-specifier.  In C that is not correct
16049     // and we should instead merge compatible types found by lookup.
16050     if (getLangOpts().CPlusPlus) {
16051       // FIXME: This can perform qualified lookups into function contexts,
16052       // which are meaningless.
16053       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16054       LookupQualifiedName(Previous, SearchDC);
16055     } else {
16056       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16057       LookupName(Previous, S);
16058     }
16059   }
16060 
16061   // If we have a known previous declaration to use, then use it.
16062   if (Previous.empty() && SkipBody && SkipBody->Previous)
16063     Previous.addDecl(SkipBody->Previous);
16064 
16065   if (!Previous.empty()) {
16066     NamedDecl *PrevDecl = Previous.getFoundDecl();
16067     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16068 
16069     // It's okay to have a tag decl in the same scope as a typedef
16070     // which hides a tag decl in the same scope.  Finding this
16071     // with a redeclaration lookup can only actually happen in C++.
16072     //
16073     // This is also okay for elaborated-type-specifiers, which is
16074     // technically forbidden by the current standard but which is
16075     // okay according to the likely resolution of an open issue;
16076     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16077     if (getLangOpts().CPlusPlus) {
16078       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16079         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16080           TagDecl *Tag = TT->getDecl();
16081           if (Tag->getDeclName() == Name &&
16082               Tag->getDeclContext()->getRedeclContext()
16083                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16084             PrevDecl = Tag;
16085             Previous.clear();
16086             Previous.addDecl(Tag);
16087             Previous.resolveKind();
16088           }
16089         }
16090       }
16091     }
16092 
16093     // If this is a redeclaration of a using shadow declaration, it must
16094     // declare a tag in the same context. In MSVC mode, we allow a
16095     // redefinition if either context is within the other.
16096     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16097       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16098       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16099           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16100           !(OldTag && isAcceptableTagRedeclContext(
16101                           *this, OldTag->getDeclContext(), SearchDC))) {
16102         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16103         Diag(Shadow->getTargetDecl()->getLocation(),
16104              diag::note_using_decl_target);
16105         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16106             << 0;
16107         // Recover by ignoring the old declaration.
16108         Previous.clear();
16109         goto CreateNewDecl;
16110       }
16111     }
16112 
16113     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16114       // If this is a use of a previous tag, or if the tag is already declared
16115       // in the same scope (so that the definition/declaration completes or
16116       // rementions the tag), reuse the decl.
16117       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16118           isDeclInScope(DirectPrevDecl, SearchDC, S,
16119                         SS.isNotEmpty() || isMemberSpecialization)) {
16120         // Make sure that this wasn't declared as an enum and now used as a
16121         // struct or something similar.
16122         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16123                                           TUK == TUK_Definition, KWLoc,
16124                                           Name)) {
16125           bool SafeToContinue
16126             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16127                Kind != TTK_Enum);
16128           if (SafeToContinue)
16129             Diag(KWLoc, diag::err_use_with_wrong_tag)
16130               << Name
16131               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16132                                               PrevTagDecl->getKindName());
16133           else
16134             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16135           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16136 
16137           if (SafeToContinue)
16138             Kind = PrevTagDecl->getTagKind();
16139           else {
16140             // Recover by making this an anonymous redefinition.
16141             Name = nullptr;
16142             Previous.clear();
16143             Invalid = true;
16144           }
16145         }
16146 
16147         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16148           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16149           if (TUK == TUK_Reference || TUK == TUK_Friend)
16150             return PrevTagDecl;
16151 
16152           QualType EnumUnderlyingTy;
16153           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16154             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16155           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16156             EnumUnderlyingTy = QualType(T, 0);
16157 
16158           // All conflicts with previous declarations are recovered by
16159           // returning the previous declaration, unless this is a definition,
16160           // in which case we want the caller to bail out.
16161           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16162                                      ScopedEnum, EnumUnderlyingTy,
16163                                      IsFixed, PrevEnum))
16164             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16165         }
16166 
16167         // C++11 [class.mem]p1:
16168         //   A member shall not be declared twice in the member-specification,
16169         //   except that a nested class or member class template can be declared
16170         //   and then later defined.
16171         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16172             S->isDeclScope(PrevDecl)) {
16173           Diag(NameLoc, diag::ext_member_redeclared);
16174           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16175         }
16176 
16177         if (!Invalid) {
16178           // If this is a use, just return the declaration we found, unless
16179           // we have attributes.
16180           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16181             if (!Attrs.empty()) {
16182               // FIXME: Diagnose these attributes. For now, we create a new
16183               // declaration to hold them.
16184             } else if (TUK == TUK_Reference &&
16185                        (PrevTagDecl->getFriendObjectKind() ==
16186                             Decl::FOK_Undeclared ||
16187                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16188                        SS.isEmpty()) {
16189               // This declaration is a reference to an existing entity, but
16190               // has different visibility from that entity: it either makes
16191               // a friend visible or it makes a type visible in a new module.
16192               // In either case, create a new declaration. We only do this if
16193               // the declaration would have meant the same thing if no prior
16194               // declaration were found, that is, if it was found in the same
16195               // scope where we would have injected a declaration.
16196               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16197                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16198                 return PrevTagDecl;
16199               // This is in the injected scope, create a new declaration in
16200               // that scope.
16201               S = getTagInjectionScope(S, getLangOpts());
16202             } else {
16203               return PrevTagDecl;
16204             }
16205           }
16206 
16207           // Diagnose attempts to redefine a tag.
16208           if (TUK == TUK_Definition) {
16209             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16210               // If we're defining a specialization and the previous definition
16211               // is from an implicit instantiation, don't emit an error
16212               // here; we'll catch this in the general case below.
16213               bool IsExplicitSpecializationAfterInstantiation = false;
16214               if (isMemberSpecialization) {
16215                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16216                   IsExplicitSpecializationAfterInstantiation =
16217                     RD->getTemplateSpecializationKind() !=
16218                     TSK_ExplicitSpecialization;
16219                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16220                   IsExplicitSpecializationAfterInstantiation =
16221                     ED->getTemplateSpecializationKind() !=
16222                     TSK_ExplicitSpecialization;
16223               }
16224 
16225               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16226               // not keep more that one definition around (merge them). However,
16227               // ensure the decl passes the structural compatibility check in
16228               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16229               NamedDecl *Hidden = nullptr;
16230               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16231                 // There is a definition of this tag, but it is not visible. We
16232                 // explicitly make use of C++'s one definition rule here, and
16233                 // assume that this definition is identical to the hidden one
16234                 // we already have. Make the existing definition visible and
16235                 // use it in place of this one.
16236                 if (!getLangOpts().CPlusPlus) {
16237                   // Postpone making the old definition visible until after we
16238                   // complete parsing the new one and do the structural
16239                   // comparison.
16240                   SkipBody->CheckSameAsPrevious = true;
16241                   SkipBody->New = createTagFromNewDecl();
16242                   SkipBody->Previous = Def;
16243                   return Def;
16244                 } else {
16245                   SkipBody->ShouldSkip = true;
16246                   SkipBody->Previous = Def;
16247                   makeMergedDefinitionVisible(Hidden);
16248                   // Carry on and handle it like a normal definition. We'll
16249                   // skip starting the definitiion later.
16250                 }
16251               } else if (!IsExplicitSpecializationAfterInstantiation) {
16252                 // A redeclaration in function prototype scope in C isn't
16253                 // visible elsewhere, so merely issue a warning.
16254                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16255                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16256                 else
16257                   Diag(NameLoc, diag::err_redefinition) << Name;
16258                 notePreviousDefinition(Def,
16259                                        NameLoc.isValid() ? NameLoc : KWLoc);
16260                 // If this is a redefinition, recover by making this
16261                 // struct be anonymous, which will make any later
16262                 // references get the previous definition.
16263                 Name = nullptr;
16264                 Previous.clear();
16265                 Invalid = true;
16266               }
16267             } else {
16268               // If the type is currently being defined, complain
16269               // about a nested redefinition.
16270               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16271               if (TD->isBeingDefined()) {
16272                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16273                 Diag(PrevTagDecl->getLocation(),
16274                      diag::note_previous_definition);
16275                 Name = nullptr;
16276                 Previous.clear();
16277                 Invalid = true;
16278               }
16279             }
16280 
16281             // Okay, this is definition of a previously declared or referenced
16282             // tag. We're going to create a new Decl for it.
16283           }
16284 
16285           // Okay, we're going to make a redeclaration.  If this is some kind
16286           // of reference, make sure we build the redeclaration in the same DC
16287           // as the original, and ignore the current access specifier.
16288           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16289             SearchDC = PrevTagDecl->getDeclContext();
16290             AS = AS_none;
16291           }
16292         }
16293         // If we get here we have (another) forward declaration or we
16294         // have a definition.  Just create a new decl.
16295 
16296       } else {
16297         // If we get here, this is a definition of a new tag type in a nested
16298         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16299         // new decl/type.  We set PrevDecl to NULL so that the entities
16300         // have distinct types.
16301         Previous.clear();
16302       }
16303       // If we get here, we're going to create a new Decl. If PrevDecl
16304       // is non-NULL, it's a definition of the tag declared by
16305       // PrevDecl. If it's NULL, we have a new definition.
16306 
16307     // Otherwise, PrevDecl is not a tag, but was found with tag
16308     // lookup.  This is only actually possible in C++, where a few
16309     // things like templates still live in the tag namespace.
16310     } else {
16311       // Use a better diagnostic if an elaborated-type-specifier
16312       // found the wrong kind of type on the first
16313       // (non-redeclaration) lookup.
16314       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16315           !Previous.isForRedeclaration()) {
16316         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16317         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16318                                                        << Kind;
16319         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16320         Invalid = true;
16321 
16322       // Otherwise, only diagnose if the declaration is in scope.
16323       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16324                                 SS.isNotEmpty() || isMemberSpecialization)) {
16325         // do nothing
16326 
16327       // Diagnose implicit declarations introduced by elaborated types.
16328       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16329         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16330         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16331         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16332         Invalid = true;
16333 
16334       // Otherwise it's a declaration.  Call out a particularly common
16335       // case here.
16336       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16337         unsigned Kind = 0;
16338         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16339         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16340           << Name << Kind << TND->getUnderlyingType();
16341         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16342         Invalid = true;
16343 
16344       // Otherwise, diagnose.
16345       } else {
16346         // The tag name clashes with something else in the target scope,
16347         // issue an error and recover by making this tag be anonymous.
16348         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16349         notePreviousDefinition(PrevDecl, NameLoc);
16350         Name = nullptr;
16351         Invalid = true;
16352       }
16353 
16354       // The existing declaration isn't relevant to us; we're in a
16355       // new scope, so clear out the previous declaration.
16356       Previous.clear();
16357     }
16358   }
16359 
16360 CreateNewDecl:
16361 
16362   TagDecl *PrevDecl = nullptr;
16363   if (Previous.isSingleResult())
16364     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16365 
16366   // If there is an identifier, use the location of the identifier as the
16367   // location of the decl, otherwise use the location of the struct/union
16368   // keyword.
16369   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16370 
16371   // Otherwise, create a new declaration. If there is a previous
16372   // declaration of the same entity, the two will be linked via
16373   // PrevDecl.
16374   TagDecl *New;
16375 
16376   if (Kind == TTK_Enum) {
16377     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16378     // enum X { A, B, C } D;    D should chain to X.
16379     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16380                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16381                            ScopedEnumUsesClassTag, IsFixed);
16382 
16383     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16384       StdAlignValT = cast<EnumDecl>(New);
16385 
16386     // If this is an undefined enum, warn.
16387     if (TUK != TUK_Definition && !Invalid) {
16388       TagDecl *Def;
16389       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16390         // C++0x: 7.2p2: opaque-enum-declaration.
16391         // Conflicts are diagnosed above. Do nothing.
16392       }
16393       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16394         Diag(Loc, diag::ext_forward_ref_enum_def)
16395           << New;
16396         Diag(Def->getLocation(), diag::note_previous_definition);
16397       } else {
16398         unsigned DiagID = diag::ext_forward_ref_enum;
16399         if (getLangOpts().MSVCCompat)
16400           DiagID = diag::ext_ms_forward_ref_enum;
16401         else if (getLangOpts().CPlusPlus)
16402           DiagID = diag::err_forward_ref_enum;
16403         Diag(Loc, DiagID);
16404       }
16405     }
16406 
16407     if (EnumUnderlying) {
16408       EnumDecl *ED = cast<EnumDecl>(New);
16409       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16410         ED->setIntegerTypeSourceInfo(TI);
16411       else
16412         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16413       ED->setPromotionType(ED->getIntegerType());
16414       assert(ED->isComplete() && "enum with type should be complete");
16415     }
16416   } else {
16417     // struct/union/class
16418 
16419     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16420     // struct X { int A; } D;    D should chain to X.
16421     if (getLangOpts().CPlusPlus) {
16422       // FIXME: Look for a way to use RecordDecl for simple structs.
16423       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16424                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16425 
16426       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16427         StdBadAlloc = cast<CXXRecordDecl>(New);
16428     } else
16429       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16430                                cast_or_null<RecordDecl>(PrevDecl));
16431   }
16432 
16433   // C++11 [dcl.type]p3:
16434   //   A type-specifier-seq shall not define a class or enumeration [...].
16435   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16436       TUK == TUK_Definition) {
16437     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16438       << Context.getTagDeclType(New);
16439     Invalid = true;
16440   }
16441 
16442   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16443       DC->getDeclKind() == Decl::Enum) {
16444     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16445       << Context.getTagDeclType(New);
16446     Invalid = true;
16447   }
16448 
16449   // Maybe add qualifier info.
16450   if (SS.isNotEmpty()) {
16451     if (SS.isSet()) {
16452       // If this is either a declaration or a definition, check the
16453       // nested-name-specifier against the current context.
16454       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16455           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16456                                        isMemberSpecialization))
16457         Invalid = true;
16458 
16459       New->setQualifierInfo(SS.getWithLocInContext(Context));
16460       if (TemplateParameterLists.size() > 0) {
16461         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16462       }
16463     }
16464     else
16465       Invalid = true;
16466   }
16467 
16468   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16469     // Add alignment attributes if necessary; these attributes are checked when
16470     // the ASTContext lays out the structure.
16471     //
16472     // It is important for implementing the correct semantics that this
16473     // happen here (in ActOnTag). The #pragma pack stack is
16474     // maintained as a result of parser callbacks which can occur at
16475     // many points during the parsing of a struct declaration (because
16476     // the #pragma tokens are effectively skipped over during the
16477     // parsing of the struct).
16478     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16479       AddAlignmentAttributesForRecord(RD);
16480       AddMsStructLayoutForRecord(RD);
16481     }
16482   }
16483 
16484   if (ModulePrivateLoc.isValid()) {
16485     if (isMemberSpecialization)
16486       Diag(New->getLocation(), diag::err_module_private_specialization)
16487         << 2
16488         << FixItHint::CreateRemoval(ModulePrivateLoc);
16489     // __module_private__ does not apply to local classes. However, we only
16490     // diagnose this as an error when the declaration specifiers are
16491     // freestanding. Here, we just ignore the __module_private__.
16492     else if (!SearchDC->isFunctionOrMethod())
16493       New->setModulePrivate();
16494   }
16495 
16496   // If this is a specialization of a member class (of a class template),
16497   // check the specialization.
16498   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16499     Invalid = true;
16500 
16501   // If we're declaring or defining a tag in function prototype scope in C,
16502   // note that this type can only be used within the function and add it to
16503   // the list of decls to inject into the function definition scope.
16504   if ((Name || Kind == TTK_Enum) &&
16505       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16506     if (getLangOpts().CPlusPlus) {
16507       // C++ [dcl.fct]p6:
16508       //   Types shall not be defined in return or parameter types.
16509       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16510         Diag(Loc, diag::err_type_defined_in_param_type)
16511             << Name;
16512         Invalid = true;
16513       }
16514     } else if (!PrevDecl) {
16515       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16516     }
16517   }
16518 
16519   if (Invalid)
16520     New->setInvalidDecl();
16521 
16522   // Set the lexical context. If the tag has a C++ scope specifier, the
16523   // lexical context will be different from the semantic context.
16524   New->setLexicalDeclContext(CurContext);
16525 
16526   // Mark this as a friend decl if applicable.
16527   // In Microsoft mode, a friend declaration also acts as a forward
16528   // declaration so we always pass true to setObjectOfFriendDecl to make
16529   // the tag name visible.
16530   if (TUK == TUK_Friend)
16531     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16532 
16533   // Set the access specifier.
16534   if (!Invalid && SearchDC->isRecord())
16535     SetMemberAccessSpecifier(New, PrevDecl, AS);
16536 
16537   if (PrevDecl)
16538     CheckRedeclarationModuleOwnership(New, PrevDecl);
16539 
16540   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16541     New->startDefinition();
16542 
16543   ProcessDeclAttributeList(S, New, Attrs);
16544   AddPragmaAttributes(S, New);
16545 
16546   // If this has an identifier, add it to the scope stack.
16547   if (TUK == TUK_Friend) {
16548     // We might be replacing an existing declaration in the lookup tables;
16549     // if so, borrow its access specifier.
16550     if (PrevDecl)
16551       New->setAccess(PrevDecl->getAccess());
16552 
16553     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16554     DC->makeDeclVisibleInContext(New);
16555     if (Name) // can be null along some error paths
16556       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16557         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16558   } else if (Name) {
16559     S = getNonFieldDeclScope(S);
16560     PushOnScopeChains(New, S, true);
16561   } else {
16562     CurContext->addDecl(New);
16563   }
16564 
16565   // If this is the C FILE type, notify the AST context.
16566   if (IdentifierInfo *II = New->getIdentifier())
16567     if (!New->isInvalidDecl() &&
16568         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16569         II->isStr("FILE"))
16570       Context.setFILEDecl(New);
16571 
16572   if (PrevDecl)
16573     mergeDeclAttributes(New, PrevDecl);
16574 
16575   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16576     inferGslOwnerPointerAttribute(CXXRD);
16577 
16578   // If there's a #pragma GCC visibility in scope, set the visibility of this
16579   // record.
16580   AddPushedVisibilityAttribute(New);
16581 
16582   if (isMemberSpecialization && !New->isInvalidDecl())
16583     CompleteMemberSpecialization(New, Previous);
16584 
16585   OwnedDecl = true;
16586   // In C++, don't return an invalid declaration. We can't recover well from
16587   // the cases where we make the type anonymous.
16588   if (Invalid && getLangOpts().CPlusPlus) {
16589     if (New->isBeingDefined())
16590       if (auto RD = dyn_cast<RecordDecl>(New))
16591         RD->completeDefinition();
16592     return nullptr;
16593   } else if (SkipBody && SkipBody->ShouldSkip) {
16594     return SkipBody->Previous;
16595   } else {
16596     return New;
16597   }
16598 }
16599 
16600 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16601   AdjustDeclIfTemplate(TagD);
16602   TagDecl *Tag = cast<TagDecl>(TagD);
16603 
16604   // Enter the tag context.
16605   PushDeclContext(S, Tag);
16606 
16607   ActOnDocumentableDecl(TagD);
16608 
16609   // If there's a #pragma GCC visibility in scope, set the visibility of this
16610   // record.
16611   AddPushedVisibilityAttribute(Tag);
16612 }
16613 
16614 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16615                                     SkipBodyInfo &SkipBody) {
16616   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16617     return false;
16618 
16619   // Make the previous decl visible.
16620   makeMergedDefinitionVisible(SkipBody.Previous);
16621   return true;
16622 }
16623 
16624 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16625   assert(isa<ObjCContainerDecl>(IDecl) &&
16626          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16627   DeclContext *OCD = cast<DeclContext>(IDecl);
16628   assert(OCD->getLexicalParent() == CurContext &&
16629       "The next DeclContext should be lexically contained in the current one.");
16630   CurContext = OCD;
16631   return IDecl;
16632 }
16633 
16634 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16635                                            SourceLocation FinalLoc,
16636                                            bool IsFinalSpelledSealed,
16637                                            bool IsAbstract,
16638                                            SourceLocation LBraceLoc) {
16639   AdjustDeclIfTemplate(TagD);
16640   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16641 
16642   FieldCollector->StartClass();
16643 
16644   if (!Record->getIdentifier())
16645     return;
16646 
16647   if (IsAbstract)
16648     Record->markAbstract();
16649 
16650   if (FinalLoc.isValid()) {
16651     Record->addAttr(FinalAttr::Create(
16652         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16653         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16654   }
16655   // C++ [class]p2:
16656   //   [...] The class-name is also inserted into the scope of the
16657   //   class itself; this is known as the injected-class-name. For
16658   //   purposes of access checking, the injected-class-name is treated
16659   //   as if it were a public member name.
16660   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16661       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16662       Record->getLocation(), Record->getIdentifier(),
16663       /*PrevDecl=*/nullptr,
16664       /*DelayTypeCreation=*/true);
16665   Context.getTypeDeclType(InjectedClassName, Record);
16666   InjectedClassName->setImplicit();
16667   InjectedClassName->setAccess(AS_public);
16668   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16669       InjectedClassName->setDescribedClassTemplate(Template);
16670   PushOnScopeChains(InjectedClassName, S);
16671   assert(InjectedClassName->isInjectedClassName() &&
16672          "Broken injected-class-name");
16673 }
16674 
16675 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16676                                     SourceRange BraceRange) {
16677   AdjustDeclIfTemplate(TagD);
16678   TagDecl *Tag = cast<TagDecl>(TagD);
16679   Tag->setBraceRange(BraceRange);
16680 
16681   // Make sure we "complete" the definition even it is invalid.
16682   if (Tag->isBeingDefined()) {
16683     assert(Tag->isInvalidDecl() && "We should already have completed it");
16684     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16685       RD->completeDefinition();
16686   }
16687 
16688   if (isa<CXXRecordDecl>(Tag)) {
16689     FieldCollector->FinishClass();
16690   }
16691 
16692   // Exit this scope of this tag's definition.
16693   PopDeclContext();
16694 
16695   if (getCurLexicalContext()->isObjCContainer() &&
16696       Tag->getDeclContext()->isFileContext())
16697     Tag->setTopLevelDeclInObjCContainer();
16698 
16699   // Notify the consumer that we've defined a tag.
16700   if (!Tag->isInvalidDecl())
16701     Consumer.HandleTagDeclDefinition(Tag);
16702 
16703   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16704   // from XLs and instead matches the XL #pragma pack(1) behavior.
16705   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16706       AlignPackStack.hasValue()) {
16707     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16708     // Only diagnose #pragma align(packed).
16709     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16710       return;
16711     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16712     if (!RD)
16713       return;
16714     // Only warn if there is at least 1 bitfield member.
16715     if (llvm::any_of(RD->fields(),
16716                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16717       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16718   }
16719 }
16720 
16721 void Sema::ActOnObjCContainerFinishDefinition() {
16722   // Exit this scope of this interface definition.
16723   PopDeclContext();
16724 }
16725 
16726 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16727   assert(DC == CurContext && "Mismatch of container contexts");
16728   OriginalLexicalContext = DC;
16729   ActOnObjCContainerFinishDefinition();
16730 }
16731 
16732 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16733   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16734   OriginalLexicalContext = nullptr;
16735 }
16736 
16737 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16738   AdjustDeclIfTemplate(TagD);
16739   TagDecl *Tag = cast<TagDecl>(TagD);
16740   Tag->setInvalidDecl();
16741 
16742   // Make sure we "complete" the definition even it is invalid.
16743   if (Tag->isBeingDefined()) {
16744     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16745       RD->completeDefinition();
16746   }
16747 
16748   // We're undoing ActOnTagStartDefinition here, not
16749   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16750   // the FieldCollector.
16751 
16752   PopDeclContext();
16753 }
16754 
16755 // Note that FieldName may be null for anonymous bitfields.
16756 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16757                                 IdentifierInfo *FieldName,
16758                                 QualType FieldTy, bool IsMsStruct,
16759                                 Expr *BitWidth, bool *ZeroWidth) {
16760   assert(BitWidth);
16761   if (BitWidth->containsErrors())
16762     return ExprError();
16763 
16764   // Default to true; that shouldn't confuse checks for emptiness
16765   if (ZeroWidth)
16766     *ZeroWidth = true;
16767 
16768   // C99 6.7.2.1p4 - verify the field type.
16769   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16770   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16771     // Handle incomplete and sizeless types with a specific error.
16772     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16773                                  diag::err_field_incomplete_or_sizeless))
16774       return ExprError();
16775     if (FieldName)
16776       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16777         << FieldName << FieldTy << BitWidth->getSourceRange();
16778     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16779       << FieldTy << BitWidth->getSourceRange();
16780   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16781                                              UPPC_BitFieldWidth))
16782     return ExprError();
16783 
16784   // If the bit-width is type- or value-dependent, don't try to check
16785   // it now.
16786   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16787     return BitWidth;
16788 
16789   llvm::APSInt Value;
16790   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16791   if (ICE.isInvalid())
16792     return ICE;
16793   BitWidth = ICE.get();
16794 
16795   if (Value != 0 && ZeroWidth)
16796     *ZeroWidth = false;
16797 
16798   // Zero-width bitfield is ok for anonymous field.
16799   if (Value == 0 && FieldName)
16800     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16801 
16802   if (Value.isSigned() && Value.isNegative()) {
16803     if (FieldName)
16804       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16805                << FieldName << toString(Value, 10);
16806     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16807       << toString(Value, 10);
16808   }
16809 
16810   // The size of the bit-field must not exceed our maximum permitted object
16811   // size.
16812   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16813     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16814            << !FieldName << FieldName << toString(Value, 10);
16815   }
16816 
16817   if (!FieldTy->isDependentType()) {
16818     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16819     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16820     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16821 
16822     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16823     // ABI.
16824     bool CStdConstraintViolation =
16825         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16826     bool MSBitfieldViolation =
16827         Value.ugt(TypeStorageSize) &&
16828         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16829     if (CStdConstraintViolation || MSBitfieldViolation) {
16830       unsigned DiagWidth =
16831           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16832       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16833              << (bool)FieldName << FieldName << toString(Value, 10)
16834              << !CStdConstraintViolation << DiagWidth;
16835     }
16836 
16837     // Warn on types where the user might conceivably expect to get all
16838     // specified bits as value bits: that's all integral types other than
16839     // 'bool'.
16840     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16841       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16842           << FieldName << toString(Value, 10)
16843           << (unsigned)TypeWidth;
16844     }
16845   }
16846 
16847   return BitWidth;
16848 }
16849 
16850 /// ActOnField - Each field of a C struct/union is passed into this in order
16851 /// to create a FieldDecl object for it.
16852 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16853                        Declarator &D, Expr *BitfieldWidth) {
16854   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16855                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16856                                /*InitStyle=*/ICIS_NoInit, AS_public);
16857   return Res;
16858 }
16859 
16860 /// HandleField - Analyze a field of a C struct or a C++ data member.
16861 ///
16862 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16863                              SourceLocation DeclStart,
16864                              Declarator &D, Expr *BitWidth,
16865                              InClassInitStyle InitStyle,
16866                              AccessSpecifier AS) {
16867   if (D.isDecompositionDeclarator()) {
16868     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16869     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16870       << Decomp.getSourceRange();
16871     return nullptr;
16872   }
16873 
16874   IdentifierInfo *II = D.getIdentifier();
16875   SourceLocation Loc = DeclStart;
16876   if (II) Loc = D.getIdentifierLoc();
16877 
16878   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16879   QualType T = TInfo->getType();
16880   if (getLangOpts().CPlusPlus) {
16881     CheckExtraCXXDefaultArguments(D);
16882 
16883     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16884                                         UPPC_DataMemberType)) {
16885       D.setInvalidType();
16886       T = Context.IntTy;
16887       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16888     }
16889   }
16890 
16891   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16892 
16893   if (D.getDeclSpec().isInlineSpecified())
16894     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16895         << getLangOpts().CPlusPlus17;
16896   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16897     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16898          diag::err_invalid_thread)
16899       << DeclSpec::getSpecifierName(TSCS);
16900 
16901   // Check to see if this name was declared as a member previously
16902   NamedDecl *PrevDecl = nullptr;
16903   LookupResult Previous(*this, II, Loc, LookupMemberName,
16904                         ForVisibleRedeclaration);
16905   LookupName(Previous, S);
16906   switch (Previous.getResultKind()) {
16907     case LookupResult::Found:
16908     case LookupResult::FoundUnresolvedValue:
16909       PrevDecl = Previous.getAsSingle<NamedDecl>();
16910       break;
16911 
16912     case LookupResult::FoundOverloaded:
16913       PrevDecl = Previous.getRepresentativeDecl();
16914       break;
16915 
16916     case LookupResult::NotFound:
16917     case LookupResult::NotFoundInCurrentInstantiation:
16918     case LookupResult::Ambiguous:
16919       break;
16920   }
16921   Previous.suppressDiagnostics();
16922 
16923   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16924     // Maybe we will complain about the shadowed template parameter.
16925     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16926     // Just pretend that we didn't see the previous declaration.
16927     PrevDecl = nullptr;
16928   }
16929 
16930   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16931     PrevDecl = nullptr;
16932 
16933   bool Mutable
16934     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16935   SourceLocation TSSL = D.getBeginLoc();
16936   FieldDecl *NewFD
16937     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16938                      TSSL, AS, PrevDecl, &D);
16939 
16940   if (NewFD->isInvalidDecl())
16941     Record->setInvalidDecl();
16942 
16943   if (D.getDeclSpec().isModulePrivateSpecified())
16944     NewFD->setModulePrivate();
16945 
16946   if (NewFD->isInvalidDecl() && PrevDecl) {
16947     // Don't introduce NewFD into scope; there's already something
16948     // with the same name in the same scope.
16949   } else if (II) {
16950     PushOnScopeChains(NewFD, S);
16951   } else
16952     Record->addDecl(NewFD);
16953 
16954   return NewFD;
16955 }
16956 
16957 /// Build a new FieldDecl and check its well-formedness.
16958 ///
16959 /// This routine builds a new FieldDecl given the fields name, type,
16960 /// record, etc. \p PrevDecl should refer to any previous declaration
16961 /// with the same name and in the same scope as the field to be
16962 /// created.
16963 ///
16964 /// \returns a new FieldDecl.
16965 ///
16966 /// \todo The Declarator argument is a hack. It will be removed once
16967 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16968                                 TypeSourceInfo *TInfo,
16969                                 RecordDecl *Record, SourceLocation Loc,
16970                                 bool Mutable, Expr *BitWidth,
16971                                 InClassInitStyle InitStyle,
16972                                 SourceLocation TSSL,
16973                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16974                                 Declarator *D) {
16975   IdentifierInfo *II = Name.getAsIdentifierInfo();
16976   bool InvalidDecl = false;
16977   if (D) InvalidDecl = D->isInvalidType();
16978 
16979   // If we receive a broken type, recover by assuming 'int' and
16980   // marking this declaration as invalid.
16981   if (T.isNull() || T->containsErrors()) {
16982     InvalidDecl = true;
16983     T = Context.IntTy;
16984   }
16985 
16986   QualType EltTy = Context.getBaseElementType(T);
16987   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16988     if (RequireCompleteSizedType(Loc, EltTy,
16989                                  diag::err_field_incomplete_or_sizeless)) {
16990       // Fields of incomplete type force their record to be invalid.
16991       Record->setInvalidDecl();
16992       InvalidDecl = true;
16993     } else {
16994       NamedDecl *Def;
16995       EltTy->isIncompleteType(&Def);
16996       if (Def && Def->isInvalidDecl()) {
16997         Record->setInvalidDecl();
16998         InvalidDecl = true;
16999       }
17000     }
17001   }
17002 
17003   // TR 18037 does not allow fields to be declared with address space
17004   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17005       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17006     Diag(Loc, diag::err_field_with_address_space);
17007     Record->setInvalidDecl();
17008     InvalidDecl = true;
17009   }
17010 
17011   if (LangOpts.OpenCL) {
17012     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17013     // used as structure or union field: image, sampler, event or block types.
17014     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17015         T->isBlockPointerType()) {
17016       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17017       Record->setInvalidDecl();
17018       InvalidDecl = true;
17019     }
17020     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17021     // is enabled.
17022     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17023                         "__cl_clang_bitfields", LangOpts)) {
17024       Diag(Loc, diag::err_opencl_bitfields);
17025       InvalidDecl = true;
17026     }
17027   }
17028 
17029   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17030   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17031       T.hasQualifiers()) {
17032     InvalidDecl = true;
17033     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17034   }
17035 
17036   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17037   // than a variably modified type.
17038   if (!InvalidDecl && T->isVariablyModifiedType()) {
17039     if (!tryToFixVariablyModifiedVarType(
17040             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17041       InvalidDecl = true;
17042   }
17043 
17044   // Fields can not have abstract class types
17045   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17046                                              diag::err_abstract_type_in_decl,
17047                                              AbstractFieldType))
17048     InvalidDecl = true;
17049 
17050   bool ZeroWidth = false;
17051   if (InvalidDecl)
17052     BitWidth = nullptr;
17053   // If this is declared as a bit-field, check the bit-field.
17054   if (BitWidth) {
17055     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17056                               &ZeroWidth).get();
17057     if (!BitWidth) {
17058       InvalidDecl = true;
17059       BitWidth = nullptr;
17060       ZeroWidth = false;
17061     }
17062   }
17063 
17064   // Check that 'mutable' is consistent with the type of the declaration.
17065   if (!InvalidDecl && Mutable) {
17066     unsigned DiagID = 0;
17067     if (T->isReferenceType())
17068       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17069                                         : diag::err_mutable_reference;
17070     else if (T.isConstQualified())
17071       DiagID = diag::err_mutable_const;
17072 
17073     if (DiagID) {
17074       SourceLocation ErrLoc = Loc;
17075       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17076         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17077       Diag(ErrLoc, DiagID);
17078       if (DiagID != diag::ext_mutable_reference) {
17079         Mutable = false;
17080         InvalidDecl = true;
17081       }
17082     }
17083   }
17084 
17085   // C++11 [class.union]p8 (DR1460):
17086   //   At most one variant member of a union may have a
17087   //   brace-or-equal-initializer.
17088   if (InitStyle != ICIS_NoInit)
17089     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17090 
17091   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17092                                        BitWidth, Mutable, InitStyle);
17093   if (InvalidDecl)
17094     NewFD->setInvalidDecl();
17095 
17096   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17097     Diag(Loc, diag::err_duplicate_member) << II;
17098     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17099     NewFD->setInvalidDecl();
17100   }
17101 
17102   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17103     if (Record->isUnion()) {
17104       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17105         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17106         if (RDecl->getDefinition()) {
17107           // C++ [class.union]p1: An object of a class with a non-trivial
17108           // constructor, a non-trivial copy constructor, a non-trivial
17109           // destructor, or a non-trivial copy assignment operator
17110           // cannot be a member of a union, nor can an array of such
17111           // objects.
17112           if (CheckNontrivialField(NewFD))
17113             NewFD->setInvalidDecl();
17114         }
17115       }
17116 
17117       // C++ [class.union]p1: If a union contains a member of reference type,
17118       // the program is ill-formed, except when compiling with MSVC extensions
17119       // enabled.
17120       if (EltTy->isReferenceType()) {
17121         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17122                                     diag::ext_union_member_of_reference_type :
17123                                     diag::err_union_member_of_reference_type)
17124           << NewFD->getDeclName() << EltTy;
17125         if (!getLangOpts().MicrosoftExt)
17126           NewFD->setInvalidDecl();
17127       }
17128     }
17129   }
17130 
17131   // FIXME: We need to pass in the attributes given an AST
17132   // representation, not a parser representation.
17133   if (D) {
17134     // FIXME: The current scope is almost... but not entirely... correct here.
17135     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17136 
17137     if (NewFD->hasAttrs())
17138       CheckAlignasUnderalignment(NewFD);
17139   }
17140 
17141   // In auto-retain/release, infer strong retension for fields of
17142   // retainable type.
17143   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17144     NewFD->setInvalidDecl();
17145 
17146   if (T.isObjCGCWeak())
17147     Diag(Loc, diag::warn_attribute_weak_on_field);
17148 
17149   // PPC MMA non-pointer types are not allowed as field types.
17150   if (Context.getTargetInfo().getTriple().isPPC64() &&
17151       CheckPPCMMAType(T, NewFD->getLocation()))
17152     NewFD->setInvalidDecl();
17153 
17154   NewFD->setAccess(AS);
17155   return NewFD;
17156 }
17157 
17158 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17159   assert(FD);
17160   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17161 
17162   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17163     return false;
17164 
17165   QualType EltTy = Context.getBaseElementType(FD->getType());
17166   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17167     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17168     if (RDecl->getDefinition()) {
17169       // We check for copy constructors before constructors
17170       // because otherwise we'll never get complaints about
17171       // copy constructors.
17172 
17173       CXXSpecialMember member = CXXInvalid;
17174       // We're required to check for any non-trivial constructors. Since the
17175       // implicit default constructor is suppressed if there are any
17176       // user-declared constructors, we just need to check that there is a
17177       // trivial default constructor and a trivial copy constructor. (We don't
17178       // worry about move constructors here, since this is a C++98 check.)
17179       if (RDecl->hasNonTrivialCopyConstructor())
17180         member = CXXCopyConstructor;
17181       else if (!RDecl->hasTrivialDefaultConstructor())
17182         member = CXXDefaultConstructor;
17183       else if (RDecl->hasNonTrivialCopyAssignment())
17184         member = CXXCopyAssignment;
17185       else if (RDecl->hasNonTrivialDestructor())
17186         member = CXXDestructor;
17187 
17188       if (member != CXXInvalid) {
17189         if (!getLangOpts().CPlusPlus11 &&
17190             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17191           // Objective-C++ ARC: it is an error to have a non-trivial field of
17192           // a union. However, system headers in Objective-C programs
17193           // occasionally have Objective-C lifetime objects within unions,
17194           // and rather than cause the program to fail, we make those
17195           // members unavailable.
17196           SourceLocation Loc = FD->getLocation();
17197           if (getSourceManager().isInSystemHeader(Loc)) {
17198             if (!FD->hasAttr<UnavailableAttr>())
17199               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17200                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17201             return false;
17202           }
17203         }
17204 
17205         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17206                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17207                diag::err_illegal_union_or_anon_struct_member)
17208           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17209         DiagnoseNontrivial(RDecl, member);
17210         return !getLangOpts().CPlusPlus11;
17211       }
17212     }
17213   }
17214 
17215   return false;
17216 }
17217 
17218 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17219 ///  AST enum value.
17220 static ObjCIvarDecl::AccessControl
17221 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17222   switch (ivarVisibility) {
17223   default: llvm_unreachable("Unknown visitibility kind");
17224   case tok::objc_private: return ObjCIvarDecl::Private;
17225   case tok::objc_public: return ObjCIvarDecl::Public;
17226   case tok::objc_protected: return ObjCIvarDecl::Protected;
17227   case tok::objc_package: return ObjCIvarDecl::Package;
17228   }
17229 }
17230 
17231 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17232 /// in order to create an IvarDecl object for it.
17233 Decl *Sema::ActOnIvar(Scope *S,
17234                                 SourceLocation DeclStart,
17235                                 Declarator &D, Expr *BitfieldWidth,
17236                                 tok::ObjCKeywordKind Visibility) {
17237 
17238   IdentifierInfo *II = D.getIdentifier();
17239   Expr *BitWidth = (Expr*)BitfieldWidth;
17240   SourceLocation Loc = DeclStart;
17241   if (II) Loc = D.getIdentifierLoc();
17242 
17243   // FIXME: Unnamed fields can be handled in various different ways, for
17244   // example, unnamed unions inject all members into the struct namespace!
17245 
17246   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17247   QualType T = TInfo->getType();
17248 
17249   if (BitWidth) {
17250     // 6.7.2.1p3, 6.7.2.1p4
17251     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17252     if (!BitWidth)
17253       D.setInvalidType();
17254   } else {
17255     // Not a bitfield.
17256 
17257     // validate II.
17258 
17259   }
17260   if (T->isReferenceType()) {
17261     Diag(Loc, diag::err_ivar_reference_type);
17262     D.setInvalidType();
17263   }
17264   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17265   // than a variably modified type.
17266   else if (T->isVariablyModifiedType()) {
17267     if (!tryToFixVariablyModifiedVarType(
17268             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17269       D.setInvalidType();
17270   }
17271 
17272   // Get the visibility (access control) for this ivar.
17273   ObjCIvarDecl::AccessControl ac =
17274     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17275                                         : ObjCIvarDecl::None;
17276   // Must set ivar's DeclContext to its enclosing interface.
17277   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17278   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17279     return nullptr;
17280   ObjCContainerDecl *EnclosingContext;
17281   if (ObjCImplementationDecl *IMPDecl =
17282       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17283     if (LangOpts.ObjCRuntime.isFragile()) {
17284     // Case of ivar declared in an implementation. Context is that of its class.
17285       EnclosingContext = IMPDecl->getClassInterface();
17286       assert(EnclosingContext && "Implementation has no class interface!");
17287     }
17288     else
17289       EnclosingContext = EnclosingDecl;
17290   } else {
17291     if (ObjCCategoryDecl *CDecl =
17292         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17293       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17294         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17295         return nullptr;
17296       }
17297     }
17298     EnclosingContext = EnclosingDecl;
17299   }
17300 
17301   // Construct the decl.
17302   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17303                                              DeclStart, Loc, II, T,
17304                                              TInfo, ac, (Expr *)BitfieldWidth);
17305 
17306   if (II) {
17307     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17308                                            ForVisibleRedeclaration);
17309     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17310         && !isa<TagDecl>(PrevDecl)) {
17311       Diag(Loc, diag::err_duplicate_member) << II;
17312       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17313       NewID->setInvalidDecl();
17314     }
17315   }
17316 
17317   // Process attributes attached to the ivar.
17318   ProcessDeclAttributes(S, NewID, D);
17319 
17320   if (D.isInvalidType())
17321     NewID->setInvalidDecl();
17322 
17323   // In ARC, infer 'retaining' for ivars of retainable type.
17324   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17325     NewID->setInvalidDecl();
17326 
17327   if (D.getDeclSpec().isModulePrivateSpecified())
17328     NewID->setModulePrivate();
17329 
17330   if (II) {
17331     // FIXME: When interfaces are DeclContexts, we'll need to add
17332     // these to the interface.
17333     S->AddDecl(NewID);
17334     IdResolver.AddDecl(NewID);
17335   }
17336 
17337   if (LangOpts.ObjCRuntime.isNonFragile() &&
17338       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17339     Diag(Loc, diag::warn_ivars_in_interface);
17340 
17341   return NewID;
17342 }
17343 
17344 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17345 /// class and class extensions. For every class \@interface and class
17346 /// extension \@interface, if the last ivar is a bitfield of any type,
17347 /// then add an implicit `char :0` ivar to the end of that interface.
17348 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17349                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17350   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17351     return;
17352 
17353   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17354   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17355 
17356   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17357     return;
17358   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17359   if (!ID) {
17360     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17361       if (!CD->IsClassExtension())
17362         return;
17363     }
17364     // No need to add this to end of @implementation.
17365     else
17366       return;
17367   }
17368   // All conditions are met. Add a new bitfield to the tail end of ivars.
17369   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17370   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17371 
17372   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17373                               DeclLoc, DeclLoc, nullptr,
17374                               Context.CharTy,
17375                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17376                                                                DeclLoc),
17377                               ObjCIvarDecl::Private, BW,
17378                               true);
17379   AllIvarDecls.push_back(Ivar);
17380 }
17381 
17382 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17383                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17384                        SourceLocation RBrac,
17385                        const ParsedAttributesView &Attrs) {
17386   assert(EnclosingDecl && "missing record or interface decl");
17387 
17388   // If this is an Objective-C @implementation or category and we have
17389   // new fields here we should reset the layout of the interface since
17390   // it will now change.
17391   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17392     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17393     switch (DC->getKind()) {
17394     default: break;
17395     case Decl::ObjCCategory:
17396       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17397       break;
17398     case Decl::ObjCImplementation:
17399       Context.
17400         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17401       break;
17402     }
17403   }
17404 
17405   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17406   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17407 
17408   // Start counting up the number of named members; make sure to include
17409   // members of anonymous structs and unions in the total.
17410   unsigned NumNamedMembers = 0;
17411   if (Record) {
17412     for (const auto *I : Record->decls()) {
17413       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17414         if (IFD->getDeclName())
17415           ++NumNamedMembers;
17416     }
17417   }
17418 
17419   // Verify that all the fields are okay.
17420   SmallVector<FieldDecl*, 32> RecFields;
17421 
17422   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17423        i != end; ++i) {
17424     FieldDecl *FD = cast<FieldDecl>(*i);
17425 
17426     // Get the type for the field.
17427     const Type *FDTy = FD->getType().getTypePtr();
17428 
17429     if (!FD->isAnonymousStructOrUnion()) {
17430       // Remember all fields written by the user.
17431       RecFields.push_back(FD);
17432     }
17433 
17434     // If the field is already invalid for some reason, don't emit more
17435     // diagnostics about it.
17436     if (FD->isInvalidDecl()) {
17437       EnclosingDecl->setInvalidDecl();
17438       continue;
17439     }
17440 
17441     // C99 6.7.2.1p2:
17442     //   A structure or union shall not contain a member with
17443     //   incomplete or function type (hence, a structure shall not
17444     //   contain an instance of itself, but may contain a pointer to
17445     //   an instance of itself), except that the last member of a
17446     //   structure with more than one named member may have incomplete
17447     //   array type; such a structure (and any union containing,
17448     //   possibly recursively, a member that is such a structure)
17449     //   shall not be a member of a structure or an element of an
17450     //   array.
17451     bool IsLastField = (i + 1 == Fields.end());
17452     if (FDTy->isFunctionType()) {
17453       // Field declared as a function.
17454       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17455         << FD->getDeclName();
17456       FD->setInvalidDecl();
17457       EnclosingDecl->setInvalidDecl();
17458       continue;
17459     } else if (FDTy->isIncompleteArrayType() &&
17460                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17461       if (Record) {
17462         // Flexible array member.
17463         // Microsoft and g++ is more permissive regarding flexible array.
17464         // It will accept flexible array in union and also
17465         // as the sole element of a struct/class.
17466         unsigned DiagID = 0;
17467         if (!Record->isUnion() && !IsLastField) {
17468           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17469             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17470           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17471           FD->setInvalidDecl();
17472           EnclosingDecl->setInvalidDecl();
17473           continue;
17474         } else if (Record->isUnion())
17475           DiagID = getLangOpts().MicrosoftExt
17476                        ? diag::ext_flexible_array_union_ms
17477                        : getLangOpts().CPlusPlus
17478                              ? diag::ext_flexible_array_union_gnu
17479                              : diag::err_flexible_array_union;
17480         else if (NumNamedMembers < 1)
17481           DiagID = getLangOpts().MicrosoftExt
17482                        ? diag::ext_flexible_array_empty_aggregate_ms
17483                        : getLangOpts().CPlusPlus
17484                              ? diag::ext_flexible_array_empty_aggregate_gnu
17485                              : diag::err_flexible_array_empty_aggregate;
17486 
17487         if (DiagID)
17488           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17489                                           << Record->getTagKind();
17490         // While the layout of types that contain virtual bases is not specified
17491         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17492         // virtual bases after the derived members.  This would make a flexible
17493         // array member declared at the end of an object not adjacent to the end
17494         // of the type.
17495         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17496           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17497               << FD->getDeclName() << Record->getTagKind();
17498         if (!getLangOpts().C99)
17499           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17500             << FD->getDeclName() << Record->getTagKind();
17501 
17502         // If the element type has a non-trivial destructor, we would not
17503         // implicitly destroy the elements, so disallow it for now.
17504         //
17505         // FIXME: GCC allows this. We should probably either implicitly delete
17506         // the destructor of the containing class, or just allow this.
17507         QualType BaseElem = Context.getBaseElementType(FD->getType());
17508         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17509           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17510             << FD->getDeclName() << FD->getType();
17511           FD->setInvalidDecl();
17512           EnclosingDecl->setInvalidDecl();
17513           continue;
17514         }
17515         // Okay, we have a legal flexible array member at the end of the struct.
17516         Record->setHasFlexibleArrayMember(true);
17517       } else {
17518         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17519         // unless they are followed by another ivar. That check is done
17520         // elsewhere, after synthesized ivars are known.
17521       }
17522     } else if (!FDTy->isDependentType() &&
17523                RequireCompleteSizedType(
17524                    FD->getLocation(), FD->getType(),
17525                    diag::err_field_incomplete_or_sizeless)) {
17526       // Incomplete type
17527       FD->setInvalidDecl();
17528       EnclosingDecl->setInvalidDecl();
17529       continue;
17530     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17531       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17532         // A type which contains a flexible array member is considered to be a
17533         // flexible array member.
17534         Record->setHasFlexibleArrayMember(true);
17535         if (!Record->isUnion()) {
17536           // If this is a struct/class and this is not the last element, reject
17537           // it.  Note that GCC supports variable sized arrays in the middle of
17538           // structures.
17539           if (!IsLastField)
17540             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17541               << FD->getDeclName() << FD->getType();
17542           else {
17543             // We support flexible arrays at the end of structs in
17544             // other structs as an extension.
17545             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17546               << FD->getDeclName();
17547           }
17548         }
17549       }
17550       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17551           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17552                                  diag::err_abstract_type_in_decl,
17553                                  AbstractIvarType)) {
17554         // Ivars can not have abstract class types
17555         FD->setInvalidDecl();
17556       }
17557       if (Record && FDTTy->getDecl()->hasObjectMember())
17558         Record->setHasObjectMember(true);
17559       if (Record && FDTTy->getDecl()->hasVolatileMember())
17560         Record->setHasVolatileMember(true);
17561     } else if (FDTy->isObjCObjectType()) {
17562       /// A field cannot be an Objective-c object
17563       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17564         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17565       QualType T = Context.getObjCObjectPointerType(FD->getType());
17566       FD->setType(T);
17567     } else if (Record && Record->isUnion() &&
17568                FD->getType().hasNonTrivialObjCLifetime() &&
17569                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17570                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17571                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17572                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17573       // For backward compatibility, fields of C unions declared in system
17574       // headers that have non-trivial ObjC ownership qualifications are marked
17575       // as unavailable unless the qualifier is explicit and __strong. This can
17576       // break ABI compatibility between programs compiled with ARC and MRR, but
17577       // is a better option than rejecting programs using those unions under
17578       // ARC.
17579       FD->addAttr(UnavailableAttr::CreateImplicit(
17580           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17581           FD->getLocation()));
17582     } else if (getLangOpts().ObjC &&
17583                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17584                !Record->hasObjectMember()) {
17585       if (FD->getType()->isObjCObjectPointerType() ||
17586           FD->getType().isObjCGCStrong())
17587         Record->setHasObjectMember(true);
17588       else if (Context.getAsArrayType(FD->getType())) {
17589         QualType BaseType = Context.getBaseElementType(FD->getType());
17590         if (BaseType->isRecordType() &&
17591             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17592           Record->setHasObjectMember(true);
17593         else if (BaseType->isObjCObjectPointerType() ||
17594                  BaseType.isObjCGCStrong())
17595                Record->setHasObjectMember(true);
17596       }
17597     }
17598 
17599     if (Record && !getLangOpts().CPlusPlus &&
17600         !shouldIgnoreForRecordTriviality(FD)) {
17601       QualType FT = FD->getType();
17602       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17603         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17604         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17605             Record->isUnion())
17606           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17607       }
17608       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17609       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17610         Record->setNonTrivialToPrimitiveCopy(true);
17611         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17612           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17613       }
17614       if (FT.isDestructedType()) {
17615         Record->setNonTrivialToPrimitiveDestroy(true);
17616         Record->setParamDestroyedInCallee(true);
17617         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17618           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17619       }
17620 
17621       if (const auto *RT = FT->getAs<RecordType>()) {
17622         if (RT->getDecl()->getArgPassingRestrictions() ==
17623             RecordDecl::APK_CanNeverPassInRegs)
17624           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17625       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17626         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17627     }
17628 
17629     if (Record && FD->getType().isVolatileQualified())
17630       Record->setHasVolatileMember(true);
17631     // Keep track of the number of named members.
17632     if (FD->getIdentifier())
17633       ++NumNamedMembers;
17634   }
17635 
17636   // Okay, we successfully defined 'Record'.
17637   if (Record) {
17638     bool Completed = false;
17639     if (CXXRecord) {
17640       if (!CXXRecord->isInvalidDecl()) {
17641         // Set access bits correctly on the directly-declared conversions.
17642         for (CXXRecordDecl::conversion_iterator
17643                I = CXXRecord->conversion_begin(),
17644                E = CXXRecord->conversion_end(); I != E; ++I)
17645           I.setAccess((*I)->getAccess());
17646       }
17647 
17648       // Add any implicitly-declared members to this class.
17649       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17650 
17651       if (!CXXRecord->isDependentType()) {
17652         if (!CXXRecord->isInvalidDecl()) {
17653           // If we have virtual base classes, we may end up finding multiple
17654           // final overriders for a given virtual function. Check for this
17655           // problem now.
17656           if (CXXRecord->getNumVBases()) {
17657             CXXFinalOverriderMap FinalOverriders;
17658             CXXRecord->getFinalOverriders(FinalOverriders);
17659 
17660             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17661                                              MEnd = FinalOverriders.end();
17662                  M != MEnd; ++M) {
17663               for (OverridingMethods::iterator SO = M->second.begin(),
17664                                             SOEnd = M->second.end();
17665                    SO != SOEnd; ++SO) {
17666                 assert(SO->second.size() > 0 &&
17667                        "Virtual function without overriding functions?");
17668                 if (SO->second.size() == 1)
17669                   continue;
17670 
17671                 // C++ [class.virtual]p2:
17672                 //   In a derived class, if a virtual member function of a base
17673                 //   class subobject has more than one final overrider the
17674                 //   program is ill-formed.
17675                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17676                   << (const NamedDecl *)M->first << Record;
17677                 Diag(M->first->getLocation(),
17678                      diag::note_overridden_virtual_function);
17679                 for (OverridingMethods::overriding_iterator
17680                           OM = SO->second.begin(),
17681                        OMEnd = SO->second.end();
17682                      OM != OMEnd; ++OM)
17683                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17684                     << (const NamedDecl *)M->first << OM->Method->getParent();
17685 
17686                 Record->setInvalidDecl();
17687               }
17688             }
17689             CXXRecord->completeDefinition(&FinalOverriders);
17690             Completed = true;
17691           }
17692         }
17693       }
17694     }
17695 
17696     if (!Completed)
17697       Record->completeDefinition();
17698 
17699     // Handle attributes before checking the layout.
17700     ProcessDeclAttributeList(S, Record, Attrs);
17701 
17702     // We may have deferred checking for a deleted destructor. Check now.
17703     if (CXXRecord) {
17704       auto *Dtor = CXXRecord->getDestructor();
17705       if (Dtor && Dtor->isImplicit() &&
17706           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17707         CXXRecord->setImplicitDestructorIsDeleted();
17708         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17709       }
17710     }
17711 
17712     if (Record->hasAttrs()) {
17713       CheckAlignasUnderalignment(Record);
17714 
17715       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17716         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17717                                            IA->getRange(), IA->getBestCase(),
17718                                            IA->getInheritanceModel());
17719     }
17720 
17721     // Check if the structure/union declaration is a type that can have zero
17722     // size in C. For C this is a language extension, for C++ it may cause
17723     // compatibility problems.
17724     bool CheckForZeroSize;
17725     if (!getLangOpts().CPlusPlus) {
17726       CheckForZeroSize = true;
17727     } else {
17728       // For C++ filter out types that cannot be referenced in C code.
17729       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17730       CheckForZeroSize =
17731           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17732           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17733           CXXRecord->isCLike();
17734     }
17735     if (CheckForZeroSize) {
17736       bool ZeroSize = true;
17737       bool IsEmpty = true;
17738       unsigned NonBitFields = 0;
17739       for (RecordDecl::field_iterator I = Record->field_begin(),
17740                                       E = Record->field_end();
17741            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17742         IsEmpty = false;
17743         if (I->isUnnamedBitfield()) {
17744           if (!I->isZeroLengthBitField(Context))
17745             ZeroSize = false;
17746         } else {
17747           ++NonBitFields;
17748           QualType FieldType = I->getType();
17749           if (FieldType->isIncompleteType() ||
17750               !Context.getTypeSizeInChars(FieldType).isZero())
17751             ZeroSize = false;
17752         }
17753       }
17754 
17755       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17756       // allowed in C++, but warn if its declaration is inside
17757       // extern "C" block.
17758       if (ZeroSize) {
17759         Diag(RecLoc, getLangOpts().CPlusPlus ?
17760                          diag::warn_zero_size_struct_union_in_extern_c :
17761                          diag::warn_zero_size_struct_union_compat)
17762           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17763       }
17764 
17765       // Structs without named members are extension in C (C99 6.7.2.1p7),
17766       // but are accepted by GCC.
17767       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17768         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17769                                diag::ext_no_named_members_in_struct_union)
17770           << Record->isUnion();
17771       }
17772     }
17773   } else {
17774     ObjCIvarDecl **ClsFields =
17775       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17776     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17777       ID->setEndOfDefinitionLoc(RBrac);
17778       // Add ivar's to class's DeclContext.
17779       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17780         ClsFields[i]->setLexicalDeclContext(ID);
17781         ID->addDecl(ClsFields[i]);
17782       }
17783       // Must enforce the rule that ivars in the base classes may not be
17784       // duplicates.
17785       if (ID->getSuperClass())
17786         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17787     } else if (ObjCImplementationDecl *IMPDecl =
17788                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17789       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17790       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17791         // Ivar declared in @implementation never belongs to the implementation.
17792         // Only it is in implementation's lexical context.
17793         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17794       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17795       IMPDecl->setIvarLBraceLoc(LBrac);
17796       IMPDecl->setIvarRBraceLoc(RBrac);
17797     } else if (ObjCCategoryDecl *CDecl =
17798                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17799       // case of ivars in class extension; all other cases have been
17800       // reported as errors elsewhere.
17801       // FIXME. Class extension does not have a LocEnd field.
17802       // CDecl->setLocEnd(RBrac);
17803       // Add ivar's to class extension's DeclContext.
17804       // Diagnose redeclaration of private ivars.
17805       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17806       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17807         if (IDecl) {
17808           if (const ObjCIvarDecl *ClsIvar =
17809               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17810             Diag(ClsFields[i]->getLocation(),
17811                  diag::err_duplicate_ivar_declaration);
17812             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17813             continue;
17814           }
17815           for (const auto *Ext : IDecl->known_extensions()) {
17816             if (const ObjCIvarDecl *ClsExtIvar
17817                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17818               Diag(ClsFields[i]->getLocation(),
17819                    diag::err_duplicate_ivar_declaration);
17820               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17821               continue;
17822             }
17823           }
17824         }
17825         ClsFields[i]->setLexicalDeclContext(CDecl);
17826         CDecl->addDecl(ClsFields[i]);
17827       }
17828       CDecl->setIvarLBraceLoc(LBrac);
17829       CDecl->setIvarRBraceLoc(RBrac);
17830     }
17831   }
17832 }
17833 
17834 /// Determine whether the given integral value is representable within
17835 /// the given type T.
17836 static bool isRepresentableIntegerValue(ASTContext &Context,
17837                                         llvm::APSInt &Value,
17838                                         QualType T) {
17839   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17840          "Integral type required!");
17841   unsigned BitWidth = Context.getIntWidth(T);
17842 
17843   if (Value.isUnsigned() || Value.isNonNegative()) {
17844     if (T->isSignedIntegerOrEnumerationType())
17845       --BitWidth;
17846     return Value.getActiveBits() <= BitWidth;
17847   }
17848   return Value.getMinSignedBits() <= BitWidth;
17849 }
17850 
17851 // Given an integral type, return the next larger integral type
17852 // (or a NULL type of no such type exists).
17853 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17854   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17855   // enum checking below.
17856   assert((T->isIntegralType(Context) ||
17857          T->isEnumeralType()) && "Integral type required!");
17858   const unsigned NumTypes = 4;
17859   QualType SignedIntegralTypes[NumTypes] = {
17860     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17861   };
17862   QualType UnsignedIntegralTypes[NumTypes] = {
17863     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17864     Context.UnsignedLongLongTy
17865   };
17866 
17867   unsigned BitWidth = Context.getTypeSize(T);
17868   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17869                                                         : UnsignedIntegralTypes;
17870   for (unsigned I = 0; I != NumTypes; ++I)
17871     if (Context.getTypeSize(Types[I]) > BitWidth)
17872       return Types[I];
17873 
17874   return QualType();
17875 }
17876 
17877 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17878                                           EnumConstantDecl *LastEnumConst,
17879                                           SourceLocation IdLoc,
17880                                           IdentifierInfo *Id,
17881                                           Expr *Val) {
17882   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17883   llvm::APSInt EnumVal(IntWidth);
17884   QualType EltTy;
17885 
17886   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17887     Val = nullptr;
17888 
17889   if (Val)
17890     Val = DefaultLvalueConversion(Val).get();
17891 
17892   if (Val) {
17893     if (Enum->isDependentType() || Val->isTypeDependent() ||
17894         Val->containsErrors())
17895       EltTy = Context.DependentTy;
17896     else {
17897       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17898       // underlying type, but do allow it in all other contexts.
17899       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17900         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17901         // constant-expression in the enumerator-definition shall be a converted
17902         // constant expression of the underlying type.
17903         EltTy = Enum->getIntegerType();
17904         ExprResult Converted =
17905           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17906                                            CCEK_Enumerator);
17907         if (Converted.isInvalid())
17908           Val = nullptr;
17909         else
17910           Val = Converted.get();
17911       } else if (!Val->isValueDependent() &&
17912                  !(Val =
17913                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17914                            .get())) {
17915         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17916       } else {
17917         if (Enum->isComplete()) {
17918           EltTy = Enum->getIntegerType();
17919 
17920           // In Obj-C and Microsoft mode, require the enumeration value to be
17921           // representable in the underlying type of the enumeration. In C++11,
17922           // we perform a non-narrowing conversion as part of converted constant
17923           // expression checking.
17924           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17925             if (Context.getTargetInfo()
17926                     .getTriple()
17927                     .isWindowsMSVCEnvironment()) {
17928               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17929             } else {
17930               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17931             }
17932           }
17933 
17934           // Cast to the underlying type.
17935           Val = ImpCastExprToType(Val, EltTy,
17936                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17937                                                          : CK_IntegralCast)
17938                     .get();
17939         } else if (getLangOpts().CPlusPlus) {
17940           // C++11 [dcl.enum]p5:
17941           //   If the underlying type is not fixed, the type of each enumerator
17942           //   is the type of its initializing value:
17943           //     - If an initializer is specified for an enumerator, the
17944           //       initializing value has the same type as the expression.
17945           EltTy = Val->getType();
17946         } else {
17947           // C99 6.7.2.2p2:
17948           //   The expression that defines the value of an enumeration constant
17949           //   shall be an integer constant expression that has a value
17950           //   representable as an int.
17951 
17952           // Complain if the value is not representable in an int.
17953           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17954             Diag(IdLoc, diag::ext_enum_value_not_int)
17955               << toString(EnumVal, 10) << Val->getSourceRange()
17956               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17957           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17958             // Force the type of the expression to 'int'.
17959             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17960           }
17961           EltTy = Val->getType();
17962         }
17963       }
17964     }
17965   }
17966 
17967   if (!Val) {
17968     if (Enum->isDependentType())
17969       EltTy = Context.DependentTy;
17970     else if (!LastEnumConst) {
17971       // C++0x [dcl.enum]p5:
17972       //   If the underlying type is not fixed, the type of each enumerator
17973       //   is the type of its initializing value:
17974       //     - If no initializer is specified for the first enumerator, the
17975       //       initializing value has an unspecified integral type.
17976       //
17977       // GCC uses 'int' for its unspecified integral type, as does
17978       // C99 6.7.2.2p3.
17979       if (Enum->isFixed()) {
17980         EltTy = Enum->getIntegerType();
17981       }
17982       else {
17983         EltTy = Context.IntTy;
17984       }
17985     } else {
17986       // Assign the last value + 1.
17987       EnumVal = LastEnumConst->getInitVal();
17988       ++EnumVal;
17989       EltTy = LastEnumConst->getType();
17990 
17991       // Check for overflow on increment.
17992       if (EnumVal < LastEnumConst->getInitVal()) {
17993         // C++0x [dcl.enum]p5:
17994         //   If the underlying type is not fixed, the type of each enumerator
17995         //   is the type of its initializing value:
17996         //
17997         //     - Otherwise the type of the initializing value is the same as
17998         //       the type of the initializing value of the preceding enumerator
17999         //       unless the incremented value is not representable in that type,
18000         //       in which case the type is an unspecified integral type
18001         //       sufficient to contain the incremented value. If no such type
18002         //       exists, the program is ill-formed.
18003         QualType T = getNextLargerIntegralType(Context, EltTy);
18004         if (T.isNull() || Enum->isFixed()) {
18005           // There is no integral type larger enough to represent this
18006           // value. Complain, then allow the value to wrap around.
18007           EnumVal = LastEnumConst->getInitVal();
18008           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18009           ++EnumVal;
18010           if (Enum->isFixed())
18011             // When the underlying type is fixed, this is ill-formed.
18012             Diag(IdLoc, diag::err_enumerator_wrapped)
18013               << toString(EnumVal, 10)
18014               << EltTy;
18015           else
18016             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18017               << toString(EnumVal, 10);
18018         } else {
18019           EltTy = T;
18020         }
18021 
18022         // Retrieve the last enumerator's value, extent that type to the
18023         // type that is supposed to be large enough to represent the incremented
18024         // value, then increment.
18025         EnumVal = LastEnumConst->getInitVal();
18026         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18027         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18028         ++EnumVal;
18029 
18030         // If we're not in C++, diagnose the overflow of enumerator values,
18031         // which in C99 means that the enumerator value is not representable in
18032         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18033         // permits enumerator values that are representable in some larger
18034         // integral type.
18035         if (!getLangOpts().CPlusPlus && !T.isNull())
18036           Diag(IdLoc, diag::warn_enum_value_overflow);
18037       } else if (!getLangOpts().CPlusPlus &&
18038                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18039         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18040         Diag(IdLoc, diag::ext_enum_value_not_int)
18041           << toString(EnumVal, 10) << 1;
18042       }
18043     }
18044   }
18045 
18046   if (!EltTy->isDependentType()) {
18047     // Make the enumerator value match the signedness and size of the
18048     // enumerator's type.
18049     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18050     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18051   }
18052 
18053   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18054                                   Val, EnumVal);
18055 }
18056 
18057 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18058                                                 SourceLocation IILoc) {
18059   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18060       !getLangOpts().CPlusPlus)
18061     return SkipBodyInfo();
18062 
18063   // We have an anonymous enum definition. Look up the first enumerator to
18064   // determine if we should merge the definition with an existing one and
18065   // skip the body.
18066   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18067                                          forRedeclarationInCurContext());
18068   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18069   if (!PrevECD)
18070     return SkipBodyInfo();
18071 
18072   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18073   NamedDecl *Hidden;
18074   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18075     SkipBodyInfo Skip;
18076     Skip.Previous = Hidden;
18077     return Skip;
18078   }
18079 
18080   return SkipBodyInfo();
18081 }
18082 
18083 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18084                               SourceLocation IdLoc, IdentifierInfo *Id,
18085                               const ParsedAttributesView &Attrs,
18086                               SourceLocation EqualLoc, Expr *Val) {
18087   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18088   EnumConstantDecl *LastEnumConst =
18089     cast_or_null<EnumConstantDecl>(lastEnumConst);
18090 
18091   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18092   // we find one that is.
18093   S = getNonFieldDeclScope(S);
18094 
18095   // Verify that there isn't already something declared with this name in this
18096   // scope.
18097   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18098   LookupName(R, S);
18099   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18100 
18101   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18102     // Maybe we will complain about the shadowed template parameter.
18103     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18104     // Just pretend that we didn't see the previous declaration.
18105     PrevDecl = nullptr;
18106   }
18107 
18108   // C++ [class.mem]p15:
18109   // If T is the name of a class, then each of the following shall have a name
18110   // different from T:
18111   // - every enumerator of every member of class T that is an unscoped
18112   // enumerated type
18113   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18114     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18115                             DeclarationNameInfo(Id, IdLoc));
18116 
18117   EnumConstantDecl *New =
18118     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18119   if (!New)
18120     return nullptr;
18121 
18122   if (PrevDecl) {
18123     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18124       // Check for other kinds of shadowing not already handled.
18125       CheckShadow(New, PrevDecl, R);
18126     }
18127 
18128     // When in C++, we may get a TagDecl with the same name; in this case the
18129     // enum constant will 'hide' the tag.
18130     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18131            "Received TagDecl when not in C++!");
18132     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18133       if (isa<EnumConstantDecl>(PrevDecl))
18134         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18135       else
18136         Diag(IdLoc, diag::err_redefinition) << Id;
18137       notePreviousDefinition(PrevDecl, IdLoc);
18138       return nullptr;
18139     }
18140   }
18141 
18142   // Process attributes.
18143   ProcessDeclAttributeList(S, New, Attrs);
18144   AddPragmaAttributes(S, New);
18145 
18146   // Register this decl in the current scope stack.
18147   New->setAccess(TheEnumDecl->getAccess());
18148   PushOnScopeChains(New, S);
18149 
18150   ActOnDocumentableDecl(New);
18151 
18152   return New;
18153 }
18154 
18155 // Returns true when the enum initial expression does not trigger the
18156 // duplicate enum warning.  A few common cases are exempted as follows:
18157 // Element2 = Element1
18158 // Element2 = Element1 + 1
18159 // Element2 = Element1 - 1
18160 // Where Element2 and Element1 are from the same enum.
18161 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18162   Expr *InitExpr = ECD->getInitExpr();
18163   if (!InitExpr)
18164     return true;
18165   InitExpr = InitExpr->IgnoreImpCasts();
18166 
18167   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18168     if (!BO->isAdditiveOp())
18169       return true;
18170     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18171     if (!IL)
18172       return true;
18173     if (IL->getValue() != 1)
18174       return true;
18175 
18176     InitExpr = BO->getLHS();
18177   }
18178 
18179   // This checks if the elements are from the same enum.
18180   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18181   if (!DRE)
18182     return true;
18183 
18184   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18185   if (!EnumConstant)
18186     return true;
18187 
18188   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18189       Enum)
18190     return true;
18191 
18192   return false;
18193 }
18194 
18195 // Emits a warning when an element is implicitly set a value that
18196 // a previous element has already been set to.
18197 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18198                                         EnumDecl *Enum, QualType EnumType) {
18199   // Avoid anonymous enums
18200   if (!Enum->getIdentifier())
18201     return;
18202 
18203   // Only check for small enums.
18204   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18205     return;
18206 
18207   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18208     return;
18209 
18210   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18211   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18212 
18213   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18214 
18215   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18216   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18217 
18218   // Use int64_t as a key to avoid needing special handling for map keys.
18219   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18220     llvm::APSInt Val = D->getInitVal();
18221     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18222   };
18223 
18224   DuplicatesVector DupVector;
18225   ValueToVectorMap EnumMap;
18226 
18227   // Populate the EnumMap with all values represented by enum constants without
18228   // an initializer.
18229   for (auto *Element : Elements) {
18230     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18231 
18232     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18233     // this constant.  Skip this enum since it may be ill-formed.
18234     if (!ECD) {
18235       return;
18236     }
18237 
18238     // Constants with initalizers are handled in the next loop.
18239     if (ECD->getInitExpr())
18240       continue;
18241 
18242     // Duplicate values are handled in the next loop.
18243     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18244   }
18245 
18246   if (EnumMap.size() == 0)
18247     return;
18248 
18249   // Create vectors for any values that has duplicates.
18250   for (auto *Element : Elements) {
18251     // The last loop returned if any constant was null.
18252     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18253     if (!ValidDuplicateEnum(ECD, Enum))
18254       continue;
18255 
18256     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18257     if (Iter == EnumMap.end())
18258       continue;
18259 
18260     DeclOrVector& Entry = Iter->second;
18261     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18262       // Ensure constants are different.
18263       if (D == ECD)
18264         continue;
18265 
18266       // Create new vector and push values onto it.
18267       auto Vec = std::make_unique<ECDVector>();
18268       Vec->push_back(D);
18269       Vec->push_back(ECD);
18270 
18271       // Update entry to point to the duplicates vector.
18272       Entry = Vec.get();
18273 
18274       // Store the vector somewhere we can consult later for quick emission of
18275       // diagnostics.
18276       DupVector.emplace_back(std::move(Vec));
18277       continue;
18278     }
18279 
18280     ECDVector *Vec = Entry.get<ECDVector*>();
18281     // Make sure constants are not added more than once.
18282     if (*Vec->begin() == ECD)
18283       continue;
18284 
18285     Vec->push_back(ECD);
18286   }
18287 
18288   // Emit diagnostics.
18289   for (const auto &Vec : DupVector) {
18290     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18291 
18292     // Emit warning for one enum constant.
18293     auto *FirstECD = Vec->front();
18294     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18295       << FirstECD << toString(FirstECD->getInitVal(), 10)
18296       << FirstECD->getSourceRange();
18297 
18298     // Emit one note for each of the remaining enum constants with
18299     // the same value.
18300     for (auto *ECD : llvm::drop_begin(*Vec))
18301       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18302         << ECD << toString(ECD->getInitVal(), 10)
18303         << ECD->getSourceRange();
18304   }
18305 }
18306 
18307 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18308                              bool AllowMask) const {
18309   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18310   assert(ED->isCompleteDefinition() && "expected enum definition");
18311 
18312   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18313   llvm::APInt &FlagBits = R.first->second;
18314 
18315   if (R.second) {
18316     for (auto *E : ED->enumerators()) {
18317       const auto &EVal = E->getInitVal();
18318       // Only single-bit enumerators introduce new flag values.
18319       if (EVal.isPowerOf2())
18320         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18321     }
18322   }
18323 
18324   // A value is in a flag enum if either its bits are a subset of the enum's
18325   // flag bits (the first condition) or we are allowing masks and the same is
18326   // true of its complement (the second condition). When masks are allowed, we
18327   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18328   //
18329   // While it's true that any value could be used as a mask, the assumption is
18330   // that a mask will have all of the insignificant bits set. Anything else is
18331   // likely a logic error.
18332   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18333   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18334 }
18335 
18336 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18337                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18338                          const ParsedAttributesView &Attrs) {
18339   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18340   QualType EnumType = Context.getTypeDeclType(Enum);
18341 
18342   ProcessDeclAttributeList(S, Enum, Attrs);
18343 
18344   if (Enum->isDependentType()) {
18345     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18346       EnumConstantDecl *ECD =
18347         cast_or_null<EnumConstantDecl>(Elements[i]);
18348       if (!ECD) continue;
18349 
18350       ECD->setType(EnumType);
18351     }
18352 
18353     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18354     return;
18355   }
18356 
18357   // TODO: If the result value doesn't fit in an int, it must be a long or long
18358   // long value.  ISO C does not support this, but GCC does as an extension,
18359   // emit a warning.
18360   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18361   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18362   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18363 
18364   // Verify that all the values are okay, compute the size of the values, and
18365   // reverse the list.
18366   unsigned NumNegativeBits = 0;
18367   unsigned NumPositiveBits = 0;
18368 
18369   // Keep track of whether all elements have type int.
18370   bool AllElementsInt = true;
18371 
18372   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18373     EnumConstantDecl *ECD =
18374       cast_or_null<EnumConstantDecl>(Elements[i]);
18375     if (!ECD) continue;  // Already issued a diagnostic.
18376 
18377     const llvm::APSInt &InitVal = ECD->getInitVal();
18378 
18379     // Keep track of the size of positive and negative values.
18380     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18381       NumPositiveBits = std::max(NumPositiveBits,
18382                                  (unsigned)InitVal.getActiveBits());
18383     else
18384       NumNegativeBits = std::max(NumNegativeBits,
18385                                  (unsigned)InitVal.getMinSignedBits());
18386 
18387     // Keep track of whether every enum element has type int (very common).
18388     if (AllElementsInt)
18389       AllElementsInt = ECD->getType() == Context.IntTy;
18390   }
18391 
18392   // Figure out the type that should be used for this enum.
18393   QualType BestType;
18394   unsigned BestWidth;
18395 
18396   // C++0x N3000 [conv.prom]p3:
18397   //   An rvalue of an unscoped enumeration type whose underlying
18398   //   type is not fixed can be converted to an rvalue of the first
18399   //   of the following types that can represent all the values of
18400   //   the enumeration: int, unsigned int, long int, unsigned long
18401   //   int, long long int, or unsigned long long int.
18402   // C99 6.4.4.3p2:
18403   //   An identifier declared as an enumeration constant has type int.
18404   // The C99 rule is modified by a gcc extension
18405   QualType BestPromotionType;
18406 
18407   bool Packed = Enum->hasAttr<PackedAttr>();
18408   // -fshort-enums is the equivalent to specifying the packed attribute on all
18409   // enum definitions.
18410   if (LangOpts.ShortEnums)
18411     Packed = true;
18412 
18413   // If the enum already has a type because it is fixed or dictated by the
18414   // target, promote that type instead of analyzing the enumerators.
18415   if (Enum->isComplete()) {
18416     BestType = Enum->getIntegerType();
18417     if (BestType->isPromotableIntegerType())
18418       BestPromotionType = Context.getPromotedIntegerType(BestType);
18419     else
18420       BestPromotionType = BestType;
18421 
18422     BestWidth = Context.getIntWidth(BestType);
18423   }
18424   else if (NumNegativeBits) {
18425     // If there is a negative value, figure out the smallest integer type (of
18426     // int/long/longlong) that fits.
18427     // If it's packed, check also if it fits a char or a short.
18428     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18429       BestType = Context.SignedCharTy;
18430       BestWidth = CharWidth;
18431     } else if (Packed && NumNegativeBits <= ShortWidth &&
18432                NumPositiveBits < ShortWidth) {
18433       BestType = Context.ShortTy;
18434       BestWidth = ShortWidth;
18435     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18436       BestType = Context.IntTy;
18437       BestWidth = IntWidth;
18438     } else {
18439       BestWidth = Context.getTargetInfo().getLongWidth();
18440 
18441       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18442         BestType = Context.LongTy;
18443       } else {
18444         BestWidth = Context.getTargetInfo().getLongLongWidth();
18445 
18446         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18447           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18448         BestType = Context.LongLongTy;
18449       }
18450     }
18451     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18452   } else {
18453     // If there is no negative value, figure out the smallest type that fits
18454     // all of the enumerator values.
18455     // If it's packed, check also if it fits a char or a short.
18456     if (Packed && NumPositiveBits <= CharWidth) {
18457       BestType = Context.UnsignedCharTy;
18458       BestPromotionType = Context.IntTy;
18459       BestWidth = CharWidth;
18460     } else if (Packed && NumPositiveBits <= ShortWidth) {
18461       BestType = Context.UnsignedShortTy;
18462       BestPromotionType = Context.IntTy;
18463       BestWidth = ShortWidth;
18464     } else if (NumPositiveBits <= IntWidth) {
18465       BestType = Context.UnsignedIntTy;
18466       BestWidth = IntWidth;
18467       BestPromotionType
18468         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18469                            ? Context.UnsignedIntTy : Context.IntTy;
18470     } else if (NumPositiveBits <=
18471                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18472       BestType = Context.UnsignedLongTy;
18473       BestPromotionType
18474         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18475                            ? Context.UnsignedLongTy : Context.LongTy;
18476     } else {
18477       BestWidth = Context.getTargetInfo().getLongLongWidth();
18478       assert(NumPositiveBits <= BestWidth &&
18479              "How could an initializer get larger than ULL?");
18480       BestType = Context.UnsignedLongLongTy;
18481       BestPromotionType
18482         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18483                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18484     }
18485   }
18486 
18487   // Loop over all of the enumerator constants, changing their types to match
18488   // the type of the enum if needed.
18489   for (auto *D : Elements) {
18490     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18491     if (!ECD) continue;  // Already issued a diagnostic.
18492 
18493     // Standard C says the enumerators have int type, but we allow, as an
18494     // extension, the enumerators to be larger than int size.  If each
18495     // enumerator value fits in an int, type it as an int, otherwise type it the
18496     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18497     // that X has type 'int', not 'unsigned'.
18498 
18499     // Determine whether the value fits into an int.
18500     llvm::APSInt InitVal = ECD->getInitVal();
18501 
18502     // If it fits into an integer type, force it.  Otherwise force it to match
18503     // the enum decl type.
18504     QualType NewTy;
18505     unsigned NewWidth;
18506     bool NewSign;
18507     if (!getLangOpts().CPlusPlus &&
18508         !Enum->isFixed() &&
18509         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18510       NewTy = Context.IntTy;
18511       NewWidth = IntWidth;
18512       NewSign = true;
18513     } else if (ECD->getType() == BestType) {
18514       // Already the right type!
18515       if (getLangOpts().CPlusPlus)
18516         // C++ [dcl.enum]p4: Following the closing brace of an
18517         // enum-specifier, each enumerator has the type of its
18518         // enumeration.
18519         ECD->setType(EnumType);
18520       continue;
18521     } else {
18522       NewTy = BestType;
18523       NewWidth = BestWidth;
18524       NewSign = BestType->isSignedIntegerOrEnumerationType();
18525     }
18526 
18527     // Adjust the APSInt value.
18528     InitVal = InitVal.extOrTrunc(NewWidth);
18529     InitVal.setIsSigned(NewSign);
18530     ECD->setInitVal(InitVal);
18531 
18532     // Adjust the Expr initializer and type.
18533     if (ECD->getInitExpr() &&
18534         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18535       ECD->setInitExpr(ImplicitCastExpr::Create(
18536           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18537           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18538     if (getLangOpts().CPlusPlus)
18539       // C++ [dcl.enum]p4: Following the closing brace of an
18540       // enum-specifier, each enumerator has the type of its
18541       // enumeration.
18542       ECD->setType(EnumType);
18543     else
18544       ECD->setType(NewTy);
18545   }
18546 
18547   Enum->completeDefinition(BestType, BestPromotionType,
18548                            NumPositiveBits, NumNegativeBits);
18549 
18550   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18551 
18552   if (Enum->isClosedFlag()) {
18553     for (Decl *D : Elements) {
18554       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18555       if (!ECD) continue;  // Already issued a diagnostic.
18556 
18557       llvm::APSInt InitVal = ECD->getInitVal();
18558       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18559           !IsValueInFlagEnum(Enum, InitVal, true))
18560         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18561           << ECD << Enum;
18562     }
18563   }
18564 
18565   // Now that the enum type is defined, ensure it's not been underaligned.
18566   if (Enum->hasAttrs())
18567     CheckAlignasUnderalignment(Enum);
18568 }
18569 
18570 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18571                                   SourceLocation StartLoc,
18572                                   SourceLocation EndLoc) {
18573   StringLiteral *AsmString = cast<StringLiteral>(expr);
18574 
18575   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18576                                                    AsmString, StartLoc,
18577                                                    EndLoc);
18578   CurContext->addDecl(New);
18579   return New;
18580 }
18581 
18582 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18583                                       IdentifierInfo* AliasName,
18584                                       SourceLocation PragmaLoc,
18585                                       SourceLocation NameLoc,
18586                                       SourceLocation AliasNameLoc) {
18587   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18588                                          LookupOrdinaryName);
18589   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18590                            AttributeCommonInfo::AS_Pragma);
18591   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18592       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18593 
18594   // If a declaration that:
18595   // 1) declares a function or a variable
18596   // 2) has external linkage
18597   // already exists, add a label attribute to it.
18598   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18599     if (isDeclExternC(PrevDecl))
18600       PrevDecl->addAttr(Attr);
18601     else
18602       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18603           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18604   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18605   } else
18606     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18607 }
18608 
18609 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18610                              SourceLocation PragmaLoc,
18611                              SourceLocation NameLoc) {
18612   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18613 
18614   if (PrevDecl) {
18615     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18616   } else {
18617     (void)WeakUndeclaredIdentifiers.insert(
18618       std::pair<IdentifierInfo*,WeakInfo>
18619         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18620   }
18621 }
18622 
18623 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18624                                 IdentifierInfo* AliasName,
18625                                 SourceLocation PragmaLoc,
18626                                 SourceLocation NameLoc,
18627                                 SourceLocation AliasNameLoc) {
18628   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18629                                     LookupOrdinaryName);
18630   WeakInfo W = WeakInfo(Name, NameLoc);
18631 
18632   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18633     if (!PrevDecl->hasAttr<AliasAttr>())
18634       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18635         DeclApplyPragmaWeak(TUScope, ND, W);
18636   } else {
18637     (void)WeakUndeclaredIdentifiers.insert(
18638       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18639   }
18640 }
18641 
18642 Decl *Sema::getObjCDeclContext() const {
18643   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18644 }
18645 
18646 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18647                                                      bool Final) {
18648   assert(FD && "Expected non-null FunctionDecl");
18649 
18650   // SYCL functions can be template, so we check if they have appropriate
18651   // attribute prior to checking if it is a template.
18652   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18653     return FunctionEmissionStatus::Emitted;
18654 
18655   // Templates are emitted when they're instantiated.
18656   if (FD->isDependentContext())
18657     return FunctionEmissionStatus::TemplateDiscarded;
18658 
18659   // Check whether this function is an externally visible definition.
18660   auto IsEmittedForExternalSymbol = [this, FD]() {
18661     // We have to check the GVA linkage of the function's *definition* -- if we
18662     // only have a declaration, we don't know whether or not the function will
18663     // be emitted, because (say) the definition could include "inline".
18664     FunctionDecl *Def = FD->getDefinition();
18665 
18666     return Def && !isDiscardableGVALinkage(
18667                       getASTContext().GetGVALinkageForFunction(Def));
18668   };
18669 
18670   if (LangOpts.OpenMPIsDevice) {
18671     // In OpenMP device mode we will not emit host only functions, or functions
18672     // we don't need due to their linkage.
18673     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18674         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18675     // DevTy may be changed later by
18676     //  #pragma omp declare target to(*) device_type(*).
18677     // Therefore DevTy having no value does not imply host. The emission status
18678     // will be checked again at the end of compilation unit with Final = true.
18679     if (DevTy.hasValue())
18680       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18681         return FunctionEmissionStatus::OMPDiscarded;
18682     // If we have an explicit value for the device type, or we are in a target
18683     // declare context, we need to emit all extern and used symbols.
18684     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18685       if (IsEmittedForExternalSymbol())
18686         return FunctionEmissionStatus::Emitted;
18687     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18688     // we'll omit it.
18689     if (Final)
18690       return FunctionEmissionStatus::OMPDiscarded;
18691   } else if (LangOpts.OpenMP > 45) {
18692     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18693     // function. In 5.0, no_host was introduced which might cause a function to
18694     // be ommitted.
18695     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18696         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18697     if (DevTy.hasValue())
18698       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18699         return FunctionEmissionStatus::OMPDiscarded;
18700   }
18701 
18702   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18703     return FunctionEmissionStatus::Emitted;
18704 
18705   if (LangOpts.CUDA) {
18706     // When compiling for device, host functions are never emitted.  Similarly,
18707     // when compiling for host, device and global functions are never emitted.
18708     // (Technically, we do emit a host-side stub for global functions, but this
18709     // doesn't count for our purposes here.)
18710     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18711     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18712       return FunctionEmissionStatus::CUDADiscarded;
18713     if (!LangOpts.CUDAIsDevice &&
18714         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18715       return FunctionEmissionStatus::CUDADiscarded;
18716 
18717     if (IsEmittedForExternalSymbol())
18718       return FunctionEmissionStatus::Emitted;
18719   }
18720 
18721   // Otherwise, the function is known-emitted if it's in our set of
18722   // known-emitted functions.
18723   return FunctionEmissionStatus::Unknown;
18724 }
18725 
18726 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18727   // Host-side references to a __global__ function refer to the stub, so the
18728   // function itself is never emitted and therefore should not be marked.
18729   // If we have host fn calls kernel fn calls host+device, the HD function
18730   // does not get instantiated on the host. We model this by omitting at the
18731   // call to the kernel from the callgraph. This ensures that, when compiling
18732   // for host, only HD functions actually called from the host get marked as
18733   // known-emitted.
18734   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18735          IdentifyCUDATarget(Callee) == CFT_Global;
18736 }
18737