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 overloading is allowed for a new function
1464 /// declaration considering prior declarations of the same name.
1465 ///
1466 /// This routine determines whether overloading is possible, not
1467 /// whether a new declaration actually overloads a previous one.
1468 /// It will return true in C++ (where overloads are alway permitted)
1469 /// or, as a C extension, when either the new declaration or a
1470 /// previous one is declared with the 'overloadable' attribute.
1471 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1472                                        ASTContext &Context,
1473                                        const FunctionDecl *New) {
1474   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1475     return true;
1476 
1477   // Multiversion function declarations are not overloads in the
1478   // usual sense of that term, but lookup will report that an
1479   // overload set was found if more than one multiversion function
1480   // declaration is present for the same name. It is therefore
1481   // inadequate to assume that some prior declaration(s) had
1482   // the overloadable attribute; checking is required. Since one
1483   // declaration is permitted to omit the attribute, it is necessary
1484   // to check at least two; hence the 'any_of' check below. Note that
1485   // the overloadable attribute is implicitly added to declarations
1486   // that were required to have it but did not.
1487   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1488     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1489       return ND->hasAttr<OverloadableAttr>();
1490     });
1491   } else if (Previous.getResultKind() == LookupResult::Found)
1492     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1493 
1494   return false;
1495 }
1496 
1497 /// Add this decl to the scope shadowed decl chains.
1498 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1499   // Move up the scope chain until we find the nearest enclosing
1500   // non-transparent context. The declaration will be introduced into this
1501   // scope.
1502   while (S->getEntity() && S->getEntity()->isTransparentContext())
1503     S = S->getParent();
1504 
1505   // Add scoped declarations into their context, so that they can be
1506   // found later. Declarations without a context won't be inserted
1507   // into any context.
1508   if (AddToContext)
1509     CurContext->addDecl(D);
1510 
1511   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1512   // are function-local declarations.
1513   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1514     return;
1515 
1516   // Template instantiations should also not be pushed into scope.
1517   if (isa<FunctionDecl>(D) &&
1518       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1519     return;
1520 
1521   // If this replaces anything in the current scope,
1522   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1523                                IEnd = IdResolver.end();
1524   for (; I != IEnd; ++I) {
1525     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1526       S->RemoveDecl(*I);
1527       IdResolver.RemoveDecl(*I);
1528 
1529       // Should only need to replace one decl.
1530       break;
1531     }
1532   }
1533 
1534   S->AddDecl(D);
1535 
1536   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1537     // Implicitly-generated labels may end up getting generated in an order that
1538     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1539     // the label at the appropriate place in the identifier chain.
1540     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1541       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1542       if (IDC == CurContext) {
1543         if (!S->isDeclScope(*I))
1544           continue;
1545       } else if (IDC->Encloses(CurContext))
1546         break;
1547     }
1548 
1549     IdResolver.InsertDeclAfter(I, D);
1550   } else {
1551     IdResolver.AddDecl(D);
1552   }
1553   warnOnReservedIdentifier(D);
1554 }
1555 
1556 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1557                          bool AllowInlineNamespace) {
1558   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1559 }
1560 
1561 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1562   DeclContext *TargetDC = DC->getPrimaryContext();
1563   do {
1564     if (DeclContext *ScopeDC = S->getEntity())
1565       if (ScopeDC->getPrimaryContext() == TargetDC)
1566         return S;
1567   } while ((S = S->getParent()));
1568 
1569   return nullptr;
1570 }
1571 
1572 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1573                                             DeclContext*,
1574                                             ASTContext&);
1575 
1576 /// Filters out lookup results that don't fall within the given scope
1577 /// as determined by isDeclInScope.
1578 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1579                                 bool ConsiderLinkage,
1580                                 bool AllowInlineNamespace) {
1581   LookupResult::Filter F = R.makeFilter();
1582   while (F.hasNext()) {
1583     NamedDecl *D = F.next();
1584 
1585     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1586       continue;
1587 
1588     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1589       continue;
1590 
1591     F.erase();
1592   }
1593 
1594   F.done();
1595 }
1596 
1597 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1598 /// have compatible owning modules.
1599 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1600   // [module.interface]p7:
1601   // A declaration is attached to a module as follows:
1602   // - If the declaration is a non-dependent friend declaration that nominates a
1603   // function with a declarator-id that is a qualified-id or template-id or that
1604   // nominates a class other than with an elaborated-type-specifier with neither
1605   // a nested-name-specifier nor a simple-template-id, it is attached to the
1606   // module to which the friend is attached ([basic.link]).
1607   if (New->getFriendObjectKind() &&
1608       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1609     New->setLocalOwningModule(Old->getOwningModule());
1610     makeMergedDefinitionVisible(New);
1611     return false;
1612   }
1613 
1614   Module *NewM = New->getOwningModule();
1615   Module *OldM = Old->getOwningModule();
1616 
1617   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1618     NewM = NewM->Parent;
1619   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1620     OldM = OldM->Parent;
1621 
1622   // If we have a decl in a module partition, it is part of the containing
1623   // module (which is the only thing that can be importing it).
1624   if (NewM && OldM &&
1625       (OldM->Kind == Module::ModulePartitionInterface ||
1626        OldM->Kind == Module::ModulePartitionImplementation)) {
1627     return false;
1628   }
1629 
1630   if (NewM == OldM)
1631     return false;
1632 
1633   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1634   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1635   if (NewIsModuleInterface || OldIsModuleInterface) {
1636     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1637     //   if a declaration of D [...] appears in the purview of a module, all
1638     //   other such declarations shall appear in the purview of the same module
1639     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1640       << New
1641       << NewIsModuleInterface
1642       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1643       << OldIsModuleInterface
1644       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1645     Diag(Old->getLocation(), diag::note_previous_declaration);
1646     New->setInvalidDecl();
1647     return true;
1648   }
1649 
1650   return false;
1651 }
1652 
1653 // [module.interface]p6:
1654 // A redeclaration of an entity X is implicitly exported if X was introduced by
1655 // an exported declaration; otherwise it shall not be exported.
1656 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1657   // [module.interface]p1:
1658   // An export-declaration shall inhabit a namespace scope.
1659   //
1660   // So it is meaningless to talk about redeclaration which is not at namespace
1661   // scope.
1662   if (!New->getLexicalDeclContext()
1663            ->getNonTransparentContext()
1664            ->isFileContext() ||
1665       !Old->getLexicalDeclContext()
1666            ->getNonTransparentContext()
1667            ->isFileContext())
1668     return false;
1669 
1670   bool IsNewExported = New->isInExportDeclContext();
1671   bool IsOldExported = Old->isInExportDeclContext();
1672 
1673   // It should be irrevelant if both of them are not exported.
1674   if (!IsNewExported && !IsOldExported)
1675     return false;
1676 
1677   if (IsOldExported)
1678     return false;
1679 
1680   assert(IsNewExported);
1681 
1682   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New;
1683   Diag(Old->getLocation(), diag::note_previous_declaration);
1684   return true;
1685 }
1686 
1687 // A wrapper function for checking the semantic restrictions of
1688 // a redeclaration within a module.
1689 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1690   if (CheckRedeclarationModuleOwnership(New, Old))
1691     return true;
1692 
1693   if (CheckRedeclarationExported(New, Old))
1694     return true;
1695 
1696   return false;
1697 }
1698 
1699 static bool isUsingDecl(NamedDecl *D) {
1700   return isa<UsingShadowDecl>(D) ||
1701          isa<UnresolvedUsingTypenameDecl>(D) ||
1702          isa<UnresolvedUsingValueDecl>(D);
1703 }
1704 
1705 /// Removes using shadow declarations from the lookup results.
1706 static void RemoveUsingDecls(LookupResult &R) {
1707   LookupResult::Filter F = R.makeFilter();
1708   while (F.hasNext())
1709     if (isUsingDecl(F.next()))
1710       F.erase();
1711 
1712   F.done();
1713 }
1714 
1715 /// Check for this common pattern:
1716 /// @code
1717 /// class S {
1718 ///   S(const S&); // DO NOT IMPLEMENT
1719 ///   void operator=(const S&); // DO NOT IMPLEMENT
1720 /// };
1721 /// @endcode
1722 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1723   // FIXME: Should check for private access too but access is set after we get
1724   // the decl here.
1725   if (D->doesThisDeclarationHaveABody())
1726     return false;
1727 
1728   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1729     return CD->isCopyConstructor();
1730   return D->isCopyAssignmentOperator();
1731 }
1732 
1733 // We need this to handle
1734 //
1735 // typedef struct {
1736 //   void *foo() { return 0; }
1737 // } A;
1738 //
1739 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1740 // for example. If 'A', foo will have external linkage. If we have '*A',
1741 // foo will have no linkage. Since we can't know until we get to the end
1742 // of the typedef, this function finds out if D might have non-external linkage.
1743 // Callers should verify at the end of the TU if it D has external linkage or
1744 // not.
1745 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1746   const DeclContext *DC = D->getDeclContext();
1747   while (!DC->isTranslationUnit()) {
1748     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1749       if (!RD->hasNameForLinkage())
1750         return true;
1751     }
1752     DC = DC->getParent();
1753   }
1754 
1755   return !D->isExternallyVisible();
1756 }
1757 
1758 // FIXME: This needs to be refactored; some other isInMainFile users want
1759 // these semantics.
1760 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1761   if (S.TUKind != TU_Complete)
1762     return false;
1763   return S.SourceMgr.isInMainFile(Loc);
1764 }
1765 
1766 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1767   assert(D);
1768 
1769   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1770     return false;
1771 
1772   // Ignore all entities declared within templates, and out-of-line definitions
1773   // of members of class templates.
1774   if (D->getDeclContext()->isDependentContext() ||
1775       D->getLexicalDeclContext()->isDependentContext())
1776     return false;
1777 
1778   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1779     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1780       return false;
1781     // A non-out-of-line declaration of a member specialization was implicitly
1782     // instantiated; it's the out-of-line declaration that we're interested in.
1783     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1784         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1785       return false;
1786 
1787     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1788       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1789         return false;
1790     } else {
1791       // 'static inline' functions are defined in headers; don't warn.
1792       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1793         return false;
1794     }
1795 
1796     if (FD->doesThisDeclarationHaveABody() &&
1797         Context.DeclMustBeEmitted(FD))
1798       return false;
1799   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800     // Constants and utility variables are defined in headers with internal
1801     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1802     // like "inline".)
1803     if (!isMainFileLoc(*this, VD->getLocation()))
1804       return false;
1805 
1806     if (Context.DeclMustBeEmitted(VD))
1807       return false;
1808 
1809     if (VD->isStaticDataMember() &&
1810         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1811       return false;
1812     if (VD->isStaticDataMember() &&
1813         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1814         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1815       return false;
1816 
1817     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1818       return false;
1819   } else {
1820     return false;
1821   }
1822 
1823   // Only warn for unused decls internal to the translation unit.
1824   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1825   // for inline functions defined in the main source file, for instance.
1826   return mightHaveNonExternalLinkage(D);
1827 }
1828 
1829 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1830   if (!D)
1831     return;
1832 
1833   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1834     const FunctionDecl *First = FD->getFirstDecl();
1835     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1836       return; // First should already be in the vector.
1837   }
1838 
1839   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1840     const VarDecl *First = VD->getFirstDecl();
1841     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1842       return; // First should already be in the vector.
1843   }
1844 
1845   if (ShouldWarnIfUnusedFileScopedDecl(D))
1846     UnusedFileScopedDecls.push_back(D);
1847 }
1848 
1849 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1850   if (D->isInvalidDecl())
1851     return false;
1852 
1853   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1854     // For a decomposition declaration, warn if none of the bindings are
1855     // referenced, instead of if the variable itself is referenced (which
1856     // it is, by the bindings' expressions).
1857     for (auto *BD : DD->bindings())
1858       if (BD->isReferenced())
1859         return false;
1860   } else if (!D->getDeclName()) {
1861     return false;
1862   } else if (D->isReferenced() || D->isUsed()) {
1863     return false;
1864   }
1865 
1866   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1867     return false;
1868 
1869   if (isa<LabelDecl>(D))
1870     return true;
1871 
1872   // Except for labels, we only care about unused decls that are local to
1873   // functions.
1874   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1875   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1876     // For dependent types, the diagnostic is deferred.
1877     WithinFunction =
1878         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1879   if (!WithinFunction)
1880     return false;
1881 
1882   if (isa<TypedefNameDecl>(D))
1883     return true;
1884 
1885   // White-list anything that isn't a local variable.
1886   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1887     return false;
1888 
1889   // Types of valid local variables should be complete, so this should succeed.
1890   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1891 
1892     // White-list anything with an __attribute__((unused)) type.
1893     const auto *Ty = VD->getType().getTypePtr();
1894 
1895     // Only look at the outermost level of typedef.
1896     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1897       if (TT->getDecl()->hasAttr<UnusedAttr>())
1898         return false;
1899     }
1900 
1901     // If we failed to complete the type for some reason, or if the type is
1902     // dependent, don't diagnose the variable.
1903     if (Ty->isIncompleteType() || Ty->isDependentType())
1904       return false;
1905 
1906     // Look at the element type to ensure that the warning behaviour is
1907     // consistent for both scalars and arrays.
1908     Ty = Ty->getBaseElementTypeUnsafe();
1909 
1910     if (const TagType *TT = Ty->getAs<TagType>()) {
1911       const TagDecl *Tag = TT->getDecl();
1912       if (Tag->hasAttr<UnusedAttr>())
1913         return false;
1914 
1915       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1916         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1917           return false;
1918 
1919         if (const Expr *Init = VD->getInit()) {
1920           if (const ExprWithCleanups *Cleanups =
1921                   dyn_cast<ExprWithCleanups>(Init))
1922             Init = Cleanups->getSubExpr();
1923           const CXXConstructExpr *Construct =
1924             dyn_cast<CXXConstructExpr>(Init);
1925           if (Construct && !Construct->isElidable()) {
1926             CXXConstructorDecl *CD = Construct->getConstructor();
1927             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1928                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1929               return false;
1930           }
1931 
1932           // Suppress the warning if we don't know how this is constructed, and
1933           // it could possibly be non-trivial constructor.
1934           if (Init->isTypeDependent())
1935             for (const CXXConstructorDecl *Ctor : RD->ctors())
1936               if (!Ctor->isTrivial())
1937                 return false;
1938         }
1939       }
1940     }
1941 
1942     // TODO: __attribute__((unused)) templates?
1943   }
1944 
1945   return true;
1946 }
1947 
1948 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1949                                      FixItHint &Hint) {
1950   if (isa<LabelDecl>(D)) {
1951     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1952         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1953         true);
1954     if (AfterColon.isInvalid())
1955       return;
1956     Hint = FixItHint::CreateRemoval(
1957         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1958   }
1959 }
1960 
1961 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1962   if (D->getTypeForDecl()->isDependentType())
1963     return;
1964 
1965   for (auto *TmpD : D->decls()) {
1966     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1967       DiagnoseUnusedDecl(T);
1968     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1969       DiagnoseUnusedNestedTypedefs(R);
1970   }
1971 }
1972 
1973 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1974 /// unless they are marked attr(unused).
1975 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1976   if (!ShouldDiagnoseUnusedDecl(D))
1977     return;
1978 
1979   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1980     // typedefs can be referenced later on, so the diagnostics are emitted
1981     // at end-of-translation-unit.
1982     UnusedLocalTypedefNameCandidates.insert(TD);
1983     return;
1984   }
1985 
1986   FixItHint Hint;
1987   GenerateFixForUnusedDecl(D, Context, Hint);
1988 
1989   unsigned DiagID;
1990   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1991     DiagID = diag::warn_unused_exception_param;
1992   else if (isa<LabelDecl>(D))
1993     DiagID = diag::warn_unused_label;
1994   else
1995     DiagID = diag::warn_unused_variable;
1996 
1997   Diag(D->getLocation(), DiagID) << D << Hint;
1998 }
1999 
2000 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2001   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2002   // it's not really unused.
2003   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2004       VD->hasAttr<CleanupAttr>())
2005     return;
2006 
2007   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2008 
2009   if (Ty->isReferenceType() || Ty->isDependentType())
2010     return;
2011 
2012   if (const TagType *TT = Ty->getAs<TagType>()) {
2013     const TagDecl *Tag = TT->getDecl();
2014     if (Tag->hasAttr<UnusedAttr>())
2015       return;
2016     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2017     // mimic gcc's behavior.
2018     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2019       if (!RD->hasAttr<WarnUnusedAttr>())
2020         return;
2021     }
2022   }
2023 
2024   // Don't warn about __block Objective-C pointer variables, as they might
2025   // be assigned in the block but not used elsewhere for the purpose of lifetime
2026   // extension.
2027   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2028     return;
2029 
2030   // Don't warn about Objective-C pointer variables with precise lifetime
2031   // semantics; they can be used to ensure ARC releases the object at a known
2032   // time, which may mean assignment but no other references.
2033   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2034     return;
2035 
2036   auto iter = RefsMinusAssignments.find(VD);
2037   if (iter == RefsMinusAssignments.end())
2038     return;
2039 
2040   assert(iter->getSecond() >= 0 &&
2041          "Found a negative number of references to a VarDecl");
2042   if (iter->getSecond() != 0)
2043     return;
2044   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2045                                          : diag::warn_unused_but_set_variable;
2046   Diag(VD->getLocation(), DiagID) << VD;
2047 }
2048 
2049 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2050   // Verify that we have no forward references left.  If so, there was a goto
2051   // or address of a label taken, but no definition of it.  Label fwd
2052   // definitions are indicated with a null substmt which is also not a resolved
2053   // MS inline assembly label name.
2054   bool Diagnose = false;
2055   if (L->isMSAsmLabel())
2056     Diagnose = !L->isResolvedMSAsmLabel();
2057   else
2058     Diagnose = L->getStmt() == nullptr;
2059   if (Diagnose)
2060     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2061 }
2062 
2063 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2064   S->mergeNRVOIntoParent();
2065 
2066   if (S->decl_empty()) return;
2067   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2068          "Scope shouldn't contain decls!");
2069 
2070   for (auto *TmpD : S->decls()) {
2071     assert(TmpD && "This decl didn't get pushed??");
2072 
2073     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2074     NamedDecl *D = cast<NamedDecl>(TmpD);
2075 
2076     // Diagnose unused variables in this scope.
2077     if (!S->hasUnrecoverableErrorOccurred()) {
2078       DiagnoseUnusedDecl(D);
2079       if (const auto *RD = dyn_cast<RecordDecl>(D))
2080         DiagnoseUnusedNestedTypedefs(RD);
2081       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2082         DiagnoseUnusedButSetDecl(VD);
2083         RefsMinusAssignments.erase(VD);
2084       }
2085     }
2086 
2087     if (!D->getDeclName()) continue;
2088 
2089     // If this was a forward reference to a label, verify it was defined.
2090     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2091       CheckPoppedLabel(LD, *this);
2092 
2093     // Remove this name from our lexical scope, and warn on it if we haven't
2094     // already.
2095     IdResolver.RemoveDecl(D);
2096     auto ShadowI = ShadowingDecls.find(D);
2097     if (ShadowI != ShadowingDecls.end()) {
2098       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2099         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2100             << D << FD << FD->getParent();
2101         Diag(FD->getLocation(), diag::note_previous_declaration);
2102       }
2103       ShadowingDecls.erase(ShadowI);
2104     }
2105   }
2106 }
2107 
2108 /// Look for an Objective-C class in the translation unit.
2109 ///
2110 /// \param Id The name of the Objective-C class we're looking for. If
2111 /// typo-correction fixes this name, the Id will be updated
2112 /// to the fixed name.
2113 ///
2114 /// \param IdLoc The location of the name in the translation unit.
2115 ///
2116 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2117 /// if there is no class with the given name.
2118 ///
2119 /// \returns The declaration of the named Objective-C class, or NULL if the
2120 /// class could not be found.
2121 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2122                                               SourceLocation IdLoc,
2123                                               bool DoTypoCorrection) {
2124   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2125   // creation from this context.
2126   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2127 
2128   if (!IDecl && DoTypoCorrection) {
2129     // Perform typo correction at the given location, but only if we
2130     // find an Objective-C class name.
2131     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2132     if (TypoCorrection C =
2133             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2134                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2135       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2136       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2137       Id = IDecl->getIdentifier();
2138     }
2139   }
2140   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2141   // This routine must always return a class definition, if any.
2142   if (Def && Def->getDefinition())
2143       Def = Def->getDefinition();
2144   return Def;
2145 }
2146 
2147 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2148 /// from S, where a non-field would be declared. This routine copes
2149 /// with the difference between C and C++ scoping rules in structs and
2150 /// unions. For example, the following code is well-formed in C but
2151 /// ill-formed in C++:
2152 /// @code
2153 /// struct S6 {
2154 ///   enum { BAR } e;
2155 /// };
2156 ///
2157 /// void test_S6() {
2158 ///   struct S6 a;
2159 ///   a.e = BAR;
2160 /// }
2161 /// @endcode
2162 /// For the declaration of BAR, this routine will return a different
2163 /// scope. The scope S will be the scope of the unnamed enumeration
2164 /// within S6. In C++, this routine will return the scope associated
2165 /// with S6, because the enumeration's scope is a transparent
2166 /// context but structures can contain non-field names. In C, this
2167 /// routine will return the translation unit scope, since the
2168 /// enumeration's scope is a transparent context and structures cannot
2169 /// contain non-field names.
2170 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2171   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2172          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2173          (S->isClassScope() && !getLangOpts().CPlusPlus))
2174     S = S->getParent();
2175   return S;
2176 }
2177 
2178 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2179                                ASTContext::GetBuiltinTypeError Error) {
2180   switch (Error) {
2181   case ASTContext::GE_None:
2182     return "";
2183   case ASTContext::GE_Missing_type:
2184     return BuiltinInfo.getHeaderName(ID);
2185   case ASTContext::GE_Missing_stdio:
2186     return "stdio.h";
2187   case ASTContext::GE_Missing_setjmp:
2188     return "setjmp.h";
2189   case ASTContext::GE_Missing_ucontext:
2190     return "ucontext.h";
2191   }
2192   llvm_unreachable("unhandled error kind");
2193 }
2194 
2195 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2196                                   unsigned ID, SourceLocation Loc) {
2197   DeclContext *Parent = Context.getTranslationUnitDecl();
2198 
2199   if (getLangOpts().CPlusPlus) {
2200     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2201         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2202     CLinkageDecl->setImplicit();
2203     Parent->addDecl(CLinkageDecl);
2204     Parent = CLinkageDecl;
2205   }
2206 
2207   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2208                                            /*TInfo=*/nullptr, SC_Extern,
2209                                            getCurFPFeatures().isFPConstrained(),
2210                                            false, Type->isFunctionProtoType());
2211   New->setImplicit();
2212   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2213 
2214   // Create Decl objects for each parameter, adding them to the
2215   // FunctionDecl.
2216   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2217     SmallVector<ParmVarDecl *, 16> Params;
2218     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2219       ParmVarDecl *parm = ParmVarDecl::Create(
2220           Context, New, SourceLocation(), SourceLocation(), nullptr,
2221           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2222       parm->setScopeInfo(0, i);
2223       Params.push_back(parm);
2224     }
2225     New->setParams(Params);
2226   }
2227 
2228   AddKnownFunctionAttributes(New);
2229   return New;
2230 }
2231 
2232 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2233 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2234 /// if we're creating this built-in in anticipation of redeclaring the
2235 /// built-in.
2236 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2237                                      Scope *S, bool ForRedeclaration,
2238                                      SourceLocation Loc) {
2239   LookupNecessaryTypesForBuiltin(S, ID);
2240 
2241   ASTContext::GetBuiltinTypeError Error;
2242   QualType R = Context.GetBuiltinType(ID, Error);
2243   if (Error) {
2244     if (!ForRedeclaration)
2245       return nullptr;
2246 
2247     // If we have a builtin without an associated type we should not emit a
2248     // warning when we were not able to find a type for it.
2249     if (Error == ASTContext::GE_Missing_type ||
2250         Context.BuiltinInfo.allowTypeMismatch(ID))
2251       return nullptr;
2252 
2253     // If we could not find a type for setjmp it is because the jmp_buf type was
2254     // not defined prior to the setjmp declaration.
2255     if (Error == ASTContext::GE_Missing_setjmp) {
2256       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2257           << Context.BuiltinInfo.getName(ID);
2258       return nullptr;
2259     }
2260 
2261     // Generally, we emit a warning that the declaration requires the
2262     // appropriate header.
2263     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2264         << getHeaderName(Context.BuiltinInfo, ID, Error)
2265         << Context.BuiltinInfo.getName(ID);
2266     return nullptr;
2267   }
2268 
2269   if (!ForRedeclaration &&
2270       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2271        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2272     Diag(Loc, diag::ext_implicit_lib_function_decl)
2273         << Context.BuiltinInfo.getName(ID) << R;
2274     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2275       Diag(Loc, diag::note_include_header_or_declare)
2276           << Header << Context.BuiltinInfo.getName(ID);
2277   }
2278 
2279   if (R.isNull())
2280     return nullptr;
2281 
2282   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2283   RegisterLocallyScopedExternCDecl(New, S);
2284 
2285   // TUScope is the translation-unit scope to insert this function into.
2286   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2287   // relate Scopes to DeclContexts, and probably eliminate CurContext
2288   // entirely, but we're not there yet.
2289   DeclContext *SavedContext = CurContext;
2290   CurContext = New->getDeclContext();
2291   PushOnScopeChains(New, TUScope);
2292   CurContext = SavedContext;
2293   return New;
2294 }
2295 
2296 /// Typedef declarations don't have linkage, but they still denote the same
2297 /// entity if their types are the same.
2298 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2299 /// isSameEntity.
2300 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2301                                                      TypedefNameDecl *Decl,
2302                                                      LookupResult &Previous) {
2303   // This is only interesting when modules are enabled.
2304   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2305     return;
2306 
2307   // Empty sets are uninteresting.
2308   if (Previous.empty())
2309     return;
2310 
2311   LookupResult::Filter Filter = Previous.makeFilter();
2312   while (Filter.hasNext()) {
2313     NamedDecl *Old = Filter.next();
2314 
2315     // Non-hidden declarations are never ignored.
2316     if (S.isVisible(Old))
2317       continue;
2318 
2319     // Declarations of the same entity are not ignored, even if they have
2320     // different linkages.
2321     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2322       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2323                                 Decl->getUnderlyingType()))
2324         continue;
2325 
2326       // If both declarations give a tag declaration a typedef name for linkage
2327       // purposes, then they declare the same entity.
2328       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2329           Decl->getAnonDeclWithTypedefName())
2330         continue;
2331     }
2332 
2333     Filter.erase();
2334   }
2335 
2336   Filter.done();
2337 }
2338 
2339 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2340   QualType OldType;
2341   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2342     OldType = OldTypedef->getUnderlyingType();
2343   else
2344     OldType = Context.getTypeDeclType(Old);
2345   QualType NewType = New->getUnderlyingType();
2346 
2347   if (NewType->isVariablyModifiedType()) {
2348     // Must not redefine a typedef with a variably-modified type.
2349     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2350     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2351       << Kind << NewType;
2352     if (Old->getLocation().isValid())
2353       notePreviousDefinition(Old, New->getLocation());
2354     New->setInvalidDecl();
2355     return true;
2356   }
2357 
2358   if (OldType != NewType &&
2359       !OldType->isDependentType() &&
2360       !NewType->isDependentType() &&
2361       !Context.hasSameType(OldType, NewType)) {
2362     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2363     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2364       << Kind << NewType << OldType;
2365     if (Old->getLocation().isValid())
2366       notePreviousDefinition(Old, New->getLocation());
2367     New->setInvalidDecl();
2368     return true;
2369   }
2370   return false;
2371 }
2372 
2373 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2374 /// same name and scope as a previous declaration 'Old'.  Figure out
2375 /// how to resolve this situation, merging decls or emitting
2376 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2377 ///
2378 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2379                                 LookupResult &OldDecls) {
2380   // If the new decl is known invalid already, don't bother doing any
2381   // merging checks.
2382   if (New->isInvalidDecl()) return;
2383 
2384   // Allow multiple definitions for ObjC built-in typedefs.
2385   // FIXME: Verify the underlying types are equivalent!
2386   if (getLangOpts().ObjC) {
2387     const IdentifierInfo *TypeID = New->getIdentifier();
2388     switch (TypeID->getLength()) {
2389     default: break;
2390     case 2:
2391       {
2392         if (!TypeID->isStr("id"))
2393           break;
2394         QualType T = New->getUnderlyingType();
2395         if (!T->isPointerType())
2396           break;
2397         if (!T->isVoidPointerType()) {
2398           QualType PT = T->castAs<PointerType>()->getPointeeType();
2399           if (!PT->isStructureType())
2400             break;
2401         }
2402         Context.setObjCIdRedefinitionType(T);
2403         // Install the built-in type for 'id', ignoring the current definition.
2404         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2405         return;
2406       }
2407     case 5:
2408       if (!TypeID->isStr("Class"))
2409         break;
2410       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2411       // Install the built-in type for 'Class', ignoring the current definition.
2412       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2413       return;
2414     case 3:
2415       if (!TypeID->isStr("SEL"))
2416         break;
2417       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2418       // Install the built-in type for 'SEL', ignoring the current definition.
2419       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2420       return;
2421     }
2422     // Fall through - the typedef name was not a builtin type.
2423   }
2424 
2425   // Verify the old decl was also a type.
2426   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2427   if (!Old) {
2428     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2429       << New->getDeclName();
2430 
2431     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2432     if (OldD->getLocation().isValid())
2433       notePreviousDefinition(OldD, New->getLocation());
2434 
2435     return New->setInvalidDecl();
2436   }
2437 
2438   // If the old declaration is invalid, just give up here.
2439   if (Old->isInvalidDecl())
2440     return New->setInvalidDecl();
2441 
2442   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2443     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2444     auto *NewTag = New->getAnonDeclWithTypedefName();
2445     NamedDecl *Hidden = nullptr;
2446     if (OldTag && NewTag &&
2447         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2448         !hasVisibleDefinition(OldTag, &Hidden)) {
2449       // There is a definition of this tag, but it is not visible. Use it
2450       // instead of our tag.
2451       New->setTypeForDecl(OldTD->getTypeForDecl());
2452       if (OldTD->isModed())
2453         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2454                                     OldTD->getUnderlyingType());
2455       else
2456         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2457 
2458       // Make the old tag definition visible.
2459       makeMergedDefinitionVisible(Hidden);
2460 
2461       // If this was an unscoped enumeration, yank all of its enumerators
2462       // out of the scope.
2463       if (isa<EnumDecl>(NewTag)) {
2464         Scope *EnumScope = getNonFieldDeclScope(S);
2465         for (auto *D : NewTag->decls()) {
2466           auto *ED = cast<EnumConstantDecl>(D);
2467           assert(EnumScope->isDeclScope(ED));
2468           EnumScope->RemoveDecl(ED);
2469           IdResolver.RemoveDecl(ED);
2470           ED->getLexicalDeclContext()->removeDecl(ED);
2471         }
2472       }
2473     }
2474   }
2475 
2476   // If the typedef types are not identical, reject them in all languages and
2477   // with any extensions enabled.
2478   if (isIncompatibleTypedef(Old, New))
2479     return;
2480 
2481   // The types match.  Link up the redeclaration chain and merge attributes if
2482   // the old declaration was a typedef.
2483   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2484     New->setPreviousDecl(Typedef);
2485     mergeDeclAttributes(New, Old);
2486   }
2487 
2488   if (getLangOpts().MicrosoftExt)
2489     return;
2490 
2491   if (getLangOpts().CPlusPlus) {
2492     // C++ [dcl.typedef]p2:
2493     //   In a given non-class scope, a typedef specifier can be used to
2494     //   redefine the name of any type declared in that scope to refer
2495     //   to the type to which it already refers.
2496     if (!isa<CXXRecordDecl>(CurContext))
2497       return;
2498 
2499     // C++0x [dcl.typedef]p4:
2500     //   In a given class scope, a typedef specifier can be used to redefine
2501     //   any class-name declared in that scope that is not also a typedef-name
2502     //   to refer to the type to which it already refers.
2503     //
2504     // This wording came in via DR424, which was a correction to the
2505     // wording in DR56, which accidentally banned code like:
2506     //
2507     //   struct S {
2508     //     typedef struct A { } A;
2509     //   };
2510     //
2511     // in the C++03 standard. We implement the C++0x semantics, which
2512     // allow the above but disallow
2513     //
2514     //   struct S {
2515     //     typedef int I;
2516     //     typedef int I;
2517     //   };
2518     //
2519     // since that was the intent of DR56.
2520     if (!isa<TypedefNameDecl>(Old))
2521       return;
2522 
2523     Diag(New->getLocation(), diag::err_redefinition)
2524       << New->getDeclName();
2525     notePreviousDefinition(Old, New->getLocation());
2526     return New->setInvalidDecl();
2527   }
2528 
2529   // Modules always permit redefinition of typedefs, as does C11.
2530   if (getLangOpts().Modules || getLangOpts().C11)
2531     return;
2532 
2533   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2534   // is normally mapped to an error, but can be controlled with
2535   // -Wtypedef-redefinition.  If either the original or the redefinition is
2536   // in a system header, don't emit this for compatibility with GCC.
2537   if (getDiagnostics().getSuppressSystemWarnings() &&
2538       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2539       (Old->isImplicit() ||
2540        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2541        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2542     return;
2543 
2544   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2545     << New->getDeclName();
2546   notePreviousDefinition(Old, New->getLocation());
2547 }
2548 
2549 /// DeclhasAttr - returns true if decl Declaration already has the target
2550 /// attribute.
2551 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2552   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2553   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2554   for (const auto *i : D->attrs())
2555     if (i->getKind() == A->getKind()) {
2556       if (Ann) {
2557         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2558           return true;
2559         continue;
2560       }
2561       // FIXME: Don't hardcode this check
2562       if (OA && isa<OwnershipAttr>(i))
2563         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2564       return true;
2565     }
2566 
2567   return false;
2568 }
2569 
2570 static bool isAttributeTargetADefinition(Decl *D) {
2571   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2572     return VD->isThisDeclarationADefinition();
2573   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2574     return TD->isCompleteDefinition() || TD->isBeingDefined();
2575   return true;
2576 }
2577 
2578 /// Merge alignment attributes from \p Old to \p New, taking into account the
2579 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2580 ///
2581 /// \return \c true if any attributes were added to \p New.
2582 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2583   // Look for alignas attributes on Old, and pick out whichever attribute
2584   // specifies the strictest alignment requirement.
2585   AlignedAttr *OldAlignasAttr = nullptr;
2586   AlignedAttr *OldStrictestAlignAttr = nullptr;
2587   unsigned OldAlign = 0;
2588   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2589     // FIXME: We have no way of representing inherited dependent alignments
2590     // in a case like:
2591     //   template<int A, int B> struct alignas(A) X;
2592     //   template<int A, int B> struct alignas(B) X {};
2593     // For now, we just ignore any alignas attributes which are not on the
2594     // definition in such a case.
2595     if (I->isAlignmentDependent())
2596       return false;
2597 
2598     if (I->isAlignas())
2599       OldAlignasAttr = I;
2600 
2601     unsigned Align = I->getAlignment(S.Context);
2602     if (Align > OldAlign) {
2603       OldAlign = Align;
2604       OldStrictestAlignAttr = I;
2605     }
2606   }
2607 
2608   // Look for alignas attributes on New.
2609   AlignedAttr *NewAlignasAttr = nullptr;
2610   unsigned NewAlign = 0;
2611   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2612     if (I->isAlignmentDependent())
2613       return false;
2614 
2615     if (I->isAlignas())
2616       NewAlignasAttr = I;
2617 
2618     unsigned Align = I->getAlignment(S.Context);
2619     if (Align > NewAlign)
2620       NewAlign = Align;
2621   }
2622 
2623   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2624     // Both declarations have 'alignas' attributes. We require them to match.
2625     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2626     // fall short. (If two declarations both have alignas, they must both match
2627     // every definition, and so must match each other if there is a definition.)
2628 
2629     // If either declaration only contains 'alignas(0)' specifiers, then it
2630     // specifies the natural alignment for the type.
2631     if (OldAlign == 0 || NewAlign == 0) {
2632       QualType Ty;
2633       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2634         Ty = VD->getType();
2635       else
2636         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2637 
2638       if (OldAlign == 0)
2639         OldAlign = S.Context.getTypeAlign(Ty);
2640       if (NewAlign == 0)
2641         NewAlign = S.Context.getTypeAlign(Ty);
2642     }
2643 
2644     if (OldAlign != NewAlign) {
2645       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2646         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2647         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2648       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2649     }
2650   }
2651 
2652   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2653     // C++11 [dcl.align]p6:
2654     //   if any declaration of an entity has an alignment-specifier,
2655     //   every defining declaration of that entity shall specify an
2656     //   equivalent alignment.
2657     // C11 6.7.5/7:
2658     //   If the definition of an object does not have an alignment
2659     //   specifier, any other declaration of that object shall also
2660     //   have no alignment specifier.
2661     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2662       << OldAlignasAttr;
2663     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2664       << OldAlignasAttr;
2665   }
2666 
2667   bool AnyAdded = false;
2668 
2669   // Ensure we have an attribute representing the strictest alignment.
2670   if (OldAlign > NewAlign) {
2671     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2672     Clone->setInherited(true);
2673     New->addAttr(Clone);
2674     AnyAdded = true;
2675   }
2676 
2677   // Ensure we have an alignas attribute if the old declaration had one.
2678   if (OldAlignasAttr && !NewAlignasAttr &&
2679       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2680     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2681     Clone->setInherited(true);
2682     New->addAttr(Clone);
2683     AnyAdded = true;
2684   }
2685 
2686   return AnyAdded;
2687 }
2688 
2689 #define WANT_DECL_MERGE_LOGIC
2690 #include "clang/Sema/AttrParsedAttrImpl.inc"
2691 #undef WANT_DECL_MERGE_LOGIC
2692 
2693 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2694                                const InheritableAttr *Attr,
2695                                Sema::AvailabilityMergeKind AMK) {
2696   // Diagnose any mutual exclusions between the attribute that we want to add
2697   // and attributes that already exist on the declaration.
2698   if (!DiagnoseMutualExclusions(S, D, Attr))
2699     return false;
2700 
2701   // This function copies an attribute Attr from a previous declaration to the
2702   // new declaration D if the new declaration doesn't itself have that attribute
2703   // yet or if that attribute allows duplicates.
2704   // If you're adding a new attribute that requires logic different from
2705   // "use explicit attribute on decl if present, else use attribute from
2706   // previous decl", for example if the attribute needs to be consistent
2707   // between redeclarations, you need to call a custom merge function here.
2708   InheritableAttr *NewAttr = nullptr;
2709   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2710     NewAttr = S.mergeAvailabilityAttr(
2711         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2712         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2713         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2714         AA->getPriority());
2715   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2716     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2717   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2718     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2719   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2720     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2721   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2722     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2723   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2724     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2725   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2726     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2727                                 FA->getFirstArg());
2728   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2729     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2730   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2731     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2732   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2733     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2734                                        IA->getInheritanceModel());
2735   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2736     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2737                                       &S.Context.Idents.get(AA->getSpelling()));
2738   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2739            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2740             isa<CUDAGlobalAttr>(Attr))) {
2741     // CUDA target attributes are part of function signature for
2742     // overloading purposes and must not be merged.
2743     return false;
2744   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2745     NewAttr = S.mergeMinSizeAttr(D, *MA);
2746   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2747     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2748   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2749     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2750   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2751     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2752   else if (isa<AlignedAttr>(Attr))
2753     // AlignedAttrs are handled separately, because we need to handle all
2754     // such attributes on a declaration at the same time.
2755     NewAttr = nullptr;
2756   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2757            (AMK == Sema::AMK_Override ||
2758             AMK == Sema::AMK_ProtocolImplementation ||
2759             AMK == Sema::AMK_OptionalProtocolImplementation))
2760     NewAttr = nullptr;
2761   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2762     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2763   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2764     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2765   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2766     NewAttr = S.mergeImportNameAttr(D, *INA);
2767   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2768     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2769   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2770     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2771   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2772     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2773   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2774     NewAttr =
2775         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2776   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2777     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2778 
2779   if (NewAttr) {
2780     NewAttr->setInherited(true);
2781     D->addAttr(NewAttr);
2782     if (isa<MSInheritanceAttr>(NewAttr))
2783       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2784     return true;
2785   }
2786 
2787   return false;
2788 }
2789 
2790 static const NamedDecl *getDefinition(const Decl *D) {
2791   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2792     return TD->getDefinition();
2793   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2794     const VarDecl *Def = VD->getDefinition();
2795     if (Def)
2796       return Def;
2797     return VD->getActingDefinition();
2798   }
2799   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2800     const FunctionDecl *Def = nullptr;
2801     if (FD->isDefined(Def, true))
2802       return Def;
2803   }
2804   return nullptr;
2805 }
2806 
2807 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2808   for (const auto *Attribute : D->attrs())
2809     if (Attribute->getKind() == Kind)
2810       return true;
2811   return false;
2812 }
2813 
2814 /// checkNewAttributesAfterDef - If we already have a definition, check that
2815 /// there are no new attributes in this declaration.
2816 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2817   if (!New->hasAttrs())
2818     return;
2819 
2820   const NamedDecl *Def = getDefinition(Old);
2821   if (!Def || Def == New)
2822     return;
2823 
2824   AttrVec &NewAttributes = New->getAttrs();
2825   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2826     const Attr *NewAttribute = NewAttributes[I];
2827 
2828     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2829       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2830         Sema::SkipBodyInfo SkipBody;
2831         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2832 
2833         // If we're skipping this definition, drop the "alias" attribute.
2834         if (SkipBody.ShouldSkip) {
2835           NewAttributes.erase(NewAttributes.begin() + I);
2836           --E;
2837           continue;
2838         }
2839       } else {
2840         VarDecl *VD = cast<VarDecl>(New);
2841         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2842                                 VarDecl::TentativeDefinition
2843                             ? diag::err_alias_after_tentative
2844                             : diag::err_redefinition;
2845         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2846         if (Diag == diag::err_redefinition)
2847           S.notePreviousDefinition(Def, VD->getLocation());
2848         else
2849           S.Diag(Def->getLocation(), diag::note_previous_definition);
2850         VD->setInvalidDecl();
2851       }
2852       ++I;
2853       continue;
2854     }
2855 
2856     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2857       // Tentative definitions are only interesting for the alias check above.
2858       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2859         ++I;
2860         continue;
2861       }
2862     }
2863 
2864     if (hasAttribute(Def, NewAttribute->getKind())) {
2865       ++I;
2866       continue; // regular attr merging will take care of validating this.
2867     }
2868 
2869     if (isa<C11NoReturnAttr>(NewAttribute)) {
2870       // C's _Noreturn is allowed to be added to a function after it is defined.
2871       ++I;
2872       continue;
2873     } else if (isa<UuidAttr>(NewAttribute)) {
2874       // msvc will allow a subsequent definition to add an uuid to a class
2875       ++I;
2876       continue;
2877     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2878       if (AA->isAlignas()) {
2879         // C++11 [dcl.align]p6:
2880         //   if any declaration of an entity has an alignment-specifier,
2881         //   every defining declaration of that entity shall specify an
2882         //   equivalent alignment.
2883         // C11 6.7.5/7:
2884         //   If the definition of an object does not have an alignment
2885         //   specifier, any other declaration of that object shall also
2886         //   have no alignment specifier.
2887         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2888           << AA;
2889         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2890           << AA;
2891         NewAttributes.erase(NewAttributes.begin() + I);
2892         --E;
2893         continue;
2894       }
2895     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2896       // If there is a C definition followed by a redeclaration with this
2897       // attribute then there are two different definitions. In C++, prefer the
2898       // standard diagnostics.
2899       if (!S.getLangOpts().CPlusPlus) {
2900         S.Diag(NewAttribute->getLocation(),
2901                diag::err_loader_uninitialized_redeclaration);
2902         S.Diag(Def->getLocation(), diag::note_previous_definition);
2903         NewAttributes.erase(NewAttributes.begin() + I);
2904         --E;
2905         continue;
2906       }
2907     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2908                cast<VarDecl>(New)->isInline() &&
2909                !cast<VarDecl>(New)->isInlineSpecified()) {
2910       // Don't warn about applying selectany to implicitly inline variables.
2911       // Older compilers and language modes would require the use of selectany
2912       // to make such variables inline, and it would have no effect if we
2913       // honored it.
2914       ++I;
2915       continue;
2916     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2917       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2918       // declarations after defintions.
2919       ++I;
2920       continue;
2921     }
2922 
2923     S.Diag(NewAttribute->getLocation(),
2924            diag::warn_attribute_precede_definition);
2925     S.Diag(Def->getLocation(), diag::note_previous_definition);
2926     NewAttributes.erase(NewAttributes.begin() + I);
2927     --E;
2928   }
2929 }
2930 
2931 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2932                                      const ConstInitAttr *CIAttr,
2933                                      bool AttrBeforeInit) {
2934   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2935 
2936   // Figure out a good way to write this specifier on the old declaration.
2937   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2938   // enough of the attribute list spelling information to extract that without
2939   // heroics.
2940   std::string SuitableSpelling;
2941   if (S.getLangOpts().CPlusPlus20)
2942     SuitableSpelling = std::string(
2943         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2944   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2945     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2946         InsertLoc, {tok::l_square, tok::l_square,
2947                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2948                     S.PP.getIdentifierInfo("require_constant_initialization"),
2949                     tok::r_square, tok::r_square}));
2950   if (SuitableSpelling.empty())
2951     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2952         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2953                     S.PP.getIdentifierInfo("require_constant_initialization"),
2954                     tok::r_paren, tok::r_paren}));
2955   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2956     SuitableSpelling = "constinit";
2957   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2958     SuitableSpelling = "[[clang::require_constant_initialization]]";
2959   if (SuitableSpelling.empty())
2960     SuitableSpelling = "__attribute__((require_constant_initialization))";
2961   SuitableSpelling += " ";
2962 
2963   if (AttrBeforeInit) {
2964     // extern constinit int a;
2965     // int a = 0; // error (missing 'constinit'), accepted as extension
2966     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2967     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2968         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2969     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2970   } else {
2971     // int a = 0;
2972     // constinit extern int a; // error (missing 'constinit')
2973     S.Diag(CIAttr->getLocation(),
2974            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2975                                  : diag::warn_require_const_init_added_too_late)
2976         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2977     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2978         << CIAttr->isConstinit()
2979         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2980   }
2981 }
2982 
2983 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2984 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2985                                AvailabilityMergeKind AMK) {
2986   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2987     UsedAttr *NewAttr = OldAttr->clone(Context);
2988     NewAttr->setInherited(true);
2989     New->addAttr(NewAttr);
2990   }
2991   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2992     RetainAttr *NewAttr = OldAttr->clone(Context);
2993     NewAttr->setInherited(true);
2994     New->addAttr(NewAttr);
2995   }
2996 
2997   if (!Old->hasAttrs() && !New->hasAttrs())
2998     return;
2999 
3000   // [dcl.constinit]p1:
3001   //   If the [constinit] specifier is applied to any declaration of a
3002   //   variable, it shall be applied to the initializing declaration.
3003   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3004   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3005   if (bool(OldConstInit) != bool(NewConstInit)) {
3006     const auto *OldVD = cast<VarDecl>(Old);
3007     auto *NewVD = cast<VarDecl>(New);
3008 
3009     // Find the initializing declaration. Note that we might not have linked
3010     // the new declaration into the redeclaration chain yet.
3011     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3012     if (!InitDecl &&
3013         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3014       InitDecl = NewVD;
3015 
3016     if (InitDecl == NewVD) {
3017       // This is the initializing declaration. If it would inherit 'constinit',
3018       // that's ill-formed. (Note that we do not apply this to the attribute
3019       // form).
3020       if (OldConstInit && OldConstInit->isConstinit())
3021         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3022                                  /*AttrBeforeInit=*/true);
3023     } else if (NewConstInit) {
3024       // This is the first time we've been told that this declaration should
3025       // have a constant initializer. If we already saw the initializing
3026       // declaration, this is too late.
3027       if (InitDecl && InitDecl != NewVD) {
3028         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3029                                  /*AttrBeforeInit=*/false);
3030         NewVD->dropAttr<ConstInitAttr>();
3031       }
3032     }
3033   }
3034 
3035   // Attributes declared post-definition are currently ignored.
3036   checkNewAttributesAfterDef(*this, New, Old);
3037 
3038   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3039     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3040       if (!OldA->isEquivalent(NewA)) {
3041         // This redeclaration changes __asm__ label.
3042         Diag(New->getLocation(), diag::err_different_asm_label);
3043         Diag(OldA->getLocation(), diag::note_previous_declaration);
3044       }
3045     } else if (Old->isUsed()) {
3046       // This redeclaration adds an __asm__ label to a declaration that has
3047       // already been ODR-used.
3048       Diag(New->getLocation(), diag::err_late_asm_label_name)
3049         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3050     }
3051   }
3052 
3053   // Re-declaration cannot add abi_tag's.
3054   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3055     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3056       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3057         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3058           Diag(NewAbiTagAttr->getLocation(),
3059                diag::err_new_abi_tag_on_redeclaration)
3060               << NewTag;
3061           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3062         }
3063       }
3064     } else {
3065       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3066       Diag(Old->getLocation(), diag::note_previous_declaration);
3067     }
3068   }
3069 
3070   // This redeclaration adds a section attribute.
3071   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3072     if (auto *VD = dyn_cast<VarDecl>(New)) {
3073       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3074         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3075         Diag(Old->getLocation(), diag::note_previous_declaration);
3076       }
3077     }
3078   }
3079 
3080   // Redeclaration adds code-seg attribute.
3081   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3082   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3083       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3084     Diag(New->getLocation(), diag::warn_mismatched_section)
3085          << 0 /*codeseg*/;
3086     Diag(Old->getLocation(), diag::note_previous_declaration);
3087   }
3088 
3089   if (!Old->hasAttrs())
3090     return;
3091 
3092   bool foundAny = New->hasAttrs();
3093 
3094   // Ensure that any moving of objects within the allocated map is done before
3095   // we process them.
3096   if (!foundAny) New->setAttrs(AttrVec());
3097 
3098   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3099     // Ignore deprecated/unavailable/availability attributes if requested.
3100     AvailabilityMergeKind LocalAMK = AMK_None;
3101     if (isa<DeprecatedAttr>(I) ||
3102         isa<UnavailableAttr>(I) ||
3103         isa<AvailabilityAttr>(I)) {
3104       switch (AMK) {
3105       case AMK_None:
3106         continue;
3107 
3108       case AMK_Redeclaration:
3109       case AMK_Override:
3110       case AMK_ProtocolImplementation:
3111       case AMK_OptionalProtocolImplementation:
3112         LocalAMK = AMK;
3113         break;
3114       }
3115     }
3116 
3117     // Already handled.
3118     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3119       continue;
3120 
3121     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3122       foundAny = true;
3123   }
3124 
3125   if (mergeAlignedAttrs(*this, New, Old))
3126     foundAny = true;
3127 
3128   if (!foundAny) New->dropAttrs();
3129 }
3130 
3131 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3132 /// to the new one.
3133 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3134                                      const ParmVarDecl *oldDecl,
3135                                      Sema &S) {
3136   // C++11 [dcl.attr.depend]p2:
3137   //   The first declaration of a function shall specify the
3138   //   carries_dependency attribute for its declarator-id if any declaration
3139   //   of the function specifies the carries_dependency attribute.
3140   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3141   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3142     S.Diag(CDA->getLocation(),
3143            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3144     // Find the first declaration of the parameter.
3145     // FIXME: Should we build redeclaration chains for function parameters?
3146     const FunctionDecl *FirstFD =
3147       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3148     const ParmVarDecl *FirstVD =
3149       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3150     S.Diag(FirstVD->getLocation(),
3151            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3152   }
3153 
3154   if (!oldDecl->hasAttrs())
3155     return;
3156 
3157   bool foundAny = newDecl->hasAttrs();
3158 
3159   // Ensure that any moving of objects within the allocated map is
3160   // done before we process them.
3161   if (!foundAny) newDecl->setAttrs(AttrVec());
3162 
3163   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3164     if (!DeclHasAttr(newDecl, I)) {
3165       InheritableAttr *newAttr =
3166         cast<InheritableParamAttr>(I->clone(S.Context));
3167       newAttr->setInherited(true);
3168       newDecl->addAttr(newAttr);
3169       foundAny = true;
3170     }
3171   }
3172 
3173   if (!foundAny) newDecl->dropAttrs();
3174 }
3175 
3176 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3177                                 const ParmVarDecl *OldParam,
3178                                 Sema &S) {
3179   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3180     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3181       if (*Oldnullability != *Newnullability) {
3182         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3183           << DiagNullabilityKind(
3184                *Newnullability,
3185                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3186                 != 0))
3187           << DiagNullabilityKind(
3188                *Oldnullability,
3189                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3190                 != 0));
3191         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3192       }
3193     } else {
3194       QualType NewT = NewParam->getType();
3195       NewT = S.Context.getAttributedType(
3196                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3197                          NewT, NewT);
3198       NewParam->setType(NewT);
3199     }
3200   }
3201 }
3202 
3203 namespace {
3204 
3205 /// Used in MergeFunctionDecl to keep track of function parameters in
3206 /// C.
3207 struct GNUCompatibleParamWarning {
3208   ParmVarDecl *OldParm;
3209   ParmVarDecl *NewParm;
3210   QualType PromotedType;
3211 };
3212 
3213 } // end anonymous namespace
3214 
3215 // Determine whether the previous declaration was a definition, implicit
3216 // declaration, or a declaration.
3217 template <typename T>
3218 static std::pair<diag::kind, SourceLocation>
3219 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3220   diag::kind PrevDiag;
3221   SourceLocation OldLocation = Old->getLocation();
3222   if (Old->isThisDeclarationADefinition())
3223     PrevDiag = diag::note_previous_definition;
3224   else if (Old->isImplicit()) {
3225     PrevDiag = diag::note_previous_implicit_declaration;
3226     if (OldLocation.isInvalid())
3227       OldLocation = New->getLocation();
3228   } else
3229     PrevDiag = diag::note_previous_declaration;
3230   return std::make_pair(PrevDiag, OldLocation);
3231 }
3232 
3233 /// canRedefineFunction - checks if a function can be redefined. Currently,
3234 /// only extern inline functions can be redefined, and even then only in
3235 /// GNU89 mode.
3236 static bool canRedefineFunction(const FunctionDecl *FD,
3237                                 const LangOptions& LangOpts) {
3238   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3239           !LangOpts.CPlusPlus &&
3240           FD->isInlineSpecified() &&
3241           FD->getStorageClass() == SC_Extern);
3242 }
3243 
3244 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3245   const AttributedType *AT = T->getAs<AttributedType>();
3246   while (AT && !AT->isCallingConv())
3247     AT = AT->getModifiedType()->getAs<AttributedType>();
3248   return AT;
3249 }
3250 
3251 template <typename T>
3252 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3253   const DeclContext *DC = Old->getDeclContext();
3254   if (DC->isRecord())
3255     return false;
3256 
3257   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3258   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3259     return true;
3260   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3261     return true;
3262   return false;
3263 }
3264 
3265 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3266 static bool isExternC(VarTemplateDecl *) { return false; }
3267 static bool isExternC(FunctionTemplateDecl *) { return false; }
3268 
3269 /// Check whether a redeclaration of an entity introduced by a
3270 /// using-declaration is valid, given that we know it's not an overload
3271 /// (nor a hidden tag declaration).
3272 template<typename ExpectedDecl>
3273 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3274                                    ExpectedDecl *New) {
3275   // C++11 [basic.scope.declarative]p4:
3276   //   Given a set of declarations in a single declarative region, each of
3277   //   which specifies the same unqualified name,
3278   //   -- they shall all refer to the same entity, or all refer to functions
3279   //      and function templates; or
3280   //   -- exactly one declaration shall declare a class name or enumeration
3281   //      name that is not a typedef name and the other declarations shall all
3282   //      refer to the same variable or enumerator, or all refer to functions
3283   //      and function templates; in this case the class name or enumeration
3284   //      name is hidden (3.3.10).
3285 
3286   // C++11 [namespace.udecl]p14:
3287   //   If a function declaration in namespace scope or block scope has the
3288   //   same name and the same parameter-type-list as a function introduced
3289   //   by a using-declaration, and the declarations do not declare the same
3290   //   function, the program is ill-formed.
3291 
3292   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3293   if (Old &&
3294       !Old->getDeclContext()->getRedeclContext()->Equals(
3295           New->getDeclContext()->getRedeclContext()) &&
3296       !(isExternC(Old) && isExternC(New)))
3297     Old = nullptr;
3298 
3299   if (!Old) {
3300     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3301     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3302     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3303     return true;
3304   }
3305   return false;
3306 }
3307 
3308 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3309                                             const FunctionDecl *B) {
3310   assert(A->getNumParams() == B->getNumParams());
3311 
3312   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3313     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3314     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3315     if (AttrA == AttrB)
3316       return true;
3317     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3318            AttrA->isDynamic() == AttrB->isDynamic();
3319   };
3320 
3321   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3322 }
3323 
3324 /// If necessary, adjust the semantic declaration context for a qualified
3325 /// declaration to name the correct inline namespace within the qualifier.
3326 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3327                                                DeclaratorDecl *OldD) {
3328   // The only case where we need to update the DeclContext is when
3329   // redeclaration lookup for a qualified name finds a declaration
3330   // in an inline namespace within the context named by the qualifier:
3331   //
3332   //   inline namespace N { int f(); }
3333   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3334   //
3335   // For unqualified declarations, the semantic context *can* change
3336   // along the redeclaration chain (for local extern declarations,
3337   // extern "C" declarations, and friend declarations in particular).
3338   if (!NewD->getQualifier())
3339     return;
3340 
3341   // NewD is probably already in the right context.
3342   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3343   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3344   if (NamedDC->Equals(SemaDC))
3345     return;
3346 
3347   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3348           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3349          "unexpected context for redeclaration");
3350 
3351   auto *LexDC = NewD->getLexicalDeclContext();
3352   auto FixSemaDC = [=](NamedDecl *D) {
3353     if (!D)
3354       return;
3355     D->setDeclContext(SemaDC);
3356     D->setLexicalDeclContext(LexDC);
3357   };
3358 
3359   FixSemaDC(NewD);
3360   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3361     FixSemaDC(FD->getDescribedFunctionTemplate());
3362   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3363     FixSemaDC(VD->getDescribedVarTemplate());
3364 }
3365 
3366 /// MergeFunctionDecl - We just parsed a function 'New' from
3367 /// declarator D which has the same name and scope as a previous
3368 /// declaration 'Old'.  Figure out how to resolve this situation,
3369 /// merging decls or emitting diagnostics as appropriate.
3370 ///
3371 /// In C++, New and Old must be declarations that are not
3372 /// overloaded. Use IsOverload to determine whether New and Old are
3373 /// overloaded, and to select the Old declaration that New should be
3374 /// merged with.
3375 ///
3376 /// Returns true if there was an error, false otherwise.
3377 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3378                              Scope *S, bool MergeTypeWithOld) {
3379   // Verify the old decl was also a function.
3380   FunctionDecl *Old = OldD->getAsFunction();
3381   if (!Old) {
3382     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3383       if (New->getFriendObjectKind()) {
3384         Diag(New->getLocation(), diag::err_using_decl_friend);
3385         Diag(Shadow->getTargetDecl()->getLocation(),
3386              diag::note_using_decl_target);
3387         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3388             << 0;
3389         return true;
3390       }
3391 
3392       // Check whether the two declarations might declare the same function or
3393       // function template.
3394       if (FunctionTemplateDecl *NewTemplate =
3395               New->getDescribedFunctionTemplate()) {
3396         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3397                                                          NewTemplate))
3398           return true;
3399         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3400                          ->getAsFunction();
3401       } else {
3402         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3403           return true;
3404         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3405       }
3406     } else {
3407       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3408         << New->getDeclName();
3409       notePreviousDefinition(OldD, New->getLocation());
3410       return true;
3411     }
3412   }
3413 
3414   // If the old declaration was found in an inline namespace and the new
3415   // declaration was qualified, update the DeclContext to match.
3416   adjustDeclContextForDeclaratorDecl(New, Old);
3417 
3418   // If the old declaration is invalid, just give up here.
3419   if (Old->isInvalidDecl())
3420     return true;
3421 
3422   // Disallow redeclaration of some builtins.
3423   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3424     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3425     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3426         << Old << Old->getType();
3427     return true;
3428   }
3429 
3430   diag::kind PrevDiag;
3431   SourceLocation OldLocation;
3432   std::tie(PrevDiag, OldLocation) =
3433       getNoteDiagForInvalidRedeclaration(Old, New);
3434 
3435   // Don't complain about this if we're in GNU89 mode and the old function
3436   // is an extern inline function.
3437   // Don't complain about specializations. They are not supposed to have
3438   // storage classes.
3439   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3440       New->getStorageClass() == SC_Static &&
3441       Old->hasExternalFormalLinkage() &&
3442       !New->getTemplateSpecializationInfo() &&
3443       !canRedefineFunction(Old, getLangOpts())) {
3444     if (getLangOpts().MicrosoftExt) {
3445       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3446       Diag(OldLocation, PrevDiag);
3447     } else {
3448       Diag(New->getLocation(), diag::err_static_non_static) << New;
3449       Diag(OldLocation, PrevDiag);
3450       return true;
3451     }
3452   }
3453 
3454   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3455     if (!Old->hasAttr<InternalLinkageAttr>()) {
3456       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3457           << ILA;
3458       Diag(Old->getLocation(), diag::note_previous_declaration);
3459       New->dropAttr<InternalLinkageAttr>();
3460     }
3461 
3462   if (auto *EA = New->getAttr<ErrorAttr>()) {
3463     if (!Old->hasAttr<ErrorAttr>()) {
3464       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3465       Diag(Old->getLocation(), diag::note_previous_declaration);
3466       New->dropAttr<ErrorAttr>();
3467     }
3468   }
3469 
3470   if (CheckRedeclarationInModule(New, Old))
3471     return true;
3472 
3473   if (!getLangOpts().CPlusPlus) {
3474     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3475     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3476       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3477         << New << OldOvl;
3478 
3479       // Try our best to find a decl that actually has the overloadable
3480       // attribute for the note. In most cases (e.g. programs with only one
3481       // broken declaration/definition), this won't matter.
3482       //
3483       // FIXME: We could do this if we juggled some extra state in
3484       // OverloadableAttr, rather than just removing it.
3485       const Decl *DiagOld = Old;
3486       if (OldOvl) {
3487         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3488           const auto *A = D->getAttr<OverloadableAttr>();
3489           return A && !A->isImplicit();
3490         });
3491         // If we've implicitly added *all* of the overloadable attrs to this
3492         // chain, emitting a "previous redecl" note is pointless.
3493         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3494       }
3495 
3496       if (DiagOld)
3497         Diag(DiagOld->getLocation(),
3498              diag::note_attribute_overloadable_prev_overload)
3499           << OldOvl;
3500 
3501       if (OldOvl)
3502         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3503       else
3504         New->dropAttr<OverloadableAttr>();
3505     }
3506   }
3507 
3508   // If a function is first declared with a calling convention, but is later
3509   // declared or defined without one, all following decls assume the calling
3510   // convention of the first.
3511   //
3512   // It's OK if a function is first declared without a calling convention,
3513   // but is later declared or defined with the default calling convention.
3514   //
3515   // To test if either decl has an explicit calling convention, we look for
3516   // AttributedType sugar nodes on the type as written.  If they are missing or
3517   // were canonicalized away, we assume the calling convention was implicit.
3518   //
3519   // Note also that we DO NOT return at this point, because we still have
3520   // other tests to run.
3521   QualType OldQType = Context.getCanonicalType(Old->getType());
3522   QualType NewQType = Context.getCanonicalType(New->getType());
3523   const FunctionType *OldType = cast<FunctionType>(OldQType);
3524   const FunctionType *NewType = cast<FunctionType>(NewQType);
3525   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3526   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3527   bool RequiresAdjustment = false;
3528 
3529   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3530     FunctionDecl *First = Old->getFirstDecl();
3531     const FunctionType *FT =
3532         First->getType().getCanonicalType()->castAs<FunctionType>();
3533     FunctionType::ExtInfo FI = FT->getExtInfo();
3534     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3535     if (!NewCCExplicit) {
3536       // Inherit the CC from the previous declaration if it was specified
3537       // there but not here.
3538       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3539       RequiresAdjustment = true;
3540     } else if (Old->getBuiltinID()) {
3541       // Builtin attribute isn't propagated to the new one yet at this point,
3542       // so we check if the old one is a builtin.
3543 
3544       // Calling Conventions on a Builtin aren't really useful and setting a
3545       // default calling convention and cdecl'ing some builtin redeclarations is
3546       // common, so warn and ignore the calling convention on the redeclaration.
3547       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3548           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3549           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3550       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3551       RequiresAdjustment = true;
3552     } else {
3553       // Calling conventions aren't compatible, so complain.
3554       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3555       Diag(New->getLocation(), diag::err_cconv_change)
3556         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3557         << !FirstCCExplicit
3558         << (!FirstCCExplicit ? "" :
3559             FunctionType::getNameForCallConv(FI.getCC()));
3560 
3561       // Put the note on the first decl, since it is the one that matters.
3562       Diag(First->getLocation(), diag::note_previous_declaration);
3563       return true;
3564     }
3565   }
3566 
3567   // FIXME: diagnose the other way around?
3568   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3569     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3570     RequiresAdjustment = true;
3571   }
3572 
3573   // Merge regparm attribute.
3574   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3575       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3576     if (NewTypeInfo.getHasRegParm()) {
3577       Diag(New->getLocation(), diag::err_regparm_mismatch)
3578         << NewType->getRegParmType()
3579         << OldType->getRegParmType();
3580       Diag(OldLocation, diag::note_previous_declaration);
3581       return true;
3582     }
3583 
3584     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3585     RequiresAdjustment = true;
3586   }
3587 
3588   // Merge ns_returns_retained attribute.
3589   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3590     if (NewTypeInfo.getProducesResult()) {
3591       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3592           << "'ns_returns_retained'";
3593       Diag(OldLocation, diag::note_previous_declaration);
3594       return true;
3595     }
3596 
3597     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3598     RequiresAdjustment = true;
3599   }
3600 
3601   if (OldTypeInfo.getNoCallerSavedRegs() !=
3602       NewTypeInfo.getNoCallerSavedRegs()) {
3603     if (NewTypeInfo.getNoCallerSavedRegs()) {
3604       AnyX86NoCallerSavedRegistersAttr *Attr =
3605         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3606       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3607       Diag(OldLocation, diag::note_previous_declaration);
3608       return true;
3609     }
3610 
3611     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3612     RequiresAdjustment = true;
3613   }
3614 
3615   if (RequiresAdjustment) {
3616     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3617     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3618     New->setType(QualType(AdjustedType, 0));
3619     NewQType = Context.getCanonicalType(New->getType());
3620   }
3621 
3622   // If this redeclaration makes the function inline, we may need to add it to
3623   // UndefinedButUsed.
3624   if (!Old->isInlined() && New->isInlined() &&
3625       !New->hasAttr<GNUInlineAttr>() &&
3626       !getLangOpts().GNUInline &&
3627       Old->isUsed(false) &&
3628       !Old->isDefined() && !New->isThisDeclarationADefinition())
3629     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3630                                            SourceLocation()));
3631 
3632   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3633   // about it.
3634   if (New->hasAttr<GNUInlineAttr>() &&
3635       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3636     UndefinedButUsed.erase(Old->getCanonicalDecl());
3637   }
3638 
3639   // If pass_object_size params don't match up perfectly, this isn't a valid
3640   // redeclaration.
3641   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3642       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3643     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3644         << New->getDeclName();
3645     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3646     return true;
3647   }
3648 
3649   if (getLangOpts().CPlusPlus) {
3650     // C++1z [over.load]p2
3651     //   Certain function declarations cannot be overloaded:
3652     //     -- Function declarations that differ only in the return type,
3653     //        the exception specification, or both cannot be overloaded.
3654 
3655     // Check the exception specifications match. This may recompute the type of
3656     // both Old and New if it resolved exception specifications, so grab the
3657     // types again after this. Because this updates the type, we do this before
3658     // any of the other checks below, which may update the "de facto" NewQType
3659     // but do not necessarily update the type of New.
3660     if (CheckEquivalentExceptionSpec(Old, New))
3661       return true;
3662     OldQType = Context.getCanonicalType(Old->getType());
3663     NewQType = Context.getCanonicalType(New->getType());
3664 
3665     // Go back to the type source info to compare the declared return types,
3666     // per C++1y [dcl.type.auto]p13:
3667     //   Redeclarations or specializations of a function or function template
3668     //   with a declared return type that uses a placeholder type shall also
3669     //   use that placeholder, not a deduced type.
3670     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3671     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3672     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3673         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3674                                        OldDeclaredReturnType)) {
3675       QualType ResQT;
3676       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3677           OldDeclaredReturnType->isObjCObjectPointerType())
3678         // FIXME: This does the wrong thing for a deduced return type.
3679         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3680       if (ResQT.isNull()) {
3681         if (New->isCXXClassMember() && New->isOutOfLine())
3682           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3683               << New << New->getReturnTypeSourceRange();
3684         else
3685           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3686               << New->getReturnTypeSourceRange();
3687         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3688                                     << Old->getReturnTypeSourceRange();
3689         return true;
3690       }
3691       else
3692         NewQType = ResQT;
3693     }
3694 
3695     QualType OldReturnType = OldType->getReturnType();
3696     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3697     if (OldReturnType != NewReturnType) {
3698       // If this function has a deduced return type and has already been
3699       // defined, copy the deduced value from the old declaration.
3700       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3701       if (OldAT && OldAT->isDeduced()) {
3702         QualType DT = OldAT->getDeducedType();
3703         if (DT.isNull()) {
3704           New->setType(SubstAutoTypeDependent(New->getType()));
3705           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3706         } else {
3707           New->setType(SubstAutoType(New->getType(), DT));
3708           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3709         }
3710       }
3711     }
3712 
3713     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3714     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3715     if (OldMethod && NewMethod) {
3716       // Preserve triviality.
3717       NewMethod->setTrivial(OldMethod->isTrivial());
3718 
3719       // MSVC allows explicit template specialization at class scope:
3720       // 2 CXXMethodDecls referring to the same function will be injected.
3721       // We don't want a redeclaration error.
3722       bool IsClassScopeExplicitSpecialization =
3723                               OldMethod->isFunctionTemplateSpecialization() &&
3724                               NewMethod->isFunctionTemplateSpecialization();
3725       bool isFriend = NewMethod->getFriendObjectKind();
3726 
3727       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3728           !IsClassScopeExplicitSpecialization) {
3729         //    -- Member function declarations with the same name and the
3730         //       same parameter types cannot be overloaded if any of them
3731         //       is a static member function declaration.
3732         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3733           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3734           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3735           return true;
3736         }
3737 
3738         // C++ [class.mem]p1:
3739         //   [...] A member shall not be declared twice in the
3740         //   member-specification, except that a nested class or member
3741         //   class template can be declared and then later defined.
3742         if (!inTemplateInstantiation()) {
3743           unsigned NewDiag;
3744           if (isa<CXXConstructorDecl>(OldMethod))
3745             NewDiag = diag::err_constructor_redeclared;
3746           else if (isa<CXXDestructorDecl>(NewMethod))
3747             NewDiag = diag::err_destructor_redeclared;
3748           else if (isa<CXXConversionDecl>(NewMethod))
3749             NewDiag = diag::err_conv_function_redeclared;
3750           else
3751             NewDiag = diag::err_member_redeclared;
3752 
3753           Diag(New->getLocation(), NewDiag);
3754         } else {
3755           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3756             << New << New->getType();
3757         }
3758         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3759         return true;
3760 
3761       // Complain if this is an explicit declaration of a special
3762       // member that was initially declared implicitly.
3763       //
3764       // As an exception, it's okay to befriend such methods in order
3765       // to permit the implicit constructor/destructor/operator calls.
3766       } else if (OldMethod->isImplicit()) {
3767         if (isFriend) {
3768           NewMethod->setImplicit();
3769         } else {
3770           Diag(NewMethod->getLocation(),
3771                diag::err_definition_of_implicitly_declared_member)
3772             << New << getSpecialMember(OldMethod);
3773           return true;
3774         }
3775       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3776         Diag(NewMethod->getLocation(),
3777              diag::err_definition_of_explicitly_defaulted_member)
3778           << getSpecialMember(OldMethod);
3779         return true;
3780       }
3781     }
3782 
3783     // C++11 [dcl.attr.noreturn]p1:
3784     //   The first declaration of a function shall specify the noreturn
3785     //   attribute if any declaration of that function specifies the noreturn
3786     //   attribute.
3787     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3788       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3789         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3790             << NRA;
3791         Diag(Old->getLocation(), diag::note_previous_declaration);
3792       }
3793 
3794     // C++11 [dcl.attr.depend]p2:
3795     //   The first declaration of a function shall specify the
3796     //   carries_dependency attribute for its declarator-id if any declaration
3797     //   of the function specifies the carries_dependency attribute.
3798     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3799     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3800       Diag(CDA->getLocation(),
3801            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3802       Diag(Old->getFirstDecl()->getLocation(),
3803            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3804     }
3805 
3806     // (C++98 8.3.5p3):
3807     //   All declarations for a function shall agree exactly in both the
3808     //   return type and the parameter-type-list.
3809     // We also want to respect all the extended bits except noreturn.
3810 
3811     // noreturn should now match unless the old type info didn't have it.
3812     QualType OldQTypeForComparison = OldQType;
3813     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3814       auto *OldType = OldQType->castAs<FunctionProtoType>();
3815       const FunctionType *OldTypeForComparison
3816         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3817       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3818       assert(OldQTypeForComparison.isCanonical());
3819     }
3820 
3821     if (haveIncompatibleLanguageLinkages(Old, New)) {
3822       // As a special case, retain the language linkage from previous
3823       // declarations of a friend function as an extension.
3824       //
3825       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3826       // and is useful because there's otherwise no way to specify language
3827       // linkage within class scope.
3828       //
3829       // Check cautiously as the friend object kind isn't yet complete.
3830       if (New->getFriendObjectKind() != Decl::FOK_None) {
3831         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3832         Diag(OldLocation, PrevDiag);
3833       } else {
3834         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3835         Diag(OldLocation, PrevDiag);
3836         return true;
3837       }
3838     }
3839 
3840     // If the function types are compatible, merge the declarations. Ignore the
3841     // exception specifier because it was already checked above in
3842     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3843     // about incompatible types under -fms-compatibility.
3844     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3845                                                          NewQType))
3846       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3847 
3848     // If the types are imprecise (due to dependent constructs in friends or
3849     // local extern declarations), it's OK if they differ. We'll check again
3850     // during instantiation.
3851     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3852       return false;
3853 
3854     // Fall through for conflicting redeclarations and redefinitions.
3855   }
3856 
3857   // C: Function types need to be compatible, not identical. This handles
3858   // duplicate function decls like "void f(int); void f(enum X);" properly.
3859   if (!getLangOpts().CPlusPlus &&
3860       Context.typesAreCompatible(OldQType, NewQType)) {
3861     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3862     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3863     const FunctionProtoType *OldProto = nullptr;
3864     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3865         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3866       // The old declaration provided a function prototype, but the
3867       // new declaration does not. Merge in the prototype.
3868       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3869       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3870       NewQType =
3871           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3872                                   OldProto->getExtProtoInfo());
3873       New->setType(NewQType);
3874       New->setHasInheritedPrototype();
3875 
3876       // Synthesize parameters with the same types.
3877       SmallVector<ParmVarDecl*, 16> Params;
3878       for (const auto &ParamType : OldProto->param_types()) {
3879         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3880                                                  SourceLocation(), nullptr,
3881                                                  ParamType, /*TInfo=*/nullptr,
3882                                                  SC_None, nullptr);
3883         Param->setScopeInfo(0, Params.size());
3884         Param->setImplicit();
3885         Params.push_back(Param);
3886       }
3887 
3888       New->setParams(Params);
3889     }
3890 
3891     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3892   }
3893 
3894   // Check if the function types are compatible when pointer size address
3895   // spaces are ignored.
3896   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3897     return false;
3898 
3899   // GNU C permits a K&R definition to follow a prototype declaration
3900   // if the declared types of the parameters in the K&R definition
3901   // match the types in the prototype declaration, even when the
3902   // promoted types of the parameters from the K&R definition differ
3903   // from the types in the prototype. GCC then keeps the types from
3904   // the prototype.
3905   //
3906   // If a variadic prototype is followed by a non-variadic K&R definition,
3907   // the K&R definition becomes variadic.  This is sort of an edge case, but
3908   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3909   // C99 6.9.1p8.
3910   if (!getLangOpts().CPlusPlus &&
3911       Old->hasPrototype() && !New->hasPrototype() &&
3912       New->getType()->getAs<FunctionProtoType>() &&
3913       Old->getNumParams() == New->getNumParams()) {
3914     SmallVector<QualType, 16> ArgTypes;
3915     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3916     const FunctionProtoType *OldProto
3917       = Old->getType()->getAs<FunctionProtoType>();
3918     const FunctionProtoType *NewProto
3919       = New->getType()->getAs<FunctionProtoType>();
3920 
3921     // Determine whether this is the GNU C extension.
3922     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3923                                                NewProto->getReturnType());
3924     bool LooseCompatible = !MergedReturn.isNull();
3925     for (unsigned Idx = 0, End = Old->getNumParams();
3926          LooseCompatible && Idx != End; ++Idx) {
3927       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3928       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3929       if (Context.typesAreCompatible(OldParm->getType(),
3930                                      NewProto->getParamType(Idx))) {
3931         ArgTypes.push_back(NewParm->getType());
3932       } else if (Context.typesAreCompatible(OldParm->getType(),
3933                                             NewParm->getType(),
3934                                             /*CompareUnqualified=*/true)) {
3935         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3936                                            NewProto->getParamType(Idx) };
3937         Warnings.push_back(Warn);
3938         ArgTypes.push_back(NewParm->getType());
3939       } else
3940         LooseCompatible = false;
3941     }
3942 
3943     if (LooseCompatible) {
3944       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3945         Diag(Warnings[Warn].NewParm->getLocation(),
3946              diag::ext_param_promoted_not_compatible_with_prototype)
3947           << Warnings[Warn].PromotedType
3948           << Warnings[Warn].OldParm->getType();
3949         if (Warnings[Warn].OldParm->getLocation().isValid())
3950           Diag(Warnings[Warn].OldParm->getLocation(),
3951                diag::note_previous_declaration);
3952       }
3953 
3954       if (MergeTypeWithOld)
3955         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3956                                              OldProto->getExtProtoInfo()));
3957       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3958     }
3959 
3960     // Fall through to diagnose conflicting types.
3961   }
3962 
3963   // A function that has already been declared has been redeclared or
3964   // defined with a different type; show an appropriate diagnostic.
3965 
3966   // If the previous declaration was an implicitly-generated builtin
3967   // declaration, then at the very least we should use a specialized note.
3968   unsigned BuiltinID;
3969   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3970     // If it's actually a library-defined builtin function like 'malloc'
3971     // or 'printf', just warn about the incompatible redeclaration.
3972     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3973       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3974       Diag(OldLocation, diag::note_previous_builtin_declaration)
3975         << Old << Old->getType();
3976       return false;
3977     }
3978 
3979     PrevDiag = diag::note_previous_builtin_declaration;
3980   }
3981 
3982   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3983   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3984   return true;
3985 }
3986 
3987 /// Completes the merge of two function declarations that are
3988 /// known to be compatible.
3989 ///
3990 /// This routine handles the merging of attributes and other
3991 /// properties of function declarations from the old declaration to
3992 /// the new declaration, once we know that New is in fact a
3993 /// redeclaration of Old.
3994 ///
3995 /// \returns false
3996 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3997                                         Scope *S, bool MergeTypeWithOld) {
3998   // Merge the attributes
3999   mergeDeclAttributes(New, Old);
4000 
4001   // Merge "pure" flag.
4002   if (Old->isPure())
4003     New->setPure();
4004 
4005   // Merge "used" flag.
4006   if (Old->getMostRecentDecl()->isUsed(false))
4007     New->setIsUsed();
4008 
4009   // Merge attributes from the parameters.  These can mismatch with K&R
4010   // declarations.
4011   if (New->getNumParams() == Old->getNumParams())
4012       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4013         ParmVarDecl *NewParam = New->getParamDecl(i);
4014         ParmVarDecl *OldParam = Old->getParamDecl(i);
4015         mergeParamDeclAttributes(NewParam, OldParam, *this);
4016         mergeParamDeclTypes(NewParam, OldParam, *this);
4017       }
4018 
4019   if (getLangOpts().CPlusPlus)
4020     return MergeCXXFunctionDecl(New, Old, S);
4021 
4022   // Merge the function types so the we get the composite types for the return
4023   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4024   // was visible.
4025   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4026   if (!Merged.isNull() && MergeTypeWithOld)
4027     New->setType(Merged);
4028 
4029   return false;
4030 }
4031 
4032 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4033                                 ObjCMethodDecl *oldMethod) {
4034   // Merge the attributes, including deprecated/unavailable
4035   AvailabilityMergeKind MergeKind =
4036       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4037           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4038                                      : AMK_ProtocolImplementation)
4039           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4040                                                            : AMK_Override;
4041 
4042   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4043 
4044   // Merge attributes from the parameters.
4045   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4046                                        oe = oldMethod->param_end();
4047   for (ObjCMethodDecl::param_iterator
4048          ni = newMethod->param_begin(), ne = newMethod->param_end();
4049        ni != ne && oi != oe; ++ni, ++oi)
4050     mergeParamDeclAttributes(*ni, *oi, *this);
4051 
4052   CheckObjCMethodOverride(newMethod, oldMethod);
4053 }
4054 
4055 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4056   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4057 
4058   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4059          ? diag::err_redefinition_different_type
4060          : diag::err_redeclaration_different_type)
4061     << New->getDeclName() << New->getType() << Old->getType();
4062 
4063   diag::kind PrevDiag;
4064   SourceLocation OldLocation;
4065   std::tie(PrevDiag, OldLocation)
4066     = getNoteDiagForInvalidRedeclaration(Old, New);
4067   S.Diag(OldLocation, PrevDiag);
4068   New->setInvalidDecl();
4069 }
4070 
4071 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4072 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4073 /// emitting diagnostics as appropriate.
4074 ///
4075 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4076 /// to here in AddInitializerToDecl. We can't check them before the initializer
4077 /// is attached.
4078 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4079                              bool MergeTypeWithOld) {
4080   if (New->isInvalidDecl() || Old->isInvalidDecl())
4081     return;
4082 
4083   QualType MergedT;
4084   if (getLangOpts().CPlusPlus) {
4085     if (New->getType()->isUndeducedType()) {
4086       // We don't know what the new type is until the initializer is attached.
4087       return;
4088     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4089       // These could still be something that needs exception specs checked.
4090       return MergeVarDeclExceptionSpecs(New, Old);
4091     }
4092     // C++ [basic.link]p10:
4093     //   [...] the types specified by all declarations referring to a given
4094     //   object or function shall be identical, except that declarations for an
4095     //   array object can specify array types that differ by the presence or
4096     //   absence of a major array bound (8.3.4).
4097     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4098       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4099       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4100 
4101       // We are merging a variable declaration New into Old. If it has an array
4102       // bound, and that bound differs from Old's bound, we should diagnose the
4103       // mismatch.
4104       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4105         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4106              PrevVD = PrevVD->getPreviousDecl()) {
4107           QualType PrevVDTy = PrevVD->getType();
4108           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4109             continue;
4110 
4111           if (!Context.hasSameType(New->getType(), PrevVDTy))
4112             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4113         }
4114       }
4115 
4116       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4117         if (Context.hasSameType(OldArray->getElementType(),
4118                                 NewArray->getElementType()))
4119           MergedT = New->getType();
4120       }
4121       // FIXME: Check visibility. New is hidden but has a complete type. If New
4122       // has no array bound, it should not inherit one from Old, if Old is not
4123       // visible.
4124       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4125         if (Context.hasSameType(OldArray->getElementType(),
4126                                 NewArray->getElementType()))
4127           MergedT = Old->getType();
4128       }
4129     }
4130     else if (New->getType()->isObjCObjectPointerType() &&
4131                Old->getType()->isObjCObjectPointerType()) {
4132       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4133                                               Old->getType());
4134     }
4135   } else {
4136     // C 6.2.7p2:
4137     //   All declarations that refer to the same object or function shall have
4138     //   compatible type.
4139     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4140   }
4141   if (MergedT.isNull()) {
4142     // It's OK if we couldn't merge types if either type is dependent, for a
4143     // block-scope variable. In other cases (static data members of class
4144     // templates, variable templates, ...), we require the types to be
4145     // equivalent.
4146     // FIXME: The C++ standard doesn't say anything about this.
4147     if ((New->getType()->isDependentType() ||
4148          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4149       // If the old type was dependent, we can't merge with it, so the new type
4150       // becomes dependent for now. We'll reproduce the original type when we
4151       // instantiate the TypeSourceInfo for the variable.
4152       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4153         New->setType(Context.DependentTy);
4154       return;
4155     }
4156     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4157   }
4158 
4159   // Don't actually update the type on the new declaration if the old
4160   // declaration was an extern declaration in a different scope.
4161   if (MergeTypeWithOld)
4162     New->setType(MergedT);
4163 }
4164 
4165 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4166                                   LookupResult &Previous) {
4167   // C11 6.2.7p4:
4168   //   For an identifier with internal or external linkage declared
4169   //   in a scope in which a prior declaration of that identifier is
4170   //   visible, if the prior declaration specifies internal or
4171   //   external linkage, the type of the identifier at the later
4172   //   declaration becomes the composite type.
4173   //
4174   // If the variable isn't visible, we do not merge with its type.
4175   if (Previous.isShadowed())
4176     return false;
4177 
4178   if (S.getLangOpts().CPlusPlus) {
4179     // C++11 [dcl.array]p3:
4180     //   If there is a preceding declaration of the entity in the same
4181     //   scope in which the bound was specified, an omitted array bound
4182     //   is taken to be the same as in that earlier declaration.
4183     return NewVD->isPreviousDeclInSameBlockScope() ||
4184            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4185             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4186   } else {
4187     // If the old declaration was function-local, don't merge with its
4188     // type unless we're in the same function.
4189     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4190            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4191   }
4192 }
4193 
4194 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4195 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4196 /// situation, merging decls or emitting diagnostics as appropriate.
4197 ///
4198 /// Tentative definition rules (C99 6.9.2p2) are checked by
4199 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4200 /// definitions here, since the initializer hasn't been attached.
4201 ///
4202 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4203   // If the new decl is already invalid, don't do any other checking.
4204   if (New->isInvalidDecl())
4205     return;
4206 
4207   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4208     return;
4209 
4210   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4211 
4212   // Verify the old decl was also a variable or variable template.
4213   VarDecl *Old = nullptr;
4214   VarTemplateDecl *OldTemplate = nullptr;
4215   if (Previous.isSingleResult()) {
4216     if (NewTemplate) {
4217       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4218       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4219 
4220       if (auto *Shadow =
4221               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4222         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4223           return New->setInvalidDecl();
4224     } else {
4225       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4226 
4227       if (auto *Shadow =
4228               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4229         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4230           return New->setInvalidDecl();
4231     }
4232   }
4233   if (!Old) {
4234     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4235         << New->getDeclName();
4236     notePreviousDefinition(Previous.getRepresentativeDecl(),
4237                            New->getLocation());
4238     return New->setInvalidDecl();
4239   }
4240 
4241   // If the old declaration was found in an inline namespace and the new
4242   // declaration was qualified, update the DeclContext to match.
4243   adjustDeclContextForDeclaratorDecl(New, Old);
4244 
4245   // Ensure the template parameters are compatible.
4246   if (NewTemplate &&
4247       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4248                                       OldTemplate->getTemplateParameters(),
4249                                       /*Complain=*/true, TPL_TemplateMatch))
4250     return New->setInvalidDecl();
4251 
4252   // C++ [class.mem]p1:
4253   //   A member shall not be declared twice in the member-specification [...]
4254   //
4255   // Here, we need only consider static data members.
4256   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4257     Diag(New->getLocation(), diag::err_duplicate_member)
4258       << New->getIdentifier();
4259     Diag(Old->getLocation(), diag::note_previous_declaration);
4260     New->setInvalidDecl();
4261   }
4262 
4263   mergeDeclAttributes(New, Old);
4264   // Warn if an already-declared variable is made a weak_import in a subsequent
4265   // declaration
4266   if (New->hasAttr<WeakImportAttr>() &&
4267       Old->getStorageClass() == SC_None &&
4268       !Old->hasAttr<WeakImportAttr>()) {
4269     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4270     Diag(Old->getLocation(), diag::note_previous_declaration);
4271     // Remove weak_import attribute on new declaration.
4272     New->dropAttr<WeakImportAttr>();
4273   }
4274 
4275   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4276     if (!Old->hasAttr<InternalLinkageAttr>()) {
4277       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4278           << ILA;
4279       Diag(Old->getLocation(), diag::note_previous_declaration);
4280       New->dropAttr<InternalLinkageAttr>();
4281     }
4282 
4283   // Merge the types.
4284   VarDecl *MostRecent = Old->getMostRecentDecl();
4285   if (MostRecent != Old) {
4286     MergeVarDeclTypes(New, MostRecent,
4287                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4288     if (New->isInvalidDecl())
4289       return;
4290   }
4291 
4292   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4293   if (New->isInvalidDecl())
4294     return;
4295 
4296   diag::kind PrevDiag;
4297   SourceLocation OldLocation;
4298   std::tie(PrevDiag, OldLocation) =
4299       getNoteDiagForInvalidRedeclaration(Old, New);
4300 
4301   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4302   if (New->getStorageClass() == SC_Static &&
4303       !New->isStaticDataMember() &&
4304       Old->hasExternalFormalLinkage()) {
4305     if (getLangOpts().MicrosoftExt) {
4306       Diag(New->getLocation(), diag::ext_static_non_static)
4307           << New->getDeclName();
4308       Diag(OldLocation, PrevDiag);
4309     } else {
4310       Diag(New->getLocation(), diag::err_static_non_static)
4311           << New->getDeclName();
4312       Diag(OldLocation, PrevDiag);
4313       return New->setInvalidDecl();
4314     }
4315   }
4316   // C99 6.2.2p4:
4317   //   For an identifier declared with the storage-class specifier
4318   //   extern in a scope in which a prior declaration of that
4319   //   identifier is visible,23) if the prior declaration specifies
4320   //   internal or external linkage, the linkage of the identifier at
4321   //   the later declaration is the same as the linkage specified at
4322   //   the prior declaration. If no prior declaration is visible, or
4323   //   if the prior declaration specifies no linkage, then the
4324   //   identifier has external linkage.
4325   if (New->hasExternalStorage() && Old->hasLinkage())
4326     /* Okay */;
4327   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4328            !New->isStaticDataMember() &&
4329            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4330     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4331     Diag(OldLocation, PrevDiag);
4332     return New->setInvalidDecl();
4333   }
4334 
4335   // Check if extern is followed by non-extern and vice-versa.
4336   if (New->hasExternalStorage() &&
4337       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4338     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4339     Diag(OldLocation, PrevDiag);
4340     return New->setInvalidDecl();
4341   }
4342   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4343       !New->hasExternalStorage()) {
4344     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4345     Diag(OldLocation, PrevDiag);
4346     return New->setInvalidDecl();
4347   }
4348 
4349   if (CheckRedeclarationInModule(New, Old))
4350     return;
4351 
4352   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4353 
4354   // FIXME: The test for external storage here seems wrong? We still
4355   // need to check for mismatches.
4356   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4357       // Don't complain about out-of-line definitions of static members.
4358       !(Old->getLexicalDeclContext()->isRecord() &&
4359         !New->getLexicalDeclContext()->isRecord())) {
4360     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4361     Diag(OldLocation, PrevDiag);
4362     return New->setInvalidDecl();
4363   }
4364 
4365   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4366     if (VarDecl *Def = Old->getDefinition()) {
4367       // C++1z [dcl.fcn.spec]p4:
4368       //   If the definition of a variable appears in a translation unit before
4369       //   its first declaration as inline, the program is ill-formed.
4370       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4371       Diag(Def->getLocation(), diag::note_previous_definition);
4372     }
4373   }
4374 
4375   // If this redeclaration makes the variable inline, we may need to add it to
4376   // UndefinedButUsed.
4377   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4378       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4379     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4380                                            SourceLocation()));
4381 
4382   if (New->getTLSKind() != Old->getTLSKind()) {
4383     if (!Old->getTLSKind()) {
4384       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4385       Diag(OldLocation, PrevDiag);
4386     } else if (!New->getTLSKind()) {
4387       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4388       Diag(OldLocation, PrevDiag);
4389     } else {
4390       // Do not allow redeclaration to change the variable between requiring
4391       // static and dynamic initialization.
4392       // FIXME: GCC allows this, but uses the TLS keyword on the first
4393       // declaration to determine the kind. Do we need to be compatible here?
4394       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4395         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4396       Diag(OldLocation, PrevDiag);
4397     }
4398   }
4399 
4400   // C++ doesn't have tentative definitions, so go right ahead and check here.
4401   if (getLangOpts().CPlusPlus &&
4402       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4403     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4404         Old->getCanonicalDecl()->isConstexpr()) {
4405       // This definition won't be a definition any more once it's been merged.
4406       Diag(New->getLocation(),
4407            diag::warn_deprecated_redundant_constexpr_static_def);
4408     } else if (VarDecl *Def = Old->getDefinition()) {
4409       if (checkVarDeclRedefinition(Def, New))
4410         return;
4411     }
4412   }
4413 
4414   if (haveIncompatibleLanguageLinkages(Old, New)) {
4415     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4416     Diag(OldLocation, PrevDiag);
4417     New->setInvalidDecl();
4418     return;
4419   }
4420 
4421   // Merge "used" flag.
4422   if (Old->getMostRecentDecl()->isUsed(false))
4423     New->setIsUsed();
4424 
4425   // Keep a chain of previous declarations.
4426   New->setPreviousDecl(Old);
4427   if (NewTemplate)
4428     NewTemplate->setPreviousDecl(OldTemplate);
4429 
4430   // Inherit access appropriately.
4431   New->setAccess(Old->getAccess());
4432   if (NewTemplate)
4433     NewTemplate->setAccess(New->getAccess());
4434 
4435   if (Old->isInline())
4436     New->setImplicitlyInline();
4437 }
4438 
4439 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4440   SourceManager &SrcMgr = getSourceManager();
4441   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4442   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4443   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4444   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4445   auto &HSI = PP.getHeaderSearchInfo();
4446   StringRef HdrFilename =
4447       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4448 
4449   auto noteFromModuleOrInclude = [&](Module *Mod,
4450                                      SourceLocation IncLoc) -> bool {
4451     // Redefinition errors with modules are common with non modular mapped
4452     // headers, example: a non-modular header H in module A that also gets
4453     // included directly in a TU. Pointing twice to the same header/definition
4454     // is confusing, try to get better diagnostics when modules is on.
4455     if (IncLoc.isValid()) {
4456       if (Mod) {
4457         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4458             << HdrFilename.str() << Mod->getFullModuleName();
4459         if (!Mod->DefinitionLoc.isInvalid())
4460           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4461               << Mod->getFullModuleName();
4462       } else {
4463         Diag(IncLoc, diag::note_redefinition_include_same_file)
4464             << HdrFilename.str();
4465       }
4466       return true;
4467     }
4468 
4469     return false;
4470   };
4471 
4472   // Is it the same file and same offset? Provide more information on why
4473   // this leads to a redefinition error.
4474   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4475     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4476     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4477     bool EmittedDiag =
4478         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4479     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4480 
4481     // If the header has no guards, emit a note suggesting one.
4482     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4483       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4484 
4485     if (EmittedDiag)
4486       return;
4487   }
4488 
4489   // Redefinition coming from different files or couldn't do better above.
4490   if (Old->getLocation().isValid())
4491     Diag(Old->getLocation(), diag::note_previous_definition);
4492 }
4493 
4494 /// We've just determined that \p Old and \p New both appear to be definitions
4495 /// of the same variable. Either diagnose or fix the problem.
4496 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4497   if (!hasVisibleDefinition(Old) &&
4498       (New->getFormalLinkage() == InternalLinkage ||
4499        New->isInline() ||
4500        New->getDescribedVarTemplate() ||
4501        New->getNumTemplateParameterLists() ||
4502        New->getDeclContext()->isDependentContext())) {
4503     // The previous definition is hidden, and multiple definitions are
4504     // permitted (in separate TUs). Demote this to a declaration.
4505     New->demoteThisDefinitionToDeclaration();
4506 
4507     // Make the canonical definition visible.
4508     if (auto *OldTD = Old->getDescribedVarTemplate())
4509       makeMergedDefinitionVisible(OldTD);
4510     makeMergedDefinitionVisible(Old);
4511     return false;
4512   } else {
4513     Diag(New->getLocation(), diag::err_redefinition) << New;
4514     notePreviousDefinition(Old, New->getLocation());
4515     New->setInvalidDecl();
4516     return true;
4517   }
4518 }
4519 
4520 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4521 /// no declarator (e.g. "struct foo;") is parsed.
4522 Decl *
4523 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4524                                  RecordDecl *&AnonRecord) {
4525   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4526                                     AnonRecord);
4527 }
4528 
4529 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4530 // disambiguate entities defined in different scopes.
4531 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4532 // compatibility.
4533 // We will pick our mangling number depending on which version of MSVC is being
4534 // targeted.
4535 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4536   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4537              ? S->getMSCurManglingNumber()
4538              : S->getMSLastManglingNumber();
4539 }
4540 
4541 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4542   if (!Context.getLangOpts().CPlusPlus)
4543     return;
4544 
4545   if (isa<CXXRecordDecl>(Tag->getParent())) {
4546     // If this tag is the direct child of a class, number it if
4547     // it is anonymous.
4548     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4549       return;
4550     MangleNumberingContext &MCtx =
4551         Context.getManglingNumberContext(Tag->getParent());
4552     Context.setManglingNumber(
4553         Tag, MCtx.getManglingNumber(
4554                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4555     return;
4556   }
4557 
4558   // If this tag isn't a direct child of a class, number it if it is local.
4559   MangleNumberingContext *MCtx;
4560   Decl *ManglingContextDecl;
4561   std::tie(MCtx, ManglingContextDecl) =
4562       getCurrentMangleNumberContext(Tag->getDeclContext());
4563   if (MCtx) {
4564     Context.setManglingNumber(
4565         Tag, MCtx->getManglingNumber(
4566                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4567   }
4568 }
4569 
4570 namespace {
4571 struct NonCLikeKind {
4572   enum {
4573     None,
4574     BaseClass,
4575     DefaultMemberInit,
4576     Lambda,
4577     Friend,
4578     OtherMember,
4579     Invalid,
4580   } Kind = None;
4581   SourceRange Range;
4582 
4583   explicit operator bool() { return Kind != None; }
4584 };
4585 }
4586 
4587 /// Determine whether a class is C-like, according to the rules of C++
4588 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4589 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4590   if (RD->isInvalidDecl())
4591     return {NonCLikeKind::Invalid, {}};
4592 
4593   // C++ [dcl.typedef]p9: [P1766R1]
4594   //   An unnamed class with a typedef name for linkage purposes shall not
4595   //
4596   //    -- have any base classes
4597   if (RD->getNumBases())
4598     return {NonCLikeKind::BaseClass,
4599             SourceRange(RD->bases_begin()->getBeginLoc(),
4600                         RD->bases_end()[-1].getEndLoc())};
4601   bool Invalid = false;
4602   for (Decl *D : RD->decls()) {
4603     // Don't complain about things we already diagnosed.
4604     if (D->isInvalidDecl()) {
4605       Invalid = true;
4606       continue;
4607     }
4608 
4609     //  -- have any [...] default member initializers
4610     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4611       if (FD->hasInClassInitializer()) {
4612         auto *Init = FD->getInClassInitializer();
4613         return {NonCLikeKind::DefaultMemberInit,
4614                 Init ? Init->getSourceRange() : D->getSourceRange()};
4615       }
4616       continue;
4617     }
4618 
4619     // FIXME: We don't allow friend declarations. This violates the wording of
4620     // P1766, but not the intent.
4621     if (isa<FriendDecl>(D))
4622       return {NonCLikeKind::Friend, D->getSourceRange()};
4623 
4624     //  -- declare any members other than non-static data members, member
4625     //     enumerations, or member classes,
4626     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4627         isa<EnumDecl>(D))
4628       continue;
4629     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4630     if (!MemberRD) {
4631       if (D->isImplicit())
4632         continue;
4633       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4634     }
4635 
4636     //  -- contain a lambda-expression,
4637     if (MemberRD->isLambda())
4638       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4639 
4640     //  and all member classes shall also satisfy these requirements
4641     //  (recursively).
4642     if (MemberRD->isThisDeclarationADefinition()) {
4643       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4644         return Kind;
4645     }
4646   }
4647 
4648   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4649 }
4650 
4651 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4652                                         TypedefNameDecl *NewTD) {
4653   if (TagFromDeclSpec->isInvalidDecl())
4654     return;
4655 
4656   // Do nothing if the tag already has a name for linkage purposes.
4657   if (TagFromDeclSpec->hasNameForLinkage())
4658     return;
4659 
4660   // A well-formed anonymous tag must always be a TUK_Definition.
4661   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4662 
4663   // The type must match the tag exactly;  no qualifiers allowed.
4664   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4665                            Context.getTagDeclType(TagFromDeclSpec))) {
4666     if (getLangOpts().CPlusPlus)
4667       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4668     return;
4669   }
4670 
4671   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4672   //   An unnamed class with a typedef name for linkage purposes shall [be
4673   //   C-like].
4674   //
4675   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4676   // shouldn't happen, but there are constructs that the language rule doesn't
4677   // disallow for which we can't reasonably avoid computing linkage early.
4678   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4679   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4680                              : NonCLikeKind();
4681   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4682   if (NonCLike || ChangesLinkage) {
4683     if (NonCLike.Kind == NonCLikeKind::Invalid)
4684       return;
4685 
4686     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4687     if (ChangesLinkage) {
4688       // If the linkage changes, we can't accept this as an extension.
4689       if (NonCLike.Kind == NonCLikeKind::None)
4690         DiagID = diag::err_typedef_changes_linkage;
4691       else
4692         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4693     }
4694 
4695     SourceLocation FixitLoc =
4696         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4697     llvm::SmallString<40> TextToInsert;
4698     TextToInsert += ' ';
4699     TextToInsert += NewTD->getIdentifier()->getName();
4700 
4701     Diag(FixitLoc, DiagID)
4702       << isa<TypeAliasDecl>(NewTD)
4703       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4704     if (NonCLike.Kind != NonCLikeKind::None) {
4705       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4706         << NonCLike.Kind - 1 << NonCLike.Range;
4707     }
4708     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4709       << NewTD << isa<TypeAliasDecl>(NewTD);
4710 
4711     if (ChangesLinkage)
4712       return;
4713   }
4714 
4715   // Otherwise, set this as the anon-decl typedef for the tag.
4716   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4717 }
4718 
4719 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4720   switch (T) {
4721   case DeclSpec::TST_class:
4722     return 0;
4723   case DeclSpec::TST_struct:
4724     return 1;
4725   case DeclSpec::TST_interface:
4726     return 2;
4727   case DeclSpec::TST_union:
4728     return 3;
4729   case DeclSpec::TST_enum:
4730     return 4;
4731   default:
4732     llvm_unreachable("unexpected type specifier");
4733   }
4734 }
4735 
4736 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4737 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4738 /// parameters to cope with template friend declarations.
4739 Decl *
4740 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4741                                  MultiTemplateParamsArg TemplateParams,
4742                                  bool IsExplicitInstantiation,
4743                                  RecordDecl *&AnonRecord) {
4744   Decl *TagD = nullptr;
4745   TagDecl *Tag = nullptr;
4746   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4747       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4748       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4749       DS.getTypeSpecType() == DeclSpec::TST_union ||
4750       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4751     TagD = DS.getRepAsDecl();
4752 
4753     if (!TagD) // We probably had an error
4754       return nullptr;
4755 
4756     // Note that the above type specs guarantee that the
4757     // type rep is a Decl, whereas in many of the others
4758     // it's a Type.
4759     if (isa<TagDecl>(TagD))
4760       Tag = cast<TagDecl>(TagD);
4761     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4762       Tag = CTD->getTemplatedDecl();
4763   }
4764 
4765   if (Tag) {
4766     handleTagNumbering(Tag, S);
4767     Tag->setFreeStanding();
4768     if (Tag->isInvalidDecl())
4769       return Tag;
4770   }
4771 
4772   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4773     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4774     // or incomplete types shall not be restrict-qualified."
4775     if (TypeQuals & DeclSpec::TQ_restrict)
4776       Diag(DS.getRestrictSpecLoc(),
4777            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4778            << DS.getSourceRange();
4779   }
4780 
4781   if (DS.isInlineSpecified())
4782     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4783         << getLangOpts().CPlusPlus17;
4784 
4785   if (DS.hasConstexprSpecifier()) {
4786     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4787     // and definitions of functions and variables.
4788     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4789     // the declaration of a function or function template
4790     if (Tag)
4791       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4792           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4793           << static_cast<int>(DS.getConstexprSpecifier());
4794     else
4795       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4796           << static_cast<int>(DS.getConstexprSpecifier());
4797     // Don't emit warnings after this error.
4798     return TagD;
4799   }
4800 
4801   DiagnoseFunctionSpecifiers(DS);
4802 
4803   if (DS.isFriendSpecified()) {
4804     // If we're dealing with a decl but not a TagDecl, assume that
4805     // whatever routines created it handled the friendship aspect.
4806     if (TagD && !Tag)
4807       return nullptr;
4808     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4809   }
4810 
4811   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4812   bool IsExplicitSpecialization =
4813     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4814   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4815       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4816       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4817     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4818     // nested-name-specifier unless it is an explicit instantiation
4819     // or an explicit specialization.
4820     //
4821     // FIXME: We allow class template partial specializations here too, per the
4822     // obvious intent of DR1819.
4823     //
4824     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4825     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4826         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4827     return nullptr;
4828   }
4829 
4830   // Track whether this decl-specifier declares anything.
4831   bool DeclaresAnything = true;
4832 
4833   // Handle anonymous struct definitions.
4834   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4835     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4836         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4837       if (getLangOpts().CPlusPlus ||
4838           Record->getDeclContext()->isRecord()) {
4839         // If CurContext is a DeclContext that can contain statements,
4840         // RecursiveASTVisitor won't visit the decls that
4841         // BuildAnonymousStructOrUnion() will put into CurContext.
4842         // Also store them here so that they can be part of the
4843         // DeclStmt that gets created in this case.
4844         // FIXME: Also return the IndirectFieldDecls created by
4845         // BuildAnonymousStructOr union, for the same reason?
4846         if (CurContext->isFunctionOrMethod())
4847           AnonRecord = Record;
4848         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4849                                            Context.getPrintingPolicy());
4850       }
4851 
4852       DeclaresAnything = false;
4853     }
4854   }
4855 
4856   // C11 6.7.2.1p2:
4857   //   A struct-declaration that does not declare an anonymous structure or
4858   //   anonymous union shall contain a struct-declarator-list.
4859   //
4860   // This rule also existed in C89 and C99; the grammar for struct-declaration
4861   // did not permit a struct-declaration without a struct-declarator-list.
4862   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4863       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4864     // Check for Microsoft C extension: anonymous struct/union member.
4865     // Handle 2 kinds of anonymous struct/union:
4866     //   struct STRUCT;
4867     //   union UNION;
4868     // and
4869     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4870     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4871     if ((Tag && Tag->getDeclName()) ||
4872         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4873       RecordDecl *Record = nullptr;
4874       if (Tag)
4875         Record = dyn_cast<RecordDecl>(Tag);
4876       else if (const RecordType *RT =
4877                    DS.getRepAsType().get()->getAsStructureType())
4878         Record = RT->getDecl();
4879       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4880         Record = UT->getDecl();
4881 
4882       if (Record && getLangOpts().MicrosoftExt) {
4883         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4884             << Record->isUnion() << DS.getSourceRange();
4885         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4886       }
4887 
4888       DeclaresAnything = false;
4889     }
4890   }
4891 
4892   // Skip all the checks below if we have a type error.
4893   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4894       (TagD && TagD->isInvalidDecl()))
4895     return TagD;
4896 
4897   if (getLangOpts().CPlusPlus &&
4898       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4899     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4900       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4901           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4902         DeclaresAnything = false;
4903 
4904   if (!DS.isMissingDeclaratorOk()) {
4905     // Customize diagnostic for a typedef missing a name.
4906     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4907       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4908           << DS.getSourceRange();
4909     else
4910       DeclaresAnything = false;
4911   }
4912 
4913   if (DS.isModulePrivateSpecified() &&
4914       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4915     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4916       << Tag->getTagKind()
4917       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4918 
4919   ActOnDocumentableDecl(TagD);
4920 
4921   // C 6.7/2:
4922   //   A declaration [...] shall declare at least a declarator [...], a tag,
4923   //   or the members of an enumeration.
4924   // C++ [dcl.dcl]p3:
4925   //   [If there are no declarators], and except for the declaration of an
4926   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4927   //   names into the program, or shall redeclare a name introduced by a
4928   //   previous declaration.
4929   if (!DeclaresAnything) {
4930     // In C, we allow this as a (popular) extension / bug. Don't bother
4931     // producing further diagnostics for redundant qualifiers after this.
4932     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4933                                ? diag::err_no_declarators
4934                                : diag::ext_no_declarators)
4935         << DS.getSourceRange();
4936     return TagD;
4937   }
4938 
4939   // C++ [dcl.stc]p1:
4940   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4941   //   init-declarator-list of the declaration shall not be empty.
4942   // C++ [dcl.fct.spec]p1:
4943   //   If a cv-qualifier appears in a decl-specifier-seq, the
4944   //   init-declarator-list of the declaration shall not be empty.
4945   //
4946   // Spurious qualifiers here appear to be valid in C.
4947   unsigned DiagID = diag::warn_standalone_specifier;
4948   if (getLangOpts().CPlusPlus)
4949     DiagID = diag::ext_standalone_specifier;
4950 
4951   // Note that a linkage-specification sets a storage class, but
4952   // 'extern "C" struct foo;' is actually valid and not theoretically
4953   // useless.
4954   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4955     if (SCS == DeclSpec::SCS_mutable)
4956       // Since mutable is not a viable storage class specifier in C, there is
4957       // no reason to treat it as an extension. Instead, diagnose as an error.
4958       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4959     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4960       Diag(DS.getStorageClassSpecLoc(), DiagID)
4961         << DeclSpec::getSpecifierName(SCS);
4962   }
4963 
4964   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4965     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4966       << DeclSpec::getSpecifierName(TSCS);
4967   if (DS.getTypeQualifiers()) {
4968     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4969       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4970     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4971       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4972     // Restrict is covered above.
4973     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4974       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4975     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4976       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4977   }
4978 
4979   // Warn about ignored type attributes, for example:
4980   // __attribute__((aligned)) struct A;
4981   // Attributes should be placed after tag to apply to type declaration.
4982   if (!DS.getAttributes().empty()) {
4983     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4984     if (TypeSpecType == DeclSpec::TST_class ||
4985         TypeSpecType == DeclSpec::TST_struct ||
4986         TypeSpecType == DeclSpec::TST_interface ||
4987         TypeSpecType == DeclSpec::TST_union ||
4988         TypeSpecType == DeclSpec::TST_enum) {
4989       for (const ParsedAttr &AL : DS.getAttributes())
4990         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4991             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4992     }
4993   }
4994 
4995   return TagD;
4996 }
4997 
4998 /// We are trying to inject an anonymous member into the given scope;
4999 /// check if there's an existing declaration that can't be overloaded.
5000 ///
5001 /// \return true if this is a forbidden redeclaration
5002 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5003                                          Scope *S,
5004                                          DeclContext *Owner,
5005                                          DeclarationName Name,
5006                                          SourceLocation NameLoc,
5007                                          bool IsUnion) {
5008   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5009                  Sema::ForVisibleRedeclaration);
5010   if (!SemaRef.LookupName(R, S)) return false;
5011 
5012   // Pick a representative declaration.
5013   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5014   assert(PrevDecl && "Expected a non-null Decl");
5015 
5016   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5017     return false;
5018 
5019   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5020     << IsUnion << Name;
5021   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5022 
5023   return true;
5024 }
5025 
5026 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5027 /// anonymous struct or union AnonRecord into the owning context Owner
5028 /// and scope S. This routine will be invoked just after we realize
5029 /// that an unnamed union or struct is actually an anonymous union or
5030 /// struct, e.g.,
5031 ///
5032 /// @code
5033 /// union {
5034 ///   int i;
5035 ///   float f;
5036 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5037 ///    // f into the surrounding scope.x
5038 /// @endcode
5039 ///
5040 /// This routine is recursive, injecting the names of nested anonymous
5041 /// structs/unions into the owning context and scope as well.
5042 static bool
5043 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5044                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5045                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5046   bool Invalid = false;
5047 
5048   // Look every FieldDecl and IndirectFieldDecl with a name.
5049   for (auto *D : AnonRecord->decls()) {
5050     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5051         cast<NamedDecl>(D)->getDeclName()) {
5052       ValueDecl *VD = cast<ValueDecl>(D);
5053       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5054                                        VD->getLocation(),
5055                                        AnonRecord->isUnion())) {
5056         // C++ [class.union]p2:
5057         //   The names of the members of an anonymous union shall be
5058         //   distinct from the names of any other entity in the
5059         //   scope in which the anonymous union is declared.
5060         Invalid = true;
5061       } else {
5062         // C++ [class.union]p2:
5063         //   For the purpose of name lookup, after the anonymous union
5064         //   definition, the members of the anonymous union are
5065         //   considered to have been defined in the scope in which the
5066         //   anonymous union is declared.
5067         unsigned OldChainingSize = Chaining.size();
5068         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5069           Chaining.append(IF->chain_begin(), IF->chain_end());
5070         else
5071           Chaining.push_back(VD);
5072 
5073         assert(Chaining.size() >= 2);
5074         NamedDecl **NamedChain =
5075           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5076         for (unsigned i = 0; i < Chaining.size(); i++)
5077           NamedChain[i] = Chaining[i];
5078 
5079         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5080             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5081             VD->getType(), {NamedChain, Chaining.size()});
5082 
5083         for (const auto *Attr : VD->attrs())
5084           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5085 
5086         IndirectField->setAccess(AS);
5087         IndirectField->setImplicit();
5088         SemaRef.PushOnScopeChains(IndirectField, S);
5089 
5090         // That includes picking up the appropriate access specifier.
5091         if (AS != AS_none) IndirectField->setAccess(AS);
5092 
5093         Chaining.resize(OldChainingSize);
5094       }
5095     }
5096   }
5097 
5098   return Invalid;
5099 }
5100 
5101 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5102 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5103 /// illegal input values are mapped to SC_None.
5104 static StorageClass
5105 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5106   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5107   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5108          "Parser allowed 'typedef' as storage class VarDecl.");
5109   switch (StorageClassSpec) {
5110   case DeclSpec::SCS_unspecified:    return SC_None;
5111   case DeclSpec::SCS_extern:
5112     if (DS.isExternInLinkageSpec())
5113       return SC_None;
5114     return SC_Extern;
5115   case DeclSpec::SCS_static:         return SC_Static;
5116   case DeclSpec::SCS_auto:           return SC_Auto;
5117   case DeclSpec::SCS_register:       return SC_Register;
5118   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5119     // Illegal SCSs map to None: error reporting is up to the caller.
5120   case DeclSpec::SCS_mutable:        // Fall through.
5121   case DeclSpec::SCS_typedef:        return SC_None;
5122   }
5123   llvm_unreachable("unknown storage class specifier");
5124 }
5125 
5126 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5127   assert(Record->hasInClassInitializer());
5128 
5129   for (const auto *I : Record->decls()) {
5130     const auto *FD = dyn_cast<FieldDecl>(I);
5131     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5132       FD = IFD->getAnonField();
5133     if (FD && FD->hasInClassInitializer())
5134       return FD->getLocation();
5135   }
5136 
5137   llvm_unreachable("couldn't find in-class initializer");
5138 }
5139 
5140 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5141                                       SourceLocation DefaultInitLoc) {
5142   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5143     return;
5144 
5145   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5146   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5147 }
5148 
5149 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5150                                       CXXRecordDecl *AnonUnion) {
5151   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5152     return;
5153 
5154   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5155 }
5156 
5157 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5158 /// anonymous structure or union. Anonymous unions are a C++ feature
5159 /// (C++ [class.union]) and a C11 feature; anonymous structures
5160 /// are a C11 feature and GNU C++ extension.
5161 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5162                                         AccessSpecifier AS,
5163                                         RecordDecl *Record,
5164                                         const PrintingPolicy &Policy) {
5165   DeclContext *Owner = Record->getDeclContext();
5166 
5167   // Diagnose whether this anonymous struct/union is an extension.
5168   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5169     Diag(Record->getLocation(), diag::ext_anonymous_union);
5170   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5171     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5172   else if (!Record->isUnion() && !getLangOpts().C11)
5173     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5174 
5175   // C and C++ require different kinds of checks for anonymous
5176   // structs/unions.
5177   bool Invalid = false;
5178   if (getLangOpts().CPlusPlus) {
5179     const char *PrevSpec = nullptr;
5180     if (Record->isUnion()) {
5181       // C++ [class.union]p6:
5182       // C++17 [class.union.anon]p2:
5183       //   Anonymous unions declared in a named namespace or in the
5184       //   global namespace shall be declared static.
5185       unsigned DiagID;
5186       DeclContext *OwnerScope = Owner->getRedeclContext();
5187       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5188           (OwnerScope->isTranslationUnit() ||
5189            (OwnerScope->isNamespace() &&
5190             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5191         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5192           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5193 
5194         // Recover by adding 'static'.
5195         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5196                                PrevSpec, DiagID, Policy);
5197       }
5198       // C++ [class.union]p6:
5199       //   A storage class is not allowed in a declaration of an
5200       //   anonymous union in a class scope.
5201       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5202                isa<RecordDecl>(Owner)) {
5203         Diag(DS.getStorageClassSpecLoc(),
5204              diag::err_anonymous_union_with_storage_spec)
5205           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5206 
5207         // Recover by removing the storage specifier.
5208         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5209                                SourceLocation(),
5210                                PrevSpec, DiagID, Context.getPrintingPolicy());
5211       }
5212     }
5213 
5214     // Ignore const/volatile/restrict qualifiers.
5215     if (DS.getTypeQualifiers()) {
5216       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5217         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5218           << Record->isUnion() << "const"
5219           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5220       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5221         Diag(DS.getVolatileSpecLoc(),
5222              diag::ext_anonymous_struct_union_qualified)
5223           << Record->isUnion() << "volatile"
5224           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5225       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5226         Diag(DS.getRestrictSpecLoc(),
5227              diag::ext_anonymous_struct_union_qualified)
5228           << Record->isUnion() << "restrict"
5229           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5230       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5231         Diag(DS.getAtomicSpecLoc(),
5232              diag::ext_anonymous_struct_union_qualified)
5233           << Record->isUnion() << "_Atomic"
5234           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5235       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5236         Diag(DS.getUnalignedSpecLoc(),
5237              diag::ext_anonymous_struct_union_qualified)
5238           << Record->isUnion() << "__unaligned"
5239           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5240 
5241       DS.ClearTypeQualifiers();
5242     }
5243 
5244     // C++ [class.union]p2:
5245     //   The member-specification of an anonymous union shall only
5246     //   define non-static data members. [Note: nested types and
5247     //   functions cannot be declared within an anonymous union. ]
5248     for (auto *Mem : Record->decls()) {
5249       // Ignore invalid declarations; we already diagnosed them.
5250       if (Mem->isInvalidDecl())
5251         continue;
5252 
5253       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5254         // C++ [class.union]p3:
5255         //   An anonymous union shall not have private or protected
5256         //   members (clause 11).
5257         assert(FD->getAccess() != AS_none);
5258         if (FD->getAccess() != AS_public) {
5259           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5260             << Record->isUnion() << (FD->getAccess() == AS_protected);
5261           Invalid = true;
5262         }
5263 
5264         // C++ [class.union]p1
5265         //   An object of a class with a non-trivial constructor, a non-trivial
5266         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5267         //   assignment operator cannot be a member of a union, nor can an
5268         //   array of such objects.
5269         if (CheckNontrivialField(FD))
5270           Invalid = true;
5271       } else if (Mem->isImplicit()) {
5272         // Any implicit members are fine.
5273       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5274         // This is a type that showed up in an
5275         // elaborated-type-specifier inside the anonymous struct or
5276         // union, but which actually declares a type outside of the
5277         // anonymous struct or union. It's okay.
5278       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5279         if (!MemRecord->isAnonymousStructOrUnion() &&
5280             MemRecord->getDeclName()) {
5281           // Visual C++ allows type definition in anonymous struct or union.
5282           if (getLangOpts().MicrosoftExt)
5283             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5284               << Record->isUnion();
5285           else {
5286             // This is a nested type declaration.
5287             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5288               << Record->isUnion();
5289             Invalid = true;
5290           }
5291         } else {
5292           // This is an anonymous type definition within another anonymous type.
5293           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5294           // not part of standard C++.
5295           Diag(MemRecord->getLocation(),
5296                diag::ext_anonymous_record_with_anonymous_type)
5297             << Record->isUnion();
5298         }
5299       } else if (isa<AccessSpecDecl>(Mem)) {
5300         // Any access specifier is fine.
5301       } else if (isa<StaticAssertDecl>(Mem)) {
5302         // In C++1z, static_assert declarations are also fine.
5303       } else {
5304         // We have something that isn't a non-static data
5305         // member. Complain about it.
5306         unsigned DK = diag::err_anonymous_record_bad_member;
5307         if (isa<TypeDecl>(Mem))
5308           DK = diag::err_anonymous_record_with_type;
5309         else if (isa<FunctionDecl>(Mem))
5310           DK = diag::err_anonymous_record_with_function;
5311         else if (isa<VarDecl>(Mem))
5312           DK = diag::err_anonymous_record_with_static;
5313 
5314         // Visual C++ allows type definition in anonymous struct or union.
5315         if (getLangOpts().MicrosoftExt &&
5316             DK == diag::err_anonymous_record_with_type)
5317           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5318             << Record->isUnion();
5319         else {
5320           Diag(Mem->getLocation(), DK) << Record->isUnion();
5321           Invalid = true;
5322         }
5323       }
5324     }
5325 
5326     // C++11 [class.union]p8 (DR1460):
5327     //   At most one variant member of a union may have a
5328     //   brace-or-equal-initializer.
5329     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5330         Owner->isRecord())
5331       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5332                                 cast<CXXRecordDecl>(Record));
5333   }
5334 
5335   if (!Record->isUnion() && !Owner->isRecord()) {
5336     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5337       << getLangOpts().CPlusPlus;
5338     Invalid = true;
5339   }
5340 
5341   // C++ [dcl.dcl]p3:
5342   //   [If there are no declarators], and except for the declaration of an
5343   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5344   //   names into the program
5345   // C++ [class.mem]p2:
5346   //   each such member-declaration shall either declare at least one member
5347   //   name of the class or declare at least one unnamed bit-field
5348   //
5349   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5350   if (getLangOpts().CPlusPlus && Record->field_empty())
5351     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5352 
5353   // Mock up a declarator.
5354   Declarator Dc(DS, DeclaratorContext::Member);
5355   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5356   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5357 
5358   // Create a declaration for this anonymous struct/union.
5359   NamedDecl *Anon = nullptr;
5360   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5361     Anon = FieldDecl::Create(
5362         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5363         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5364         /*BitWidth=*/nullptr, /*Mutable=*/false,
5365         /*InitStyle=*/ICIS_NoInit);
5366     Anon->setAccess(AS);
5367     ProcessDeclAttributes(S, Anon, Dc);
5368 
5369     if (getLangOpts().CPlusPlus)
5370       FieldCollector->Add(cast<FieldDecl>(Anon));
5371   } else {
5372     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5373     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5374     if (SCSpec == DeclSpec::SCS_mutable) {
5375       // mutable can only appear on non-static class members, so it's always
5376       // an error here
5377       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5378       Invalid = true;
5379       SC = SC_None;
5380     }
5381 
5382     assert(DS.getAttributes().empty() && "No attribute expected");
5383     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5384                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5385                            Context.getTypeDeclType(Record), TInfo, SC);
5386 
5387     // Default-initialize the implicit variable. This initialization will be
5388     // trivial in almost all cases, except if a union member has an in-class
5389     // initializer:
5390     //   union { int n = 0; };
5391     ActOnUninitializedDecl(Anon);
5392   }
5393   Anon->setImplicit();
5394 
5395   // Mark this as an anonymous struct/union type.
5396   Record->setAnonymousStructOrUnion(true);
5397 
5398   // Add the anonymous struct/union object to the current
5399   // context. We'll be referencing this object when we refer to one of
5400   // its members.
5401   Owner->addDecl(Anon);
5402 
5403   // Inject the members of the anonymous struct/union into the owning
5404   // context and into the identifier resolver chain for name lookup
5405   // purposes.
5406   SmallVector<NamedDecl*, 2> Chain;
5407   Chain.push_back(Anon);
5408 
5409   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5410     Invalid = true;
5411 
5412   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5413     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5414       MangleNumberingContext *MCtx;
5415       Decl *ManglingContextDecl;
5416       std::tie(MCtx, ManglingContextDecl) =
5417           getCurrentMangleNumberContext(NewVD->getDeclContext());
5418       if (MCtx) {
5419         Context.setManglingNumber(
5420             NewVD, MCtx->getManglingNumber(
5421                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5422         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5423       }
5424     }
5425   }
5426 
5427   if (Invalid)
5428     Anon->setInvalidDecl();
5429 
5430   return Anon;
5431 }
5432 
5433 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5434 /// Microsoft C anonymous structure.
5435 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5436 /// Example:
5437 ///
5438 /// struct A { int a; };
5439 /// struct B { struct A; int b; };
5440 ///
5441 /// void foo() {
5442 ///   B var;
5443 ///   var.a = 3;
5444 /// }
5445 ///
5446 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5447                                            RecordDecl *Record) {
5448   assert(Record && "expected a record!");
5449 
5450   // Mock up a declarator.
5451   Declarator Dc(DS, DeclaratorContext::TypeName);
5452   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5453   assert(TInfo && "couldn't build declarator info for anonymous struct");
5454 
5455   auto *ParentDecl = cast<RecordDecl>(CurContext);
5456   QualType RecTy = Context.getTypeDeclType(Record);
5457 
5458   // Create a declaration for this anonymous struct.
5459   NamedDecl *Anon =
5460       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5461                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5462                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5463                         /*InitStyle=*/ICIS_NoInit);
5464   Anon->setImplicit();
5465 
5466   // Add the anonymous struct object to the current context.
5467   CurContext->addDecl(Anon);
5468 
5469   // Inject the members of the anonymous struct into the current
5470   // context and into the identifier resolver chain for name lookup
5471   // purposes.
5472   SmallVector<NamedDecl*, 2> Chain;
5473   Chain.push_back(Anon);
5474 
5475   RecordDecl *RecordDef = Record->getDefinition();
5476   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5477                                diag::err_field_incomplete_or_sizeless) ||
5478       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5479                                           AS_none, Chain)) {
5480     Anon->setInvalidDecl();
5481     ParentDecl->setInvalidDecl();
5482   }
5483 
5484   return Anon;
5485 }
5486 
5487 /// GetNameForDeclarator - Determine the full declaration name for the
5488 /// given Declarator.
5489 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5490   return GetNameFromUnqualifiedId(D.getName());
5491 }
5492 
5493 /// Retrieves the declaration name from a parsed unqualified-id.
5494 DeclarationNameInfo
5495 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5496   DeclarationNameInfo NameInfo;
5497   NameInfo.setLoc(Name.StartLocation);
5498 
5499   switch (Name.getKind()) {
5500 
5501   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5502   case UnqualifiedIdKind::IK_Identifier:
5503     NameInfo.setName(Name.Identifier);
5504     return NameInfo;
5505 
5506   case UnqualifiedIdKind::IK_DeductionGuideName: {
5507     // C++ [temp.deduct.guide]p3:
5508     //   The simple-template-id shall name a class template specialization.
5509     //   The template-name shall be the same identifier as the template-name
5510     //   of the simple-template-id.
5511     // These together intend to imply that the template-name shall name a
5512     // class template.
5513     // FIXME: template<typename T> struct X {};
5514     //        template<typename T> using Y = X<T>;
5515     //        Y(int) -> Y<int>;
5516     //   satisfies these rules but does not name a class template.
5517     TemplateName TN = Name.TemplateName.get().get();
5518     auto *Template = TN.getAsTemplateDecl();
5519     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5520       Diag(Name.StartLocation,
5521            diag::err_deduction_guide_name_not_class_template)
5522         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5523       if (Template)
5524         Diag(Template->getLocation(), diag::note_template_decl_here);
5525       return DeclarationNameInfo();
5526     }
5527 
5528     NameInfo.setName(
5529         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5530     return NameInfo;
5531   }
5532 
5533   case UnqualifiedIdKind::IK_OperatorFunctionId:
5534     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5535                                            Name.OperatorFunctionId.Operator));
5536     NameInfo.setCXXOperatorNameRange(SourceRange(
5537         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5538     return NameInfo;
5539 
5540   case UnqualifiedIdKind::IK_LiteralOperatorId:
5541     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5542                                                            Name.Identifier));
5543     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5544     return NameInfo;
5545 
5546   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5547     TypeSourceInfo *TInfo;
5548     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5549     if (Ty.isNull())
5550       return DeclarationNameInfo();
5551     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5552                                                Context.getCanonicalType(Ty)));
5553     NameInfo.setNamedTypeInfo(TInfo);
5554     return NameInfo;
5555   }
5556 
5557   case UnqualifiedIdKind::IK_ConstructorName: {
5558     TypeSourceInfo *TInfo;
5559     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5560     if (Ty.isNull())
5561       return DeclarationNameInfo();
5562     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5563                                               Context.getCanonicalType(Ty)));
5564     NameInfo.setNamedTypeInfo(TInfo);
5565     return NameInfo;
5566   }
5567 
5568   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5569     // In well-formed code, we can only have a constructor
5570     // template-id that refers to the current context, so go there
5571     // to find the actual type being constructed.
5572     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5573     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5574       return DeclarationNameInfo();
5575 
5576     // Determine the type of the class being constructed.
5577     QualType CurClassType = Context.getTypeDeclType(CurClass);
5578 
5579     // FIXME: Check two things: that the template-id names the same type as
5580     // CurClassType, and that the template-id does not occur when the name
5581     // was qualified.
5582 
5583     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5584                                     Context.getCanonicalType(CurClassType)));
5585     // FIXME: should we retrieve TypeSourceInfo?
5586     NameInfo.setNamedTypeInfo(nullptr);
5587     return NameInfo;
5588   }
5589 
5590   case UnqualifiedIdKind::IK_DestructorName: {
5591     TypeSourceInfo *TInfo;
5592     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5593     if (Ty.isNull())
5594       return DeclarationNameInfo();
5595     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5596                                               Context.getCanonicalType(Ty)));
5597     NameInfo.setNamedTypeInfo(TInfo);
5598     return NameInfo;
5599   }
5600 
5601   case UnqualifiedIdKind::IK_TemplateId: {
5602     TemplateName TName = Name.TemplateId->Template.get();
5603     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5604     return Context.getNameForTemplate(TName, TNameLoc);
5605   }
5606 
5607   } // switch (Name.getKind())
5608 
5609   llvm_unreachable("Unknown name kind");
5610 }
5611 
5612 static QualType getCoreType(QualType Ty) {
5613   do {
5614     if (Ty->isPointerType() || Ty->isReferenceType())
5615       Ty = Ty->getPointeeType();
5616     else if (Ty->isArrayType())
5617       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5618     else
5619       return Ty.withoutLocalFastQualifiers();
5620   } while (true);
5621 }
5622 
5623 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5624 /// and Definition have "nearly" matching parameters. This heuristic is
5625 /// used to improve diagnostics in the case where an out-of-line function
5626 /// definition doesn't match any declaration within the class or namespace.
5627 /// Also sets Params to the list of indices to the parameters that differ
5628 /// between the declaration and the definition. If hasSimilarParameters
5629 /// returns true and Params is empty, then all of the parameters match.
5630 static bool hasSimilarParameters(ASTContext &Context,
5631                                      FunctionDecl *Declaration,
5632                                      FunctionDecl *Definition,
5633                                      SmallVectorImpl<unsigned> &Params) {
5634   Params.clear();
5635   if (Declaration->param_size() != Definition->param_size())
5636     return false;
5637   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5638     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5639     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5640 
5641     // The parameter types are identical
5642     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5643       continue;
5644 
5645     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5646     QualType DefParamBaseTy = getCoreType(DefParamTy);
5647     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5648     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5649 
5650     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5651         (DeclTyName && DeclTyName == DefTyName))
5652       Params.push_back(Idx);
5653     else  // The two parameters aren't even close
5654       return false;
5655   }
5656 
5657   return true;
5658 }
5659 
5660 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5661 /// declarator needs to be rebuilt in the current instantiation.
5662 /// Any bits of declarator which appear before the name are valid for
5663 /// consideration here.  That's specifically the type in the decl spec
5664 /// and the base type in any member-pointer chunks.
5665 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5666                                                     DeclarationName Name) {
5667   // The types we specifically need to rebuild are:
5668   //   - typenames, typeofs, and decltypes
5669   //   - types which will become injected class names
5670   // Of course, we also need to rebuild any type referencing such a
5671   // type.  It's safest to just say "dependent", but we call out a
5672   // few cases here.
5673 
5674   DeclSpec &DS = D.getMutableDeclSpec();
5675   switch (DS.getTypeSpecType()) {
5676   case DeclSpec::TST_typename:
5677   case DeclSpec::TST_typeofType:
5678   case DeclSpec::TST_underlyingType:
5679   case DeclSpec::TST_atomic: {
5680     // Grab the type from the parser.
5681     TypeSourceInfo *TSI = nullptr;
5682     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5683     if (T.isNull() || !T->isInstantiationDependentType()) break;
5684 
5685     // Make sure there's a type source info.  This isn't really much
5686     // of a waste; most dependent types should have type source info
5687     // attached already.
5688     if (!TSI)
5689       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5690 
5691     // Rebuild the type in the current instantiation.
5692     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5693     if (!TSI) return true;
5694 
5695     // Store the new type back in the decl spec.
5696     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5697     DS.UpdateTypeRep(LocType);
5698     break;
5699   }
5700 
5701   case DeclSpec::TST_decltype:
5702   case DeclSpec::TST_typeofExpr: {
5703     Expr *E = DS.getRepAsExpr();
5704     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5705     if (Result.isInvalid()) return true;
5706     DS.UpdateExprRep(Result.get());
5707     break;
5708   }
5709 
5710   default:
5711     // Nothing to do for these decl specs.
5712     break;
5713   }
5714 
5715   // It doesn't matter what order we do this in.
5716   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5717     DeclaratorChunk &Chunk = D.getTypeObject(I);
5718 
5719     // The only type information in the declarator which can come
5720     // before the declaration name is the base type of a member
5721     // pointer.
5722     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5723       continue;
5724 
5725     // Rebuild the scope specifier in-place.
5726     CXXScopeSpec &SS = Chunk.Mem.Scope();
5727     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5728       return true;
5729   }
5730 
5731   return false;
5732 }
5733 
5734 /// Returns true if the declaration is declared in a system header or from a
5735 /// system macro.
5736 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5737   return SM.isInSystemHeader(D->getLocation()) ||
5738          SM.isInSystemMacro(D->getLocation());
5739 }
5740 
5741 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5742   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5743   // of system decl.
5744   if (D->getPreviousDecl() || D->isImplicit())
5745     return;
5746   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5747   if (Status != ReservedIdentifierStatus::NotReserved &&
5748       !isFromSystemHeader(Context.getSourceManager(), D)) {
5749     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5750         << D << static_cast<int>(Status);
5751   }
5752 }
5753 
5754 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5755   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5756   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5757 
5758   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5759       Dcl && Dcl->getDeclContext()->isFileContext())
5760     Dcl->setTopLevelDeclInObjCContainer();
5761 
5762   return Dcl;
5763 }
5764 
5765 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5766 ///   If T is the name of a class, then each of the following shall have a
5767 ///   name different from T:
5768 ///     - every static data member of class T;
5769 ///     - every member function of class T
5770 ///     - every member of class T that is itself a type;
5771 /// \returns true if the declaration name violates these rules.
5772 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5773                                    DeclarationNameInfo NameInfo) {
5774   DeclarationName Name = NameInfo.getName();
5775 
5776   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5777   while (Record && Record->isAnonymousStructOrUnion())
5778     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5779   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5780     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5781     return true;
5782   }
5783 
5784   return false;
5785 }
5786 
5787 /// Diagnose a declaration whose declarator-id has the given
5788 /// nested-name-specifier.
5789 ///
5790 /// \param SS The nested-name-specifier of the declarator-id.
5791 ///
5792 /// \param DC The declaration context to which the nested-name-specifier
5793 /// resolves.
5794 ///
5795 /// \param Name The name of the entity being declared.
5796 ///
5797 /// \param Loc The location of the name of the entity being declared.
5798 ///
5799 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5800 /// we're declaring an explicit / partial specialization / instantiation.
5801 ///
5802 /// \returns true if we cannot safely recover from this error, false otherwise.
5803 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5804                                         DeclarationName Name,
5805                                         SourceLocation Loc, bool IsTemplateId) {
5806   DeclContext *Cur = CurContext;
5807   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5808     Cur = Cur->getParent();
5809 
5810   // If the user provided a superfluous scope specifier that refers back to the
5811   // class in which the entity is already declared, diagnose and ignore it.
5812   //
5813   // class X {
5814   //   void X::f();
5815   // };
5816   //
5817   // Note, it was once ill-formed to give redundant qualification in all
5818   // contexts, but that rule was removed by DR482.
5819   if (Cur->Equals(DC)) {
5820     if (Cur->isRecord()) {
5821       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5822                                       : diag::err_member_extra_qualification)
5823         << Name << FixItHint::CreateRemoval(SS.getRange());
5824       SS.clear();
5825     } else {
5826       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5827     }
5828     return false;
5829   }
5830 
5831   // Check whether the qualifying scope encloses the scope of the original
5832   // declaration. For a template-id, we perform the checks in
5833   // CheckTemplateSpecializationScope.
5834   if (!Cur->Encloses(DC) && !IsTemplateId) {
5835     if (Cur->isRecord())
5836       Diag(Loc, diag::err_member_qualification)
5837         << Name << SS.getRange();
5838     else if (isa<TranslationUnitDecl>(DC))
5839       Diag(Loc, diag::err_invalid_declarator_global_scope)
5840         << Name << SS.getRange();
5841     else if (isa<FunctionDecl>(Cur))
5842       Diag(Loc, diag::err_invalid_declarator_in_function)
5843         << Name << SS.getRange();
5844     else if (isa<BlockDecl>(Cur))
5845       Diag(Loc, diag::err_invalid_declarator_in_block)
5846         << Name << SS.getRange();
5847     else if (isa<ExportDecl>(Cur)) {
5848       if (!isa<NamespaceDecl>(DC))
5849         Diag(Loc, diag::err_export_non_namespace_scope_name)
5850             << Name << SS.getRange();
5851       else
5852         // The cases that DC is not NamespaceDecl should be handled in
5853         // CheckRedeclarationExported.
5854         return false;
5855     } else
5856       Diag(Loc, diag::err_invalid_declarator_scope)
5857       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5858 
5859     return true;
5860   }
5861 
5862   if (Cur->isRecord()) {
5863     // Cannot qualify members within a class.
5864     Diag(Loc, diag::err_member_qualification)
5865       << Name << SS.getRange();
5866     SS.clear();
5867 
5868     // C++ constructors and destructors with incorrect scopes can break
5869     // our AST invariants by having the wrong underlying types. If
5870     // that's the case, then drop this declaration entirely.
5871     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5872          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5873         !Context.hasSameType(Name.getCXXNameType(),
5874                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5875       return true;
5876 
5877     return false;
5878   }
5879 
5880   // C++11 [dcl.meaning]p1:
5881   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5882   //   not begin with a decltype-specifer"
5883   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5884   while (SpecLoc.getPrefix())
5885     SpecLoc = SpecLoc.getPrefix();
5886   if (isa_and_nonnull<DecltypeType>(
5887           SpecLoc.getNestedNameSpecifier()->getAsType()))
5888     Diag(Loc, diag::err_decltype_in_declarator)
5889       << SpecLoc.getTypeLoc().getSourceRange();
5890 
5891   return false;
5892 }
5893 
5894 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5895                                   MultiTemplateParamsArg TemplateParamLists) {
5896   // TODO: consider using NameInfo for diagnostic.
5897   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5898   DeclarationName Name = NameInfo.getName();
5899 
5900   // All of these full declarators require an identifier.  If it doesn't have
5901   // one, the ParsedFreeStandingDeclSpec action should be used.
5902   if (D.isDecompositionDeclarator()) {
5903     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5904   } else if (!Name) {
5905     if (!D.isInvalidType())  // Reject this if we think it is valid.
5906       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5907           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5908     return nullptr;
5909   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5910     return nullptr;
5911 
5912   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5913   // we find one that is.
5914   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5915          (S->getFlags() & Scope::TemplateParamScope) != 0)
5916     S = S->getParent();
5917 
5918   DeclContext *DC = CurContext;
5919   if (D.getCXXScopeSpec().isInvalid())
5920     D.setInvalidType();
5921   else if (D.getCXXScopeSpec().isSet()) {
5922     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5923                                         UPPC_DeclarationQualifier))
5924       return nullptr;
5925 
5926     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5927     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5928     if (!DC || isa<EnumDecl>(DC)) {
5929       // If we could not compute the declaration context, it's because the
5930       // declaration context is dependent but does not refer to a class,
5931       // class template, or class template partial specialization. Complain
5932       // and return early, to avoid the coming semantic disaster.
5933       Diag(D.getIdentifierLoc(),
5934            diag::err_template_qualified_declarator_no_match)
5935         << D.getCXXScopeSpec().getScopeRep()
5936         << D.getCXXScopeSpec().getRange();
5937       return nullptr;
5938     }
5939     bool IsDependentContext = DC->isDependentContext();
5940 
5941     if (!IsDependentContext &&
5942         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5943       return nullptr;
5944 
5945     // If a class is incomplete, do not parse entities inside it.
5946     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5947       Diag(D.getIdentifierLoc(),
5948            diag::err_member_def_undefined_record)
5949         << Name << DC << D.getCXXScopeSpec().getRange();
5950       return nullptr;
5951     }
5952     if (!D.getDeclSpec().isFriendSpecified()) {
5953       if (diagnoseQualifiedDeclaration(
5954               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5955               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5956         if (DC->isRecord())
5957           return nullptr;
5958 
5959         D.setInvalidType();
5960       }
5961     }
5962 
5963     // Check whether we need to rebuild the type of the given
5964     // declaration in the current instantiation.
5965     if (EnteringContext && IsDependentContext &&
5966         TemplateParamLists.size() != 0) {
5967       ContextRAII SavedContext(*this, DC);
5968       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5969         D.setInvalidType();
5970     }
5971   }
5972 
5973   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5974   QualType R = TInfo->getType();
5975 
5976   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5977                                       UPPC_DeclarationType))
5978     D.setInvalidType();
5979 
5980   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5981                         forRedeclarationInCurContext());
5982 
5983   // See if this is a redefinition of a variable in the same scope.
5984   if (!D.getCXXScopeSpec().isSet()) {
5985     bool IsLinkageLookup = false;
5986     bool CreateBuiltins = false;
5987 
5988     // If the declaration we're planning to build will be a function
5989     // or object with linkage, then look for another declaration with
5990     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5991     //
5992     // If the declaration we're planning to build will be declared with
5993     // external linkage in the translation unit, create any builtin with
5994     // the same name.
5995     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5996       /* Do nothing*/;
5997     else if (CurContext->isFunctionOrMethod() &&
5998              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5999               R->isFunctionType())) {
6000       IsLinkageLookup = true;
6001       CreateBuiltins =
6002           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6003     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6004                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6005       CreateBuiltins = true;
6006 
6007     if (IsLinkageLookup) {
6008       Previous.clear(LookupRedeclarationWithLinkage);
6009       Previous.setRedeclarationKind(ForExternalRedeclaration);
6010     }
6011 
6012     LookupName(Previous, S, CreateBuiltins);
6013   } else { // Something like "int foo::x;"
6014     LookupQualifiedName(Previous, DC);
6015 
6016     // C++ [dcl.meaning]p1:
6017     //   When the declarator-id is qualified, the declaration shall refer to a
6018     //  previously declared member of the class or namespace to which the
6019     //  qualifier refers (or, in the case of a namespace, of an element of the
6020     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6021     //  thereof; [...]
6022     //
6023     // Note that we already checked the context above, and that we do not have
6024     // enough information to make sure that Previous contains the declaration
6025     // we want to match. For example, given:
6026     //
6027     //   class X {
6028     //     void f();
6029     //     void f(float);
6030     //   };
6031     //
6032     //   void X::f(int) { } // ill-formed
6033     //
6034     // In this case, Previous will point to the overload set
6035     // containing the two f's declared in X, but neither of them
6036     // matches.
6037 
6038     // C++ [dcl.meaning]p1:
6039     //   [...] the member shall not merely have been introduced by a
6040     //   using-declaration in the scope of the class or namespace nominated by
6041     //   the nested-name-specifier of the declarator-id.
6042     RemoveUsingDecls(Previous);
6043   }
6044 
6045   if (Previous.isSingleResult() &&
6046       Previous.getFoundDecl()->isTemplateParameter()) {
6047     // Maybe we will complain about the shadowed template parameter.
6048     if (!D.isInvalidType())
6049       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6050                                       Previous.getFoundDecl());
6051 
6052     // Just pretend that we didn't see the previous declaration.
6053     Previous.clear();
6054   }
6055 
6056   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6057     // Forget that the previous declaration is the injected-class-name.
6058     Previous.clear();
6059 
6060   // In C++, the previous declaration we find might be a tag type
6061   // (class or enum). In this case, the new declaration will hide the
6062   // tag type. Note that this applies to functions, function templates, and
6063   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6064   if (Previous.isSingleTagDecl() &&
6065       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6066       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6067     Previous.clear();
6068 
6069   // Check that there are no default arguments other than in the parameters
6070   // of a function declaration (C++ only).
6071   if (getLangOpts().CPlusPlus)
6072     CheckExtraCXXDefaultArguments(D);
6073 
6074   NamedDecl *New;
6075 
6076   bool AddToScope = true;
6077   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6078     if (TemplateParamLists.size()) {
6079       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6080       return nullptr;
6081     }
6082 
6083     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6084   } else if (R->isFunctionType()) {
6085     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6086                                   TemplateParamLists,
6087                                   AddToScope);
6088   } else {
6089     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6090                                   AddToScope);
6091   }
6092 
6093   if (!New)
6094     return nullptr;
6095 
6096   // If this has an identifier and is not a function template specialization,
6097   // add it to the scope stack.
6098   if (New->getDeclName() && AddToScope)
6099     PushOnScopeChains(New, S);
6100 
6101   if (isInOpenMPDeclareTargetContext())
6102     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6103 
6104   return New;
6105 }
6106 
6107 /// Helper method to turn variable array types into constant array
6108 /// types in certain situations which would otherwise be errors (for
6109 /// GCC compatibility).
6110 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6111                                                     ASTContext &Context,
6112                                                     bool &SizeIsNegative,
6113                                                     llvm::APSInt &Oversized) {
6114   // This method tries to turn a variable array into a constant
6115   // array even when the size isn't an ICE.  This is necessary
6116   // for compatibility with code that depends on gcc's buggy
6117   // constant expression folding, like struct {char x[(int)(char*)2];}
6118   SizeIsNegative = false;
6119   Oversized = 0;
6120 
6121   if (T->isDependentType())
6122     return QualType();
6123 
6124   QualifierCollector Qs;
6125   const Type *Ty = Qs.strip(T);
6126 
6127   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6128     QualType Pointee = PTy->getPointeeType();
6129     QualType FixedType =
6130         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6131                                             Oversized);
6132     if (FixedType.isNull()) return FixedType;
6133     FixedType = Context.getPointerType(FixedType);
6134     return Qs.apply(Context, FixedType);
6135   }
6136   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6137     QualType Inner = PTy->getInnerType();
6138     QualType FixedType =
6139         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6140                                             Oversized);
6141     if (FixedType.isNull()) return FixedType;
6142     FixedType = Context.getParenType(FixedType);
6143     return Qs.apply(Context, FixedType);
6144   }
6145 
6146   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6147   if (!VLATy)
6148     return QualType();
6149 
6150   QualType ElemTy = VLATy->getElementType();
6151   if (ElemTy->isVariablyModifiedType()) {
6152     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6153                                                  SizeIsNegative, Oversized);
6154     if (ElemTy.isNull())
6155       return QualType();
6156   }
6157 
6158   Expr::EvalResult Result;
6159   if (!VLATy->getSizeExpr() ||
6160       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6161     return QualType();
6162 
6163   llvm::APSInt Res = Result.Val.getInt();
6164 
6165   // Check whether the array size is negative.
6166   if (Res.isSigned() && Res.isNegative()) {
6167     SizeIsNegative = true;
6168     return QualType();
6169   }
6170 
6171   // Check whether the array is too large to be addressed.
6172   unsigned ActiveSizeBits =
6173       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6174        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6175           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6176           : Res.getActiveBits();
6177   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6178     Oversized = Res;
6179     return QualType();
6180   }
6181 
6182   QualType FoldedArrayType = Context.getConstantArrayType(
6183       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6184   return Qs.apply(Context, FoldedArrayType);
6185 }
6186 
6187 static void
6188 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6189   SrcTL = SrcTL.getUnqualifiedLoc();
6190   DstTL = DstTL.getUnqualifiedLoc();
6191   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6192     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6193     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6194                                       DstPTL.getPointeeLoc());
6195     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6196     return;
6197   }
6198   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6199     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6200     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6201                                       DstPTL.getInnerLoc());
6202     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6203     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6204     return;
6205   }
6206   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6207   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6208   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6209   TypeLoc DstElemTL = DstATL.getElementLoc();
6210   if (VariableArrayTypeLoc SrcElemATL =
6211           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6212     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6213     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6214   } else {
6215     DstElemTL.initializeFullCopy(SrcElemTL);
6216   }
6217   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6218   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6219   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6220 }
6221 
6222 /// Helper method to turn variable array types into constant array
6223 /// types in certain situations which would otherwise be errors (for
6224 /// GCC compatibility).
6225 static TypeSourceInfo*
6226 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6227                                               ASTContext &Context,
6228                                               bool &SizeIsNegative,
6229                                               llvm::APSInt &Oversized) {
6230   QualType FixedTy
6231     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6232                                           SizeIsNegative, Oversized);
6233   if (FixedTy.isNull())
6234     return nullptr;
6235   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6236   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6237                                     FixedTInfo->getTypeLoc());
6238   return FixedTInfo;
6239 }
6240 
6241 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6242 /// true if we were successful.
6243 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6244                                            QualType &T, SourceLocation Loc,
6245                                            unsigned FailedFoldDiagID) {
6246   bool SizeIsNegative;
6247   llvm::APSInt Oversized;
6248   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6249       TInfo, Context, SizeIsNegative, Oversized);
6250   if (FixedTInfo) {
6251     Diag(Loc, diag::ext_vla_folded_to_constant);
6252     TInfo = FixedTInfo;
6253     T = FixedTInfo->getType();
6254     return true;
6255   }
6256 
6257   if (SizeIsNegative)
6258     Diag(Loc, diag::err_typecheck_negative_array_size);
6259   else if (Oversized.getBoolValue())
6260     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6261   else if (FailedFoldDiagID)
6262     Diag(Loc, FailedFoldDiagID);
6263   return false;
6264 }
6265 
6266 /// Register the given locally-scoped extern "C" declaration so
6267 /// that it can be found later for redeclarations. We include any extern "C"
6268 /// declaration that is not visible in the translation unit here, not just
6269 /// function-scope declarations.
6270 void
6271 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6272   if (!getLangOpts().CPlusPlus &&
6273       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6274     // Don't need to track declarations in the TU in C.
6275     return;
6276 
6277   // Note that we have a locally-scoped external with this name.
6278   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6279 }
6280 
6281 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6282   // FIXME: We can have multiple results via __attribute__((overloadable)).
6283   auto Result = Context.getExternCContextDecl()->lookup(Name);
6284   return Result.empty() ? nullptr : *Result.begin();
6285 }
6286 
6287 /// Diagnose function specifiers on a declaration of an identifier that
6288 /// does not identify a function.
6289 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6290   // FIXME: We should probably indicate the identifier in question to avoid
6291   // confusion for constructs like "virtual int a(), b;"
6292   if (DS.isVirtualSpecified())
6293     Diag(DS.getVirtualSpecLoc(),
6294          diag::err_virtual_non_function);
6295 
6296   if (DS.hasExplicitSpecifier())
6297     Diag(DS.getExplicitSpecLoc(),
6298          diag::err_explicit_non_function);
6299 
6300   if (DS.isNoreturnSpecified())
6301     Diag(DS.getNoreturnSpecLoc(),
6302          diag::err_noreturn_non_function);
6303 }
6304 
6305 NamedDecl*
6306 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6307                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6308   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6309   if (D.getCXXScopeSpec().isSet()) {
6310     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6311       << D.getCXXScopeSpec().getRange();
6312     D.setInvalidType();
6313     // Pretend we didn't see the scope specifier.
6314     DC = CurContext;
6315     Previous.clear();
6316   }
6317 
6318   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6319 
6320   if (D.getDeclSpec().isInlineSpecified())
6321     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6322         << getLangOpts().CPlusPlus17;
6323   if (D.getDeclSpec().hasConstexprSpecifier())
6324     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6325         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6326 
6327   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6328     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6329       Diag(D.getName().StartLocation,
6330            diag::err_deduction_guide_invalid_specifier)
6331           << "typedef";
6332     else
6333       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6334           << D.getName().getSourceRange();
6335     return nullptr;
6336   }
6337 
6338   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6339   if (!NewTD) return nullptr;
6340 
6341   // Handle attributes prior to checking for duplicates in MergeVarDecl
6342   ProcessDeclAttributes(S, NewTD, D);
6343 
6344   CheckTypedefForVariablyModifiedType(S, NewTD);
6345 
6346   bool Redeclaration = D.isRedeclaration();
6347   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6348   D.setRedeclaration(Redeclaration);
6349   return ND;
6350 }
6351 
6352 void
6353 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6354   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6355   // then it shall have block scope.
6356   // Note that variably modified types must be fixed before merging the decl so
6357   // that redeclarations will match.
6358   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6359   QualType T = TInfo->getType();
6360   if (T->isVariablyModifiedType()) {
6361     setFunctionHasBranchProtectedScope();
6362 
6363     if (S->getFnParent() == nullptr) {
6364       bool SizeIsNegative;
6365       llvm::APSInt Oversized;
6366       TypeSourceInfo *FixedTInfo =
6367         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6368                                                       SizeIsNegative,
6369                                                       Oversized);
6370       if (FixedTInfo) {
6371         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6372         NewTD->setTypeSourceInfo(FixedTInfo);
6373       } else {
6374         if (SizeIsNegative)
6375           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6376         else if (T->isVariableArrayType())
6377           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6378         else if (Oversized.getBoolValue())
6379           Diag(NewTD->getLocation(), diag::err_array_too_large)
6380             << toString(Oversized, 10);
6381         else
6382           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6383         NewTD->setInvalidDecl();
6384       }
6385     }
6386   }
6387 }
6388 
6389 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6390 /// declares a typedef-name, either using the 'typedef' type specifier or via
6391 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6392 NamedDecl*
6393 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6394                            LookupResult &Previous, bool &Redeclaration) {
6395 
6396   // Find the shadowed declaration before filtering for scope.
6397   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6398 
6399   // Merge the decl with the existing one if appropriate. If the decl is
6400   // in an outer scope, it isn't the same thing.
6401   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6402                        /*AllowInlineNamespace*/false);
6403   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6404   if (!Previous.empty()) {
6405     Redeclaration = true;
6406     MergeTypedefNameDecl(S, NewTD, Previous);
6407   } else {
6408     inferGslPointerAttribute(NewTD);
6409   }
6410 
6411   if (ShadowedDecl && !Redeclaration)
6412     CheckShadow(NewTD, ShadowedDecl, Previous);
6413 
6414   // If this is the C FILE type, notify the AST context.
6415   if (IdentifierInfo *II = NewTD->getIdentifier())
6416     if (!NewTD->isInvalidDecl() &&
6417         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6418       if (II->isStr("FILE"))
6419         Context.setFILEDecl(NewTD);
6420       else if (II->isStr("jmp_buf"))
6421         Context.setjmp_bufDecl(NewTD);
6422       else if (II->isStr("sigjmp_buf"))
6423         Context.setsigjmp_bufDecl(NewTD);
6424       else if (II->isStr("ucontext_t"))
6425         Context.setucontext_tDecl(NewTD);
6426     }
6427 
6428   return NewTD;
6429 }
6430 
6431 /// Determines whether the given declaration is an out-of-scope
6432 /// previous declaration.
6433 ///
6434 /// This routine should be invoked when name lookup has found a
6435 /// previous declaration (PrevDecl) that is not in the scope where a
6436 /// new declaration by the same name is being introduced. If the new
6437 /// declaration occurs in a local scope, previous declarations with
6438 /// linkage may still be considered previous declarations (C99
6439 /// 6.2.2p4-5, C++ [basic.link]p6).
6440 ///
6441 /// \param PrevDecl the previous declaration found by name
6442 /// lookup
6443 ///
6444 /// \param DC the context in which the new declaration is being
6445 /// declared.
6446 ///
6447 /// \returns true if PrevDecl is an out-of-scope previous declaration
6448 /// for a new delcaration with the same name.
6449 static bool
6450 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6451                                 ASTContext &Context) {
6452   if (!PrevDecl)
6453     return false;
6454 
6455   if (!PrevDecl->hasLinkage())
6456     return false;
6457 
6458   if (Context.getLangOpts().CPlusPlus) {
6459     // C++ [basic.link]p6:
6460     //   If there is a visible declaration of an entity with linkage
6461     //   having the same name and type, ignoring entities declared
6462     //   outside the innermost enclosing namespace scope, the block
6463     //   scope declaration declares that same entity and receives the
6464     //   linkage of the previous declaration.
6465     DeclContext *OuterContext = DC->getRedeclContext();
6466     if (!OuterContext->isFunctionOrMethod())
6467       // This rule only applies to block-scope declarations.
6468       return false;
6469 
6470     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6471     if (PrevOuterContext->isRecord())
6472       // We found a member function: ignore it.
6473       return false;
6474 
6475     // Find the innermost enclosing namespace for the new and
6476     // previous declarations.
6477     OuterContext = OuterContext->getEnclosingNamespaceContext();
6478     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6479 
6480     // The previous declaration is in a different namespace, so it
6481     // isn't the same function.
6482     if (!OuterContext->Equals(PrevOuterContext))
6483       return false;
6484   }
6485 
6486   return true;
6487 }
6488 
6489 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6490   CXXScopeSpec &SS = D.getCXXScopeSpec();
6491   if (!SS.isSet()) return;
6492   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6493 }
6494 
6495 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6496   QualType type = decl->getType();
6497   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6498   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6499     // Various kinds of declaration aren't allowed to be __autoreleasing.
6500     unsigned kind = -1U;
6501     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6502       if (var->hasAttr<BlocksAttr>())
6503         kind = 0; // __block
6504       else if (!var->hasLocalStorage())
6505         kind = 1; // global
6506     } else if (isa<ObjCIvarDecl>(decl)) {
6507       kind = 3; // ivar
6508     } else if (isa<FieldDecl>(decl)) {
6509       kind = 2; // field
6510     }
6511 
6512     if (kind != -1U) {
6513       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6514         << kind;
6515     }
6516   } else if (lifetime == Qualifiers::OCL_None) {
6517     // Try to infer lifetime.
6518     if (!type->isObjCLifetimeType())
6519       return false;
6520 
6521     lifetime = type->getObjCARCImplicitLifetime();
6522     type = Context.getLifetimeQualifiedType(type, lifetime);
6523     decl->setType(type);
6524   }
6525 
6526   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6527     // Thread-local variables cannot have lifetime.
6528     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6529         var->getTLSKind()) {
6530       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6531         << var->getType();
6532       return true;
6533     }
6534   }
6535 
6536   return false;
6537 }
6538 
6539 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6540   if (Decl->getType().hasAddressSpace())
6541     return;
6542   if (Decl->getType()->isDependentType())
6543     return;
6544   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6545     QualType Type = Var->getType();
6546     if (Type->isSamplerT() || Type->isVoidType())
6547       return;
6548     LangAS ImplAS = LangAS::opencl_private;
6549     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6550     // __opencl_c_program_scope_global_variables feature, the address space
6551     // for a variable at program scope or a static or extern variable inside
6552     // a function are inferred to be __global.
6553     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6554         Var->hasGlobalStorage())
6555       ImplAS = LangAS::opencl_global;
6556     // If the original type from a decayed type is an array type and that array
6557     // type has no address space yet, deduce it now.
6558     if (auto DT = dyn_cast<DecayedType>(Type)) {
6559       auto OrigTy = DT->getOriginalType();
6560       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6561         // Add the address space to the original array type and then propagate
6562         // that to the element type through `getAsArrayType`.
6563         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6564         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6565         // Re-generate the decayed type.
6566         Type = Context.getDecayedType(OrigTy);
6567       }
6568     }
6569     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6570     // Apply any qualifiers (including address space) from the array type to
6571     // the element type. This implements C99 6.7.3p8: "If the specification of
6572     // an array type includes any type qualifiers, the element type is so
6573     // qualified, not the array type."
6574     if (Type->isArrayType())
6575       Type = QualType(Context.getAsArrayType(Type), 0);
6576     Decl->setType(Type);
6577   }
6578 }
6579 
6580 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6581   // Ensure that an auto decl is deduced otherwise the checks below might cache
6582   // the wrong linkage.
6583   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6584 
6585   // 'weak' only applies to declarations with external linkage.
6586   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6587     if (!ND.isExternallyVisible()) {
6588       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6589       ND.dropAttr<WeakAttr>();
6590     }
6591   }
6592   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6593     if (ND.isExternallyVisible()) {
6594       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6595       ND.dropAttr<WeakRefAttr>();
6596       ND.dropAttr<AliasAttr>();
6597     }
6598   }
6599 
6600   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6601     if (VD->hasInit()) {
6602       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6603         assert(VD->isThisDeclarationADefinition() &&
6604                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6605         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6606         VD->dropAttr<AliasAttr>();
6607       }
6608     }
6609   }
6610 
6611   // 'selectany' only applies to externally visible variable declarations.
6612   // It does not apply to functions.
6613   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6614     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6615       S.Diag(Attr->getLocation(),
6616              diag::err_attribute_selectany_non_extern_data);
6617       ND.dropAttr<SelectAnyAttr>();
6618     }
6619   }
6620 
6621   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6622     auto *VD = dyn_cast<VarDecl>(&ND);
6623     bool IsAnonymousNS = false;
6624     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6625     if (VD) {
6626       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6627       while (NS && !IsAnonymousNS) {
6628         IsAnonymousNS = NS->isAnonymousNamespace();
6629         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6630       }
6631     }
6632     // dll attributes require external linkage. Static locals may have external
6633     // linkage but still cannot be explicitly imported or exported.
6634     // In Microsoft mode, a variable defined in anonymous namespace must have
6635     // external linkage in order to be exported.
6636     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6637     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6638         (!AnonNSInMicrosoftMode &&
6639          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6640       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6641         << &ND << Attr;
6642       ND.setInvalidDecl();
6643     }
6644   }
6645 
6646   // Check the attributes on the function type, if any.
6647   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6648     // Don't declare this variable in the second operand of the for-statement;
6649     // GCC miscompiles that by ending its lifetime before evaluating the
6650     // third operand. See gcc.gnu.org/PR86769.
6651     AttributedTypeLoc ATL;
6652     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6653          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6654          TL = ATL.getModifiedLoc()) {
6655       // The [[lifetimebound]] attribute can be applied to the implicit object
6656       // parameter of a non-static member function (other than a ctor or dtor)
6657       // by applying it to the function type.
6658       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6659         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6660         if (!MD || MD->isStatic()) {
6661           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6662               << !MD << A->getRange();
6663         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6664           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6665               << isa<CXXDestructorDecl>(MD) << A->getRange();
6666         }
6667       }
6668     }
6669   }
6670 }
6671 
6672 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6673                                            NamedDecl *NewDecl,
6674                                            bool IsSpecialization,
6675                                            bool IsDefinition) {
6676   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6677     return;
6678 
6679   bool IsTemplate = false;
6680   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6681     OldDecl = OldTD->getTemplatedDecl();
6682     IsTemplate = true;
6683     if (!IsSpecialization)
6684       IsDefinition = false;
6685   }
6686   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6687     NewDecl = NewTD->getTemplatedDecl();
6688     IsTemplate = true;
6689   }
6690 
6691   if (!OldDecl || !NewDecl)
6692     return;
6693 
6694   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6695   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6696   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6697   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6698 
6699   // dllimport and dllexport are inheritable attributes so we have to exclude
6700   // inherited attribute instances.
6701   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6702                     (NewExportAttr && !NewExportAttr->isInherited());
6703 
6704   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6705   // the only exception being explicit specializations.
6706   // Implicitly generated declarations are also excluded for now because there
6707   // is no other way to switch these to use dllimport or dllexport.
6708   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6709 
6710   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6711     // Allow with a warning for free functions and global variables.
6712     bool JustWarn = false;
6713     if (!OldDecl->isCXXClassMember()) {
6714       auto *VD = dyn_cast<VarDecl>(OldDecl);
6715       if (VD && !VD->getDescribedVarTemplate())
6716         JustWarn = true;
6717       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6718       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6719         JustWarn = true;
6720     }
6721 
6722     // We cannot change a declaration that's been used because IR has already
6723     // been emitted. Dllimported functions will still work though (modulo
6724     // address equality) as they can use the thunk.
6725     if (OldDecl->isUsed())
6726       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6727         JustWarn = false;
6728 
6729     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6730                                : diag::err_attribute_dll_redeclaration;
6731     S.Diag(NewDecl->getLocation(), DiagID)
6732         << NewDecl
6733         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6734     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6735     if (!JustWarn) {
6736       NewDecl->setInvalidDecl();
6737       return;
6738     }
6739   }
6740 
6741   // A redeclaration is not allowed to drop a dllimport attribute, the only
6742   // exceptions being inline function definitions (except for function
6743   // templates), local extern declarations, qualified friend declarations or
6744   // special MSVC extension: in the last case, the declaration is treated as if
6745   // it were marked dllexport.
6746   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6747   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6748   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6749     // Ignore static data because out-of-line definitions are diagnosed
6750     // separately.
6751     IsStaticDataMember = VD->isStaticDataMember();
6752     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6753                    VarDecl::DeclarationOnly;
6754   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6755     IsInline = FD->isInlined();
6756     IsQualifiedFriend = FD->getQualifier() &&
6757                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6758   }
6759 
6760   if (OldImportAttr && !HasNewAttr &&
6761       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6762       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6763     if (IsMicrosoftABI && IsDefinition) {
6764       S.Diag(NewDecl->getLocation(),
6765              diag::warn_redeclaration_without_import_attribute)
6766           << NewDecl;
6767       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6768       NewDecl->dropAttr<DLLImportAttr>();
6769       NewDecl->addAttr(
6770           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6771     } else {
6772       S.Diag(NewDecl->getLocation(),
6773              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6774           << NewDecl << OldImportAttr;
6775       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6776       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6777       OldDecl->dropAttr<DLLImportAttr>();
6778       NewDecl->dropAttr<DLLImportAttr>();
6779     }
6780   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6781     // In MinGW, seeing a function declared inline drops the dllimport
6782     // attribute.
6783     OldDecl->dropAttr<DLLImportAttr>();
6784     NewDecl->dropAttr<DLLImportAttr>();
6785     S.Diag(NewDecl->getLocation(),
6786            diag::warn_dllimport_dropped_from_inline_function)
6787         << NewDecl << OldImportAttr;
6788   }
6789 
6790   // A specialization of a class template member function is processed here
6791   // since it's a redeclaration. If the parent class is dllexport, the
6792   // specialization inherits that attribute. This doesn't happen automatically
6793   // since the parent class isn't instantiated until later.
6794   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6795     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6796         !NewImportAttr && !NewExportAttr) {
6797       if (const DLLExportAttr *ParentExportAttr =
6798               MD->getParent()->getAttr<DLLExportAttr>()) {
6799         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6800         NewAttr->setInherited(true);
6801         NewDecl->addAttr(NewAttr);
6802       }
6803     }
6804   }
6805 }
6806 
6807 /// Given that we are within the definition of the given function,
6808 /// will that definition behave like C99's 'inline', where the
6809 /// definition is discarded except for optimization purposes?
6810 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6811   // Try to avoid calling GetGVALinkageForFunction.
6812 
6813   // All cases of this require the 'inline' keyword.
6814   if (!FD->isInlined()) return false;
6815 
6816   // This is only possible in C++ with the gnu_inline attribute.
6817   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6818     return false;
6819 
6820   // Okay, go ahead and call the relatively-more-expensive function.
6821   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6822 }
6823 
6824 /// Determine whether a variable is extern "C" prior to attaching
6825 /// an initializer. We can't just call isExternC() here, because that
6826 /// will also compute and cache whether the declaration is externally
6827 /// visible, which might change when we attach the initializer.
6828 ///
6829 /// This can only be used if the declaration is known to not be a
6830 /// redeclaration of an internal linkage declaration.
6831 ///
6832 /// For instance:
6833 ///
6834 ///   auto x = []{};
6835 ///
6836 /// Attaching the initializer here makes this declaration not externally
6837 /// visible, because its type has internal linkage.
6838 ///
6839 /// FIXME: This is a hack.
6840 template<typename T>
6841 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6842   if (S.getLangOpts().CPlusPlus) {
6843     // In C++, the overloadable attribute negates the effects of extern "C".
6844     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6845       return false;
6846 
6847     // So do CUDA's host/device attributes.
6848     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6849                                  D->template hasAttr<CUDAHostAttr>()))
6850       return false;
6851   }
6852   return D->isExternC();
6853 }
6854 
6855 static bool shouldConsiderLinkage(const VarDecl *VD) {
6856   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6857   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6858       isa<OMPDeclareMapperDecl>(DC))
6859     return VD->hasExternalStorage();
6860   if (DC->isFileContext())
6861     return true;
6862   if (DC->isRecord())
6863     return false;
6864   if (isa<RequiresExprBodyDecl>(DC))
6865     return false;
6866   llvm_unreachable("Unexpected context");
6867 }
6868 
6869 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6870   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6871   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6872       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6873     return true;
6874   if (DC->isRecord())
6875     return false;
6876   llvm_unreachable("Unexpected context");
6877 }
6878 
6879 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6880                           ParsedAttr::Kind Kind) {
6881   // Check decl attributes on the DeclSpec.
6882   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6883     return true;
6884 
6885   // Walk the declarator structure, checking decl attributes that were in a type
6886   // position to the decl itself.
6887   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6888     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6889       return true;
6890   }
6891 
6892   // Finally, check attributes on the decl itself.
6893   return PD.getAttributes().hasAttribute(Kind);
6894 }
6895 
6896 /// Adjust the \c DeclContext for a function or variable that might be a
6897 /// function-local external declaration.
6898 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6899   if (!DC->isFunctionOrMethod())
6900     return false;
6901 
6902   // If this is a local extern function or variable declared within a function
6903   // template, don't add it into the enclosing namespace scope until it is
6904   // instantiated; it might have a dependent type right now.
6905   if (DC->isDependentContext())
6906     return true;
6907 
6908   // C++11 [basic.link]p7:
6909   //   When a block scope declaration of an entity with linkage is not found to
6910   //   refer to some other declaration, then that entity is a member of the
6911   //   innermost enclosing namespace.
6912   //
6913   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6914   // semantically-enclosing namespace, not a lexically-enclosing one.
6915   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6916     DC = DC->getParent();
6917   return true;
6918 }
6919 
6920 /// Returns true if given declaration has external C language linkage.
6921 static bool isDeclExternC(const Decl *D) {
6922   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6923     return FD->isExternC();
6924   if (const auto *VD = dyn_cast<VarDecl>(D))
6925     return VD->isExternC();
6926 
6927   llvm_unreachable("Unknown type of decl!");
6928 }
6929 
6930 /// Returns true if there hasn't been any invalid type diagnosed.
6931 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6932   DeclContext *DC = NewVD->getDeclContext();
6933   QualType R = NewVD->getType();
6934 
6935   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6936   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6937   // argument.
6938   if (R->isImageType() || R->isPipeType()) {
6939     Se.Diag(NewVD->getLocation(),
6940             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6941         << R;
6942     NewVD->setInvalidDecl();
6943     return false;
6944   }
6945 
6946   // OpenCL v1.2 s6.9.r:
6947   // The event type cannot be used to declare a program scope variable.
6948   // OpenCL v2.0 s6.9.q:
6949   // The clk_event_t and reserve_id_t types cannot be declared in program
6950   // scope.
6951   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6952     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6953       Se.Diag(NewVD->getLocation(),
6954               diag::err_invalid_type_for_program_scope_var)
6955           << R;
6956       NewVD->setInvalidDecl();
6957       return false;
6958     }
6959   }
6960 
6961   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6962   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6963                                                Se.getLangOpts())) {
6964     QualType NR = R.getCanonicalType();
6965     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6966            NR->isReferenceType()) {
6967       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6968           NR->isFunctionReferenceType()) {
6969         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6970             << NR->isReferenceType();
6971         NewVD->setInvalidDecl();
6972         return false;
6973       }
6974       NR = NR->getPointeeType();
6975     }
6976   }
6977 
6978   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6979                                                Se.getLangOpts())) {
6980     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6981     // half array type (unless the cl_khr_fp16 extension is enabled).
6982     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6983       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6984       NewVD->setInvalidDecl();
6985       return false;
6986     }
6987   }
6988 
6989   // OpenCL v1.2 s6.9.r:
6990   // The event type cannot be used with the __local, __constant and __global
6991   // address space qualifiers.
6992   if (R->isEventT()) {
6993     if (R.getAddressSpace() != LangAS::opencl_private) {
6994       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6995       NewVD->setInvalidDecl();
6996       return false;
6997     }
6998   }
6999 
7000   if (R->isSamplerT()) {
7001     // OpenCL v1.2 s6.9.b p4:
7002     // The sampler type cannot be used with the __local and __global address
7003     // space qualifiers.
7004     if (R.getAddressSpace() == LangAS::opencl_local ||
7005         R.getAddressSpace() == LangAS::opencl_global) {
7006       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7007       NewVD->setInvalidDecl();
7008     }
7009 
7010     // OpenCL v1.2 s6.12.14.1:
7011     // A global sampler must be declared with either the constant address
7012     // space qualifier or with the const qualifier.
7013     if (DC->isTranslationUnit() &&
7014         !(R.getAddressSpace() == LangAS::opencl_constant ||
7015           R.isConstQualified())) {
7016       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7017       NewVD->setInvalidDecl();
7018     }
7019     if (NewVD->isInvalidDecl())
7020       return false;
7021   }
7022 
7023   return true;
7024 }
7025 
7026 template <typename AttrTy>
7027 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7028   const TypedefNameDecl *TND = TT->getDecl();
7029   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7030     AttrTy *Clone = Attribute->clone(S.Context);
7031     Clone->setInherited(true);
7032     D->addAttr(Clone);
7033   }
7034 }
7035 
7036 NamedDecl *Sema::ActOnVariableDeclarator(
7037     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7038     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7039     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7040   QualType R = TInfo->getType();
7041   DeclarationName Name = GetNameForDeclarator(D).getName();
7042 
7043   IdentifierInfo *II = Name.getAsIdentifierInfo();
7044 
7045   if (D.isDecompositionDeclarator()) {
7046     // Take the name of the first declarator as our name for diagnostic
7047     // purposes.
7048     auto &Decomp = D.getDecompositionDeclarator();
7049     if (!Decomp.bindings().empty()) {
7050       II = Decomp.bindings()[0].Name;
7051       Name = II;
7052     }
7053   } else if (!II) {
7054     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7055     return nullptr;
7056   }
7057 
7058 
7059   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7060   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7061 
7062   // dllimport globals without explicit storage class are treated as extern. We
7063   // have to change the storage class this early to get the right DeclContext.
7064   if (SC == SC_None && !DC->isRecord() &&
7065       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7066       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7067     SC = SC_Extern;
7068 
7069   DeclContext *OriginalDC = DC;
7070   bool IsLocalExternDecl = SC == SC_Extern &&
7071                            adjustContextForLocalExternDecl(DC);
7072 
7073   if (SCSpec == DeclSpec::SCS_mutable) {
7074     // mutable can only appear on non-static class members, so it's always
7075     // an error here
7076     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7077     D.setInvalidType();
7078     SC = SC_None;
7079   }
7080 
7081   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7082       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7083                               D.getDeclSpec().getStorageClassSpecLoc())) {
7084     // In C++11, the 'register' storage class specifier is deprecated.
7085     // Suppress the warning in system macros, it's used in macros in some
7086     // popular C system headers, such as in glibc's htonl() macro.
7087     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7088          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7089                                    : diag::warn_deprecated_register)
7090       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7091   }
7092 
7093   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7094 
7095   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7096     // C99 6.9p2: The storage-class specifiers auto and register shall not
7097     // appear in the declaration specifiers in an external declaration.
7098     // Global Register+Asm is a GNU extension we support.
7099     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7100       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7101       D.setInvalidType();
7102     }
7103   }
7104 
7105   // If this variable has a VLA type and an initializer, try to
7106   // fold to a constant-sized type. This is otherwise invalid.
7107   if (D.hasInitializer() && R->isVariableArrayType())
7108     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7109                                     /*DiagID=*/0);
7110 
7111   bool IsMemberSpecialization = false;
7112   bool IsVariableTemplateSpecialization = false;
7113   bool IsPartialSpecialization = false;
7114   bool IsVariableTemplate = false;
7115   VarDecl *NewVD = nullptr;
7116   VarTemplateDecl *NewTemplate = nullptr;
7117   TemplateParameterList *TemplateParams = nullptr;
7118   if (!getLangOpts().CPlusPlus) {
7119     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7120                             II, R, TInfo, SC);
7121 
7122     if (R->getContainedDeducedType())
7123       ParsingInitForAutoVars.insert(NewVD);
7124 
7125     if (D.isInvalidType())
7126       NewVD->setInvalidDecl();
7127 
7128     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7129         NewVD->hasLocalStorage())
7130       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7131                             NTCUC_AutoVar, NTCUK_Destruct);
7132   } else {
7133     bool Invalid = false;
7134 
7135     if (DC->isRecord() && !CurContext->isRecord()) {
7136       // This is an out-of-line definition of a static data member.
7137       switch (SC) {
7138       case SC_None:
7139         break;
7140       case SC_Static:
7141         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7142              diag::err_static_out_of_line)
7143           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7144         break;
7145       case SC_Auto:
7146       case SC_Register:
7147       case SC_Extern:
7148         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7149         // to names of variables declared in a block or to function parameters.
7150         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7151         // of class members
7152 
7153         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7154              diag::err_storage_class_for_static_member)
7155           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7156         break;
7157       case SC_PrivateExtern:
7158         llvm_unreachable("C storage class in c++!");
7159       }
7160     }
7161 
7162     if (SC == SC_Static && CurContext->isRecord()) {
7163       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7164         // Walk up the enclosing DeclContexts to check for any that are
7165         // incompatible with static data members.
7166         const DeclContext *FunctionOrMethod = nullptr;
7167         const CXXRecordDecl *AnonStruct = nullptr;
7168         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7169           if (Ctxt->isFunctionOrMethod()) {
7170             FunctionOrMethod = Ctxt;
7171             break;
7172           }
7173           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7174           if (ParentDecl && !ParentDecl->getDeclName()) {
7175             AnonStruct = ParentDecl;
7176             break;
7177           }
7178         }
7179         if (FunctionOrMethod) {
7180           // C++ [class.static.data]p5: A local class shall not have static data
7181           // members.
7182           Diag(D.getIdentifierLoc(),
7183                diag::err_static_data_member_not_allowed_in_local_class)
7184             << Name << RD->getDeclName() << RD->getTagKind();
7185         } else if (AnonStruct) {
7186           // C++ [class.static.data]p4: Unnamed classes and classes contained
7187           // directly or indirectly within unnamed classes shall not contain
7188           // static data members.
7189           Diag(D.getIdentifierLoc(),
7190                diag::err_static_data_member_not_allowed_in_anon_struct)
7191             << Name << AnonStruct->getTagKind();
7192           Invalid = true;
7193         } else if (RD->isUnion()) {
7194           // C++98 [class.union]p1: If a union contains a static data member,
7195           // the program is ill-formed. C++11 drops this restriction.
7196           Diag(D.getIdentifierLoc(),
7197                getLangOpts().CPlusPlus11
7198                  ? diag::warn_cxx98_compat_static_data_member_in_union
7199                  : diag::ext_static_data_member_in_union) << Name;
7200         }
7201       }
7202     }
7203 
7204     // Match up the template parameter lists with the scope specifier, then
7205     // determine whether we have a template or a template specialization.
7206     bool InvalidScope = false;
7207     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7208         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7209         D.getCXXScopeSpec(),
7210         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7211             ? D.getName().TemplateId
7212             : nullptr,
7213         TemplateParamLists,
7214         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7215     Invalid |= InvalidScope;
7216 
7217     if (TemplateParams) {
7218       if (!TemplateParams->size() &&
7219           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7220         // There is an extraneous 'template<>' for this variable. Complain
7221         // about it, but allow the declaration of the variable.
7222         Diag(TemplateParams->getTemplateLoc(),
7223              diag::err_template_variable_noparams)
7224           << II
7225           << SourceRange(TemplateParams->getTemplateLoc(),
7226                          TemplateParams->getRAngleLoc());
7227         TemplateParams = nullptr;
7228       } else {
7229         // Check that we can declare a template here.
7230         if (CheckTemplateDeclScope(S, TemplateParams))
7231           return nullptr;
7232 
7233         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7234           // This is an explicit specialization or a partial specialization.
7235           IsVariableTemplateSpecialization = true;
7236           IsPartialSpecialization = TemplateParams->size() > 0;
7237         } else { // if (TemplateParams->size() > 0)
7238           // This is a template declaration.
7239           IsVariableTemplate = true;
7240 
7241           // Only C++1y supports variable templates (N3651).
7242           Diag(D.getIdentifierLoc(),
7243                getLangOpts().CPlusPlus14
7244                    ? diag::warn_cxx11_compat_variable_template
7245                    : diag::ext_variable_template);
7246         }
7247       }
7248     } else {
7249       // Check that we can declare a member specialization here.
7250       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7251           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7252         return nullptr;
7253       assert((Invalid ||
7254               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7255              "should have a 'template<>' for this decl");
7256     }
7257 
7258     if (IsVariableTemplateSpecialization) {
7259       SourceLocation TemplateKWLoc =
7260           TemplateParamLists.size() > 0
7261               ? TemplateParamLists[0]->getTemplateLoc()
7262               : SourceLocation();
7263       DeclResult Res = ActOnVarTemplateSpecialization(
7264           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7265           IsPartialSpecialization);
7266       if (Res.isInvalid())
7267         return nullptr;
7268       NewVD = cast<VarDecl>(Res.get());
7269       AddToScope = false;
7270     } else if (D.isDecompositionDeclarator()) {
7271       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7272                                         D.getIdentifierLoc(), R, TInfo, SC,
7273                                         Bindings);
7274     } else
7275       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7276                               D.getIdentifierLoc(), II, R, TInfo, SC);
7277 
7278     // If this is supposed to be a variable template, create it as such.
7279     if (IsVariableTemplate) {
7280       NewTemplate =
7281           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7282                                   TemplateParams, NewVD);
7283       NewVD->setDescribedVarTemplate(NewTemplate);
7284     }
7285 
7286     // If this decl has an auto type in need of deduction, make a note of the
7287     // Decl so we can diagnose uses of it in its own initializer.
7288     if (R->getContainedDeducedType())
7289       ParsingInitForAutoVars.insert(NewVD);
7290 
7291     if (D.isInvalidType() || Invalid) {
7292       NewVD->setInvalidDecl();
7293       if (NewTemplate)
7294         NewTemplate->setInvalidDecl();
7295     }
7296 
7297     SetNestedNameSpecifier(*this, NewVD, D);
7298 
7299     // If we have any template parameter lists that don't directly belong to
7300     // the variable (matching the scope specifier), store them.
7301     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7302     if (TemplateParamLists.size() > VDTemplateParamLists)
7303       NewVD->setTemplateParameterListsInfo(
7304           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7305   }
7306 
7307   if (D.getDeclSpec().isInlineSpecified()) {
7308     if (!getLangOpts().CPlusPlus) {
7309       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7310           << 0;
7311     } else if (CurContext->isFunctionOrMethod()) {
7312       // 'inline' is not allowed on block scope variable declaration.
7313       Diag(D.getDeclSpec().getInlineSpecLoc(),
7314            diag::err_inline_declaration_block_scope) << Name
7315         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7316     } else {
7317       Diag(D.getDeclSpec().getInlineSpecLoc(),
7318            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7319                                      : diag::ext_inline_variable);
7320       NewVD->setInlineSpecified();
7321     }
7322   }
7323 
7324   // Set the lexical context. If the declarator has a C++ scope specifier, the
7325   // lexical context will be different from the semantic context.
7326   NewVD->setLexicalDeclContext(CurContext);
7327   if (NewTemplate)
7328     NewTemplate->setLexicalDeclContext(CurContext);
7329 
7330   if (IsLocalExternDecl) {
7331     if (D.isDecompositionDeclarator())
7332       for (auto *B : Bindings)
7333         B->setLocalExternDecl();
7334     else
7335       NewVD->setLocalExternDecl();
7336   }
7337 
7338   bool EmitTLSUnsupportedError = false;
7339   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7340     // C++11 [dcl.stc]p4:
7341     //   When thread_local is applied to a variable of block scope the
7342     //   storage-class-specifier static is implied if it does not appear
7343     //   explicitly.
7344     // Core issue: 'static' is not implied if the variable is declared
7345     //   'extern'.
7346     if (NewVD->hasLocalStorage() &&
7347         (SCSpec != DeclSpec::SCS_unspecified ||
7348          TSCS != DeclSpec::TSCS_thread_local ||
7349          !DC->isFunctionOrMethod()))
7350       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7351            diag::err_thread_non_global)
7352         << DeclSpec::getSpecifierName(TSCS);
7353     else if (!Context.getTargetInfo().isTLSSupported()) {
7354       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7355           getLangOpts().SYCLIsDevice) {
7356         // Postpone error emission until we've collected attributes required to
7357         // figure out whether it's a host or device variable and whether the
7358         // error should be ignored.
7359         EmitTLSUnsupportedError = true;
7360         // We still need to mark the variable as TLS so it shows up in AST with
7361         // proper storage class for other tools to use even if we're not going
7362         // to emit any code for it.
7363         NewVD->setTSCSpec(TSCS);
7364       } else
7365         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7366              diag::err_thread_unsupported);
7367     } else
7368       NewVD->setTSCSpec(TSCS);
7369   }
7370 
7371   switch (D.getDeclSpec().getConstexprSpecifier()) {
7372   case ConstexprSpecKind::Unspecified:
7373     break;
7374 
7375   case ConstexprSpecKind::Consteval:
7376     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7377          diag::err_constexpr_wrong_decl_kind)
7378         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7379     LLVM_FALLTHROUGH;
7380 
7381   case ConstexprSpecKind::Constexpr:
7382     NewVD->setConstexpr(true);
7383     // C++1z [dcl.spec.constexpr]p1:
7384     //   A static data member declared with the constexpr specifier is
7385     //   implicitly an inline variable.
7386     if (NewVD->isStaticDataMember() &&
7387         (getLangOpts().CPlusPlus17 ||
7388          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7389       NewVD->setImplicitlyInline();
7390     break;
7391 
7392   case ConstexprSpecKind::Constinit:
7393     if (!NewVD->hasGlobalStorage())
7394       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7395            diag::err_constinit_local_variable);
7396     else
7397       NewVD->addAttr(ConstInitAttr::Create(
7398           Context, D.getDeclSpec().getConstexprSpecLoc(),
7399           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7400     break;
7401   }
7402 
7403   // C99 6.7.4p3
7404   //   An inline definition of a function with external linkage shall
7405   //   not contain a definition of a modifiable object with static or
7406   //   thread storage duration...
7407   // We only apply this when the function is required to be defined
7408   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7409   // that a local variable with thread storage duration still has to
7410   // be marked 'static'.  Also note that it's possible to get these
7411   // semantics in C++ using __attribute__((gnu_inline)).
7412   if (SC == SC_Static && S->getFnParent() != nullptr &&
7413       !NewVD->getType().isConstQualified()) {
7414     FunctionDecl *CurFD = getCurFunctionDecl();
7415     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7416       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7417            diag::warn_static_local_in_extern_inline);
7418       MaybeSuggestAddingStaticToDecl(CurFD);
7419     }
7420   }
7421 
7422   if (D.getDeclSpec().isModulePrivateSpecified()) {
7423     if (IsVariableTemplateSpecialization)
7424       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7425           << (IsPartialSpecialization ? 1 : 0)
7426           << FixItHint::CreateRemoval(
7427                  D.getDeclSpec().getModulePrivateSpecLoc());
7428     else if (IsMemberSpecialization)
7429       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7430         << 2
7431         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7432     else if (NewVD->hasLocalStorage())
7433       Diag(NewVD->getLocation(), diag::err_module_private_local)
7434           << 0 << NewVD
7435           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7436           << FixItHint::CreateRemoval(
7437                  D.getDeclSpec().getModulePrivateSpecLoc());
7438     else {
7439       NewVD->setModulePrivate();
7440       if (NewTemplate)
7441         NewTemplate->setModulePrivate();
7442       for (auto *B : Bindings)
7443         B->setModulePrivate();
7444     }
7445   }
7446 
7447   if (getLangOpts().OpenCL) {
7448     deduceOpenCLAddressSpace(NewVD);
7449 
7450     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7451     if (TSC != TSCS_unspecified) {
7452       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7453            diag::err_opencl_unknown_type_specifier)
7454           << getLangOpts().getOpenCLVersionString()
7455           << DeclSpec::getSpecifierName(TSC) << 1;
7456       NewVD->setInvalidDecl();
7457     }
7458   }
7459 
7460   // Handle attributes prior to checking for duplicates in MergeVarDecl
7461   ProcessDeclAttributes(S, NewVD, D);
7462 
7463   // FIXME: This is probably the wrong location to be doing this and we should
7464   // probably be doing this for more attributes (especially for function
7465   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7466   // the code to copy attributes would be generated by TableGen.
7467   if (R->isFunctionPointerType())
7468     if (const auto *TT = R->getAs<TypedefType>())
7469       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7470 
7471   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7472       getLangOpts().SYCLIsDevice) {
7473     if (EmitTLSUnsupportedError &&
7474         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7475          (getLangOpts().OpenMPIsDevice &&
7476           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7477       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7478            diag::err_thread_unsupported);
7479 
7480     if (EmitTLSUnsupportedError &&
7481         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7482       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7483     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7484     // storage [duration]."
7485     if (SC == SC_None && S->getFnParent() != nullptr &&
7486         (NewVD->hasAttr<CUDASharedAttr>() ||
7487          NewVD->hasAttr<CUDAConstantAttr>())) {
7488       NewVD->setStorageClass(SC_Static);
7489     }
7490   }
7491 
7492   // Ensure that dllimport globals without explicit storage class are treated as
7493   // extern. The storage class is set above using parsed attributes. Now we can
7494   // check the VarDecl itself.
7495   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7496          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7497          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7498 
7499   // In auto-retain/release, infer strong retension for variables of
7500   // retainable type.
7501   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7502     NewVD->setInvalidDecl();
7503 
7504   // Handle GNU asm-label extension (encoded as an attribute).
7505   if (Expr *E = (Expr*)D.getAsmLabel()) {
7506     // The parser guarantees this is a string.
7507     StringLiteral *SE = cast<StringLiteral>(E);
7508     StringRef Label = SE->getString();
7509     if (S->getFnParent() != nullptr) {
7510       switch (SC) {
7511       case SC_None:
7512       case SC_Auto:
7513         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7514         break;
7515       case SC_Register:
7516         // Local Named register
7517         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7518             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7519           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7520         break;
7521       case SC_Static:
7522       case SC_Extern:
7523       case SC_PrivateExtern:
7524         break;
7525       }
7526     } else if (SC == SC_Register) {
7527       // Global Named register
7528       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7529         const auto &TI = Context.getTargetInfo();
7530         bool HasSizeMismatch;
7531 
7532         if (!TI.isValidGCCRegisterName(Label))
7533           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7534         else if (!TI.validateGlobalRegisterVariable(Label,
7535                                                     Context.getTypeSize(R),
7536                                                     HasSizeMismatch))
7537           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7538         else if (HasSizeMismatch)
7539           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7540       }
7541 
7542       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7543         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7544         NewVD->setInvalidDecl(true);
7545       }
7546     }
7547 
7548     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7549                                         /*IsLiteralLabel=*/true,
7550                                         SE->getStrTokenLoc(0)));
7551   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7552     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7553       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7554     if (I != ExtnameUndeclaredIdentifiers.end()) {
7555       if (isDeclExternC(NewVD)) {
7556         NewVD->addAttr(I->second);
7557         ExtnameUndeclaredIdentifiers.erase(I);
7558       } else
7559         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7560             << /*Variable*/1 << NewVD;
7561     }
7562   }
7563 
7564   // Find the shadowed declaration before filtering for scope.
7565   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7566                                 ? getShadowedDeclaration(NewVD, Previous)
7567                                 : nullptr;
7568 
7569   // Don't consider existing declarations that are in a different
7570   // scope and are out-of-semantic-context declarations (if the new
7571   // declaration has linkage).
7572   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7573                        D.getCXXScopeSpec().isNotEmpty() ||
7574                        IsMemberSpecialization ||
7575                        IsVariableTemplateSpecialization);
7576 
7577   // Check whether the previous declaration is in the same block scope. This
7578   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7579   if (getLangOpts().CPlusPlus &&
7580       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7581     NewVD->setPreviousDeclInSameBlockScope(
7582         Previous.isSingleResult() && !Previous.isShadowed() &&
7583         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7584 
7585   if (!getLangOpts().CPlusPlus) {
7586     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7587   } else {
7588     // If this is an explicit specialization of a static data member, check it.
7589     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7590         CheckMemberSpecialization(NewVD, Previous))
7591       NewVD->setInvalidDecl();
7592 
7593     // Merge the decl with the existing one if appropriate.
7594     if (!Previous.empty()) {
7595       if (Previous.isSingleResult() &&
7596           isa<FieldDecl>(Previous.getFoundDecl()) &&
7597           D.getCXXScopeSpec().isSet()) {
7598         // The user tried to define a non-static data member
7599         // out-of-line (C++ [dcl.meaning]p1).
7600         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7601           << D.getCXXScopeSpec().getRange();
7602         Previous.clear();
7603         NewVD->setInvalidDecl();
7604       }
7605     } else if (D.getCXXScopeSpec().isSet()) {
7606       // No previous declaration in the qualifying scope.
7607       Diag(D.getIdentifierLoc(), diag::err_no_member)
7608         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7609         << D.getCXXScopeSpec().getRange();
7610       NewVD->setInvalidDecl();
7611     }
7612 
7613     if (!IsVariableTemplateSpecialization)
7614       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7615 
7616     if (NewTemplate) {
7617       VarTemplateDecl *PrevVarTemplate =
7618           NewVD->getPreviousDecl()
7619               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7620               : nullptr;
7621 
7622       // Check the template parameter list of this declaration, possibly
7623       // merging in the template parameter list from the previous variable
7624       // template declaration.
7625       if (CheckTemplateParameterList(
7626               TemplateParams,
7627               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7628                               : nullptr,
7629               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7630                DC->isDependentContext())
7631                   ? TPC_ClassTemplateMember
7632                   : TPC_VarTemplate))
7633         NewVD->setInvalidDecl();
7634 
7635       // If we are providing an explicit specialization of a static variable
7636       // template, make a note of that.
7637       if (PrevVarTemplate &&
7638           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7639         PrevVarTemplate->setMemberSpecialization();
7640     }
7641   }
7642 
7643   // Diagnose shadowed variables iff this isn't a redeclaration.
7644   if (ShadowedDecl && !D.isRedeclaration())
7645     CheckShadow(NewVD, ShadowedDecl, Previous);
7646 
7647   ProcessPragmaWeak(S, NewVD);
7648 
7649   // If this is the first declaration of an extern C variable, update
7650   // the map of such variables.
7651   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7652       isIncompleteDeclExternC(*this, NewVD))
7653     RegisterLocallyScopedExternCDecl(NewVD, S);
7654 
7655   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7656     MangleNumberingContext *MCtx;
7657     Decl *ManglingContextDecl;
7658     std::tie(MCtx, ManglingContextDecl) =
7659         getCurrentMangleNumberContext(NewVD->getDeclContext());
7660     if (MCtx) {
7661       Context.setManglingNumber(
7662           NewVD, MCtx->getManglingNumber(
7663                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7664       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7665     }
7666   }
7667 
7668   // Special handling of variable named 'main'.
7669   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7670       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7671       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7672 
7673     // C++ [basic.start.main]p3
7674     // A program that declares a variable main at global scope is ill-formed.
7675     if (getLangOpts().CPlusPlus)
7676       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7677 
7678     // In C, and external-linkage variable named main results in undefined
7679     // behavior.
7680     else if (NewVD->hasExternalFormalLinkage())
7681       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7682   }
7683 
7684   if (D.isRedeclaration() && !Previous.empty()) {
7685     NamedDecl *Prev = Previous.getRepresentativeDecl();
7686     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7687                                    D.isFunctionDefinition());
7688   }
7689 
7690   if (NewTemplate) {
7691     if (NewVD->isInvalidDecl())
7692       NewTemplate->setInvalidDecl();
7693     ActOnDocumentableDecl(NewTemplate);
7694     return NewTemplate;
7695   }
7696 
7697   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7698     CompleteMemberSpecialization(NewVD, Previous);
7699 
7700   return NewVD;
7701 }
7702 
7703 /// Enum describing the %select options in diag::warn_decl_shadow.
7704 enum ShadowedDeclKind {
7705   SDK_Local,
7706   SDK_Global,
7707   SDK_StaticMember,
7708   SDK_Field,
7709   SDK_Typedef,
7710   SDK_Using,
7711   SDK_StructuredBinding
7712 };
7713 
7714 /// Determine what kind of declaration we're shadowing.
7715 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7716                                                 const DeclContext *OldDC) {
7717   if (isa<TypeAliasDecl>(ShadowedDecl))
7718     return SDK_Using;
7719   else if (isa<TypedefDecl>(ShadowedDecl))
7720     return SDK_Typedef;
7721   else if (isa<BindingDecl>(ShadowedDecl))
7722     return SDK_StructuredBinding;
7723   else if (isa<RecordDecl>(OldDC))
7724     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7725 
7726   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7727 }
7728 
7729 /// Return the location of the capture if the given lambda captures the given
7730 /// variable \p VD, or an invalid source location otherwise.
7731 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7732                                          const VarDecl *VD) {
7733   for (const Capture &Capture : LSI->Captures) {
7734     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7735       return Capture.getLocation();
7736   }
7737   return SourceLocation();
7738 }
7739 
7740 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7741                                      const LookupResult &R) {
7742   // Only diagnose if we're shadowing an unambiguous field or variable.
7743   if (R.getResultKind() != LookupResult::Found)
7744     return false;
7745 
7746   // Return false if warning is ignored.
7747   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7748 }
7749 
7750 /// Return the declaration shadowed by the given variable \p D, or null
7751 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7752 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7753                                         const LookupResult &R) {
7754   if (!shouldWarnIfShadowedDecl(Diags, R))
7755     return nullptr;
7756 
7757   // Don't diagnose declarations at file scope.
7758   if (D->hasGlobalStorage())
7759     return nullptr;
7760 
7761   NamedDecl *ShadowedDecl = R.getFoundDecl();
7762   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7763                                                             : nullptr;
7764 }
7765 
7766 /// Return the declaration shadowed by the given typedef \p D, or null
7767 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7768 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7769                                         const LookupResult &R) {
7770   // Don't warn if typedef declaration is part of a class
7771   if (D->getDeclContext()->isRecord())
7772     return nullptr;
7773 
7774   if (!shouldWarnIfShadowedDecl(Diags, R))
7775     return nullptr;
7776 
7777   NamedDecl *ShadowedDecl = R.getFoundDecl();
7778   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7779 }
7780 
7781 /// Return the declaration shadowed by the given variable \p D, or null
7782 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7783 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7784                                         const LookupResult &R) {
7785   if (!shouldWarnIfShadowedDecl(Diags, R))
7786     return nullptr;
7787 
7788   NamedDecl *ShadowedDecl = R.getFoundDecl();
7789   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7790                                                             : nullptr;
7791 }
7792 
7793 /// Diagnose variable or built-in function shadowing.  Implements
7794 /// -Wshadow.
7795 ///
7796 /// This method is called whenever a VarDecl is added to a "useful"
7797 /// scope.
7798 ///
7799 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7800 /// \param R the lookup of the name
7801 ///
7802 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7803                        const LookupResult &R) {
7804   DeclContext *NewDC = D->getDeclContext();
7805 
7806   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7807     // Fields are not shadowed by variables in C++ static methods.
7808     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7809       if (MD->isStatic())
7810         return;
7811 
7812     // Fields shadowed by constructor parameters are a special case. Usually
7813     // the constructor initializes the field with the parameter.
7814     if (isa<CXXConstructorDecl>(NewDC))
7815       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7816         // Remember that this was shadowed so we can either warn about its
7817         // modification or its existence depending on warning settings.
7818         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7819         return;
7820       }
7821   }
7822 
7823   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7824     if (shadowedVar->isExternC()) {
7825       // For shadowing external vars, make sure that we point to the global
7826       // declaration, not a locally scoped extern declaration.
7827       for (auto I : shadowedVar->redecls())
7828         if (I->isFileVarDecl()) {
7829           ShadowedDecl = I;
7830           break;
7831         }
7832     }
7833 
7834   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7835 
7836   unsigned WarningDiag = diag::warn_decl_shadow;
7837   SourceLocation CaptureLoc;
7838   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7839       isa<CXXMethodDecl>(NewDC)) {
7840     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7841       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7842         if (RD->getLambdaCaptureDefault() == LCD_None) {
7843           // Try to avoid warnings for lambdas with an explicit capture list.
7844           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7845           // Warn only when the lambda captures the shadowed decl explicitly.
7846           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7847           if (CaptureLoc.isInvalid())
7848             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7849         } else {
7850           // Remember that this was shadowed so we can avoid the warning if the
7851           // shadowed decl isn't captured and the warning settings allow it.
7852           cast<LambdaScopeInfo>(getCurFunction())
7853               ->ShadowingDecls.push_back(
7854                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7855           return;
7856         }
7857       }
7858 
7859       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7860         // A variable can't shadow a local variable in an enclosing scope, if
7861         // they are separated by a non-capturing declaration context.
7862         for (DeclContext *ParentDC = NewDC;
7863              ParentDC && !ParentDC->Equals(OldDC);
7864              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7865           // Only block literals, captured statements, and lambda expressions
7866           // can capture; other scopes don't.
7867           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7868               !isLambdaCallOperator(ParentDC)) {
7869             return;
7870           }
7871         }
7872       }
7873     }
7874   }
7875 
7876   // Only warn about certain kinds of shadowing for class members.
7877   if (NewDC && NewDC->isRecord()) {
7878     // In particular, don't warn about shadowing non-class members.
7879     if (!OldDC->isRecord())
7880       return;
7881 
7882     // TODO: should we warn about static data members shadowing
7883     // static data members from base classes?
7884 
7885     // TODO: don't diagnose for inaccessible shadowed members.
7886     // This is hard to do perfectly because we might friend the
7887     // shadowing context, but that's just a false negative.
7888   }
7889 
7890 
7891   DeclarationName Name = R.getLookupName();
7892 
7893   // Emit warning and note.
7894   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7895   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7896   if (!CaptureLoc.isInvalid())
7897     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7898         << Name << /*explicitly*/ 1;
7899   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7900 }
7901 
7902 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7903 /// when these variables are captured by the lambda.
7904 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7905   for (const auto &Shadow : LSI->ShadowingDecls) {
7906     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7907     // Try to avoid the warning when the shadowed decl isn't captured.
7908     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7909     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7910     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7911                                        ? diag::warn_decl_shadow_uncaptured_local
7912                                        : diag::warn_decl_shadow)
7913         << Shadow.VD->getDeclName()
7914         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7915     if (!CaptureLoc.isInvalid())
7916       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7917           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7918     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7919   }
7920 }
7921 
7922 /// Check -Wshadow without the advantage of a previous lookup.
7923 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7924   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7925     return;
7926 
7927   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7928                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7929   LookupName(R, S);
7930   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7931     CheckShadow(D, ShadowedDecl, R);
7932 }
7933 
7934 /// Check if 'E', which is an expression that is about to be modified, refers
7935 /// to a constructor parameter that shadows a field.
7936 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7937   // Quickly ignore expressions that can't be shadowing ctor parameters.
7938   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7939     return;
7940   E = E->IgnoreParenImpCasts();
7941   auto *DRE = dyn_cast<DeclRefExpr>(E);
7942   if (!DRE)
7943     return;
7944   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7945   auto I = ShadowingDecls.find(D);
7946   if (I == ShadowingDecls.end())
7947     return;
7948   const NamedDecl *ShadowedDecl = I->second;
7949   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7950   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7951   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7952   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7953 
7954   // Avoid issuing multiple warnings about the same decl.
7955   ShadowingDecls.erase(I);
7956 }
7957 
7958 /// Check for conflict between this global or extern "C" declaration and
7959 /// previous global or extern "C" declarations. This is only used in C++.
7960 template<typename T>
7961 static bool checkGlobalOrExternCConflict(
7962     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7963   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7964   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7965 
7966   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7967     // The common case: this global doesn't conflict with any extern "C"
7968     // declaration.
7969     return false;
7970   }
7971 
7972   if (Prev) {
7973     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7974       // Both the old and new declarations have C language linkage. This is a
7975       // redeclaration.
7976       Previous.clear();
7977       Previous.addDecl(Prev);
7978       return true;
7979     }
7980 
7981     // This is a global, non-extern "C" declaration, and there is a previous
7982     // non-global extern "C" declaration. Diagnose if this is a variable
7983     // declaration.
7984     if (!isa<VarDecl>(ND))
7985       return false;
7986   } else {
7987     // The declaration is extern "C". Check for any declaration in the
7988     // translation unit which might conflict.
7989     if (IsGlobal) {
7990       // We have already performed the lookup into the translation unit.
7991       IsGlobal = false;
7992       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7993            I != E; ++I) {
7994         if (isa<VarDecl>(*I)) {
7995           Prev = *I;
7996           break;
7997         }
7998       }
7999     } else {
8000       DeclContext::lookup_result R =
8001           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8002       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8003            I != E; ++I) {
8004         if (isa<VarDecl>(*I)) {
8005           Prev = *I;
8006           break;
8007         }
8008         // FIXME: If we have any other entity with this name in global scope,
8009         // the declaration is ill-formed, but that is a defect: it breaks the
8010         // 'stat' hack, for instance. Only variables can have mangled name
8011         // clashes with extern "C" declarations, so only they deserve a
8012         // diagnostic.
8013       }
8014     }
8015 
8016     if (!Prev)
8017       return false;
8018   }
8019 
8020   // Use the first declaration's location to ensure we point at something which
8021   // is lexically inside an extern "C" linkage-spec.
8022   assert(Prev && "should have found a previous declaration to diagnose");
8023   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8024     Prev = FD->getFirstDecl();
8025   else
8026     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8027 
8028   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8029     << IsGlobal << ND;
8030   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8031     << IsGlobal;
8032   return false;
8033 }
8034 
8035 /// Apply special rules for handling extern "C" declarations. Returns \c true
8036 /// if we have found that this is a redeclaration of some prior entity.
8037 ///
8038 /// Per C++ [dcl.link]p6:
8039 ///   Two declarations [for a function or variable] with C language linkage
8040 ///   with the same name that appear in different scopes refer to the same
8041 ///   [entity]. An entity with C language linkage shall not be declared with
8042 ///   the same name as an entity in global scope.
8043 template<typename T>
8044 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8045                                                   LookupResult &Previous) {
8046   if (!S.getLangOpts().CPlusPlus) {
8047     // In C, when declaring a global variable, look for a corresponding 'extern'
8048     // variable declared in function scope. We don't need this in C++, because
8049     // we find local extern decls in the surrounding file-scope DeclContext.
8050     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8051       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8052         Previous.clear();
8053         Previous.addDecl(Prev);
8054         return true;
8055       }
8056     }
8057     return false;
8058   }
8059 
8060   // A declaration in the translation unit can conflict with an extern "C"
8061   // declaration.
8062   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8063     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8064 
8065   // An extern "C" declaration can conflict with a declaration in the
8066   // translation unit or can be a redeclaration of an extern "C" declaration
8067   // in another scope.
8068   if (isIncompleteDeclExternC(S,ND))
8069     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8070 
8071   // Neither global nor extern "C": nothing to do.
8072   return false;
8073 }
8074 
8075 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8076   // If the decl is already known invalid, don't check it.
8077   if (NewVD->isInvalidDecl())
8078     return;
8079 
8080   QualType T = NewVD->getType();
8081 
8082   // Defer checking an 'auto' type until its initializer is attached.
8083   if (T->isUndeducedType())
8084     return;
8085 
8086   if (NewVD->hasAttrs())
8087     CheckAlignasUnderalignment(NewVD);
8088 
8089   if (T->isObjCObjectType()) {
8090     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8091       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8092     T = Context.getObjCObjectPointerType(T);
8093     NewVD->setType(T);
8094   }
8095 
8096   // Emit an error if an address space was applied to decl with local storage.
8097   // This includes arrays of objects with address space qualifiers, but not
8098   // automatic variables that point to other address spaces.
8099   // ISO/IEC TR 18037 S5.1.2
8100   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8101       T.getAddressSpace() != LangAS::Default) {
8102     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8103     NewVD->setInvalidDecl();
8104     return;
8105   }
8106 
8107   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8108   // scope.
8109   if (getLangOpts().OpenCLVersion == 120 &&
8110       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8111                                             getLangOpts()) &&
8112       NewVD->isStaticLocal()) {
8113     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8114     NewVD->setInvalidDecl();
8115     return;
8116   }
8117 
8118   if (getLangOpts().OpenCL) {
8119     if (!diagnoseOpenCLTypes(*this, NewVD))
8120       return;
8121 
8122     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8123     if (NewVD->hasAttr<BlocksAttr>()) {
8124       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8125       return;
8126     }
8127 
8128     if (T->isBlockPointerType()) {
8129       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8130       // can't use 'extern' storage class.
8131       if (!T.isConstQualified()) {
8132         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8133             << 0 /*const*/;
8134         NewVD->setInvalidDecl();
8135         return;
8136       }
8137       if (NewVD->hasExternalStorage()) {
8138         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8139         NewVD->setInvalidDecl();
8140         return;
8141       }
8142     }
8143 
8144     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8145     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8146         NewVD->hasExternalStorage()) {
8147       if (!T->isSamplerT() && !T->isDependentType() &&
8148           !(T.getAddressSpace() == LangAS::opencl_constant ||
8149             (T.getAddressSpace() == LangAS::opencl_global &&
8150              getOpenCLOptions().areProgramScopeVariablesSupported(
8151                  getLangOpts())))) {
8152         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8153         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8154           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8155               << Scope << "global or constant";
8156         else
8157           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8158               << Scope << "constant";
8159         NewVD->setInvalidDecl();
8160         return;
8161       }
8162     } else {
8163       if (T.getAddressSpace() == LangAS::opencl_global) {
8164         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8165             << 1 /*is any function*/ << "global";
8166         NewVD->setInvalidDecl();
8167         return;
8168       }
8169       if (T.getAddressSpace() == LangAS::opencl_constant ||
8170           T.getAddressSpace() == LangAS::opencl_local) {
8171         FunctionDecl *FD = getCurFunctionDecl();
8172         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8173         // in functions.
8174         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8175           if (T.getAddressSpace() == LangAS::opencl_constant)
8176             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8177                 << 0 /*non-kernel only*/ << "constant";
8178           else
8179             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8180                 << 0 /*non-kernel only*/ << "local";
8181           NewVD->setInvalidDecl();
8182           return;
8183         }
8184         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8185         // in the outermost scope of a kernel function.
8186         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8187           if (!getCurScope()->isFunctionScope()) {
8188             if (T.getAddressSpace() == LangAS::opencl_constant)
8189               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8190                   << "constant";
8191             else
8192               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8193                   << "local";
8194             NewVD->setInvalidDecl();
8195             return;
8196           }
8197         }
8198       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8199                  // If we are parsing a template we didn't deduce an addr
8200                  // space yet.
8201                  T.getAddressSpace() != LangAS::Default) {
8202         // Do not allow other address spaces on automatic variable.
8203         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8204         NewVD->setInvalidDecl();
8205         return;
8206       }
8207     }
8208   }
8209 
8210   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8211       && !NewVD->hasAttr<BlocksAttr>()) {
8212     if (getLangOpts().getGC() != LangOptions::NonGC)
8213       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8214     else {
8215       assert(!getLangOpts().ObjCAutoRefCount);
8216       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8217     }
8218   }
8219 
8220   bool isVM = T->isVariablyModifiedType();
8221   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8222       NewVD->hasAttr<BlocksAttr>())
8223     setFunctionHasBranchProtectedScope();
8224 
8225   if ((isVM && NewVD->hasLinkage()) ||
8226       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8227     bool SizeIsNegative;
8228     llvm::APSInt Oversized;
8229     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8230         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8231     QualType FixedT;
8232     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8233       FixedT = FixedTInfo->getType();
8234     else if (FixedTInfo) {
8235       // Type and type-as-written are canonically different. We need to fix up
8236       // both types separately.
8237       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8238                                                    Oversized);
8239     }
8240     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8241       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8242       // FIXME: This won't give the correct result for
8243       // int a[10][n];
8244       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8245 
8246       if (NewVD->isFileVarDecl())
8247         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8248         << SizeRange;
8249       else if (NewVD->isStaticLocal())
8250         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8251         << SizeRange;
8252       else
8253         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8254         << SizeRange;
8255       NewVD->setInvalidDecl();
8256       return;
8257     }
8258 
8259     if (!FixedTInfo) {
8260       if (NewVD->isFileVarDecl())
8261         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8262       else
8263         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8264       NewVD->setInvalidDecl();
8265       return;
8266     }
8267 
8268     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8269     NewVD->setType(FixedT);
8270     NewVD->setTypeSourceInfo(FixedTInfo);
8271   }
8272 
8273   if (T->isVoidType()) {
8274     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8275     //                    of objects and functions.
8276     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8277       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8278         << T;
8279       NewVD->setInvalidDecl();
8280       return;
8281     }
8282   }
8283 
8284   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8285     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8286     NewVD->setInvalidDecl();
8287     return;
8288   }
8289 
8290   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8291     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8292     NewVD->setInvalidDecl();
8293     return;
8294   }
8295 
8296   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8297     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8298     NewVD->setInvalidDecl();
8299     return;
8300   }
8301 
8302   if (NewVD->isConstexpr() && !T->isDependentType() &&
8303       RequireLiteralType(NewVD->getLocation(), T,
8304                          diag::err_constexpr_var_non_literal)) {
8305     NewVD->setInvalidDecl();
8306     return;
8307   }
8308 
8309   // PPC MMA non-pointer types are not allowed as non-local variable types.
8310   if (Context.getTargetInfo().getTriple().isPPC64() &&
8311       !NewVD->isLocalVarDecl() &&
8312       CheckPPCMMAType(T, NewVD->getLocation())) {
8313     NewVD->setInvalidDecl();
8314     return;
8315   }
8316 }
8317 
8318 /// Perform semantic checking on a newly-created variable
8319 /// declaration.
8320 ///
8321 /// This routine performs all of the type-checking required for a
8322 /// variable declaration once it has been built. It is used both to
8323 /// check variables after they have been parsed and their declarators
8324 /// have been translated into a declaration, and to check variables
8325 /// that have been instantiated from a template.
8326 ///
8327 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8328 ///
8329 /// Returns true if the variable declaration is a redeclaration.
8330 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8331   CheckVariableDeclarationType(NewVD);
8332 
8333   // If the decl is already known invalid, don't check it.
8334   if (NewVD->isInvalidDecl())
8335     return false;
8336 
8337   // If we did not find anything by this name, look for a non-visible
8338   // extern "C" declaration with the same name.
8339   if (Previous.empty() &&
8340       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8341     Previous.setShadowed();
8342 
8343   if (!Previous.empty()) {
8344     MergeVarDecl(NewVD, Previous);
8345     return true;
8346   }
8347   return false;
8348 }
8349 
8350 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8351 /// and if so, check that it's a valid override and remember it.
8352 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8353   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8354 
8355   // Look for methods in base classes that this method might override.
8356   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8357                      /*DetectVirtual=*/false);
8358   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8359     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8360     DeclarationName Name = MD->getDeclName();
8361 
8362     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8363       // We really want to find the base class destructor here.
8364       QualType T = Context.getTypeDeclType(BaseRecord);
8365       CanQualType CT = Context.getCanonicalType(T);
8366       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8367     }
8368 
8369     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8370       CXXMethodDecl *BaseMD =
8371           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8372       if (!BaseMD || !BaseMD->isVirtual() ||
8373           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8374                      /*ConsiderCudaAttrs=*/true,
8375                      // C++2a [class.virtual]p2 does not consider requires
8376                      // clauses when overriding.
8377                      /*ConsiderRequiresClauses=*/false))
8378         continue;
8379 
8380       if (Overridden.insert(BaseMD).second) {
8381         MD->addOverriddenMethod(BaseMD);
8382         CheckOverridingFunctionReturnType(MD, BaseMD);
8383         CheckOverridingFunctionAttributes(MD, BaseMD);
8384         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8385         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8386       }
8387 
8388       // A method can only override one function from each base class. We
8389       // don't track indirectly overridden methods from bases of bases.
8390       return true;
8391     }
8392 
8393     return false;
8394   };
8395 
8396   DC->lookupInBases(VisitBase, Paths);
8397   return !Overridden.empty();
8398 }
8399 
8400 namespace {
8401   // Struct for holding all of the extra arguments needed by
8402   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8403   struct ActOnFDArgs {
8404     Scope *S;
8405     Declarator &D;
8406     MultiTemplateParamsArg TemplateParamLists;
8407     bool AddToScope;
8408   };
8409 } // end anonymous namespace
8410 
8411 namespace {
8412 
8413 // Callback to only accept typo corrections that have a non-zero edit distance.
8414 // Also only accept corrections that have the same parent decl.
8415 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8416  public:
8417   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8418                             CXXRecordDecl *Parent)
8419       : Context(Context), OriginalFD(TypoFD),
8420         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8421 
8422   bool ValidateCandidate(const TypoCorrection &candidate) override {
8423     if (candidate.getEditDistance() == 0)
8424       return false;
8425 
8426     SmallVector<unsigned, 1> MismatchedParams;
8427     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8428                                           CDeclEnd = candidate.end();
8429          CDecl != CDeclEnd; ++CDecl) {
8430       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8431 
8432       if (FD && !FD->hasBody() &&
8433           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8434         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8435           CXXRecordDecl *Parent = MD->getParent();
8436           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8437             return true;
8438         } else if (!ExpectedParent) {
8439           return true;
8440         }
8441       }
8442     }
8443 
8444     return false;
8445   }
8446 
8447   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8448     return std::make_unique<DifferentNameValidatorCCC>(*this);
8449   }
8450 
8451  private:
8452   ASTContext &Context;
8453   FunctionDecl *OriginalFD;
8454   CXXRecordDecl *ExpectedParent;
8455 };
8456 
8457 } // end anonymous namespace
8458 
8459 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8460   TypoCorrectedFunctionDefinitions.insert(F);
8461 }
8462 
8463 /// Generate diagnostics for an invalid function redeclaration.
8464 ///
8465 /// This routine handles generating the diagnostic messages for an invalid
8466 /// function redeclaration, including finding possible similar declarations
8467 /// or performing typo correction if there are no previous declarations with
8468 /// the same name.
8469 ///
8470 /// Returns a NamedDecl iff typo correction was performed and substituting in
8471 /// the new declaration name does not cause new errors.
8472 static NamedDecl *DiagnoseInvalidRedeclaration(
8473     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8474     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8475   DeclarationName Name = NewFD->getDeclName();
8476   DeclContext *NewDC = NewFD->getDeclContext();
8477   SmallVector<unsigned, 1> MismatchedParams;
8478   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8479   TypoCorrection Correction;
8480   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8481   unsigned DiagMsg =
8482     IsLocalFriend ? diag::err_no_matching_local_friend :
8483     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8484     diag::err_member_decl_does_not_match;
8485   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8486                     IsLocalFriend ? Sema::LookupLocalFriendName
8487                                   : Sema::LookupOrdinaryName,
8488                     Sema::ForVisibleRedeclaration);
8489 
8490   NewFD->setInvalidDecl();
8491   if (IsLocalFriend)
8492     SemaRef.LookupName(Prev, S);
8493   else
8494     SemaRef.LookupQualifiedName(Prev, NewDC);
8495   assert(!Prev.isAmbiguous() &&
8496          "Cannot have an ambiguity in previous-declaration lookup");
8497   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8498   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8499                                 MD ? MD->getParent() : nullptr);
8500   if (!Prev.empty()) {
8501     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8502          Func != FuncEnd; ++Func) {
8503       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8504       if (FD &&
8505           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8506         // Add 1 to the index so that 0 can mean the mismatch didn't
8507         // involve a parameter
8508         unsigned ParamNum =
8509             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8510         NearMatches.push_back(std::make_pair(FD, ParamNum));
8511       }
8512     }
8513   // If the qualified name lookup yielded nothing, try typo correction
8514   } else if ((Correction = SemaRef.CorrectTypo(
8515                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8516                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8517                   IsLocalFriend ? nullptr : NewDC))) {
8518     // Set up everything for the call to ActOnFunctionDeclarator
8519     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8520                               ExtraArgs.D.getIdentifierLoc());
8521     Previous.clear();
8522     Previous.setLookupName(Correction.getCorrection());
8523     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8524                                     CDeclEnd = Correction.end();
8525          CDecl != CDeclEnd; ++CDecl) {
8526       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8527       if (FD && !FD->hasBody() &&
8528           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8529         Previous.addDecl(FD);
8530       }
8531     }
8532     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8533 
8534     NamedDecl *Result;
8535     // Retry building the function declaration with the new previous
8536     // declarations, and with errors suppressed.
8537     {
8538       // Trap errors.
8539       Sema::SFINAETrap Trap(SemaRef);
8540 
8541       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8542       // pieces need to verify the typo-corrected C++ declaration and hopefully
8543       // eliminate the need for the parameter pack ExtraArgs.
8544       Result = SemaRef.ActOnFunctionDeclarator(
8545           ExtraArgs.S, ExtraArgs.D,
8546           Correction.getCorrectionDecl()->getDeclContext(),
8547           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8548           ExtraArgs.AddToScope);
8549 
8550       if (Trap.hasErrorOccurred())
8551         Result = nullptr;
8552     }
8553 
8554     if (Result) {
8555       // Determine which correction we picked.
8556       Decl *Canonical = Result->getCanonicalDecl();
8557       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8558            I != E; ++I)
8559         if ((*I)->getCanonicalDecl() == Canonical)
8560           Correction.setCorrectionDecl(*I);
8561 
8562       // Let Sema know about the correction.
8563       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8564       SemaRef.diagnoseTypo(
8565           Correction,
8566           SemaRef.PDiag(IsLocalFriend
8567                           ? diag::err_no_matching_local_friend_suggest
8568                           : diag::err_member_decl_does_not_match_suggest)
8569             << Name << NewDC << IsDefinition);
8570       return Result;
8571     }
8572 
8573     // Pretend the typo correction never occurred
8574     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8575                               ExtraArgs.D.getIdentifierLoc());
8576     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8577     Previous.clear();
8578     Previous.setLookupName(Name);
8579   }
8580 
8581   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8582       << Name << NewDC << IsDefinition << NewFD->getLocation();
8583 
8584   bool NewFDisConst = false;
8585   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8586     NewFDisConst = NewMD->isConst();
8587 
8588   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8589        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8590        NearMatch != NearMatchEnd; ++NearMatch) {
8591     FunctionDecl *FD = NearMatch->first;
8592     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8593     bool FDisConst = MD && MD->isConst();
8594     bool IsMember = MD || !IsLocalFriend;
8595 
8596     // FIXME: These notes are poorly worded for the local friend case.
8597     if (unsigned Idx = NearMatch->second) {
8598       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8599       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8600       if (Loc.isInvalid()) Loc = FD->getLocation();
8601       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8602                                  : diag::note_local_decl_close_param_match)
8603         << Idx << FDParam->getType()
8604         << NewFD->getParamDecl(Idx - 1)->getType();
8605     } else if (FDisConst != NewFDisConst) {
8606       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8607           << NewFDisConst << FD->getSourceRange().getEnd()
8608           << (NewFDisConst
8609                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8610                                                  .getConstQualifierLoc())
8611                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8612                                                    .getRParenLoc()
8613                                                    .getLocWithOffset(1),
8614                                                " const"));
8615     } else
8616       SemaRef.Diag(FD->getLocation(),
8617                    IsMember ? diag::note_member_def_close_match
8618                             : diag::note_local_decl_close_match);
8619   }
8620   return nullptr;
8621 }
8622 
8623 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8624   switch (D.getDeclSpec().getStorageClassSpec()) {
8625   default: llvm_unreachable("Unknown storage class!");
8626   case DeclSpec::SCS_auto:
8627   case DeclSpec::SCS_register:
8628   case DeclSpec::SCS_mutable:
8629     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8630                  diag::err_typecheck_sclass_func);
8631     D.getMutableDeclSpec().ClearStorageClassSpecs();
8632     D.setInvalidType();
8633     break;
8634   case DeclSpec::SCS_unspecified: break;
8635   case DeclSpec::SCS_extern:
8636     if (D.getDeclSpec().isExternInLinkageSpec())
8637       return SC_None;
8638     return SC_Extern;
8639   case DeclSpec::SCS_static: {
8640     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8641       // C99 6.7.1p5:
8642       //   The declaration of an identifier for a function that has
8643       //   block scope shall have no explicit storage-class specifier
8644       //   other than extern
8645       // See also (C++ [dcl.stc]p4).
8646       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8647                    diag::err_static_block_func);
8648       break;
8649     } else
8650       return SC_Static;
8651   }
8652   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8653   }
8654 
8655   // No explicit storage class has already been returned
8656   return SC_None;
8657 }
8658 
8659 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8660                                            DeclContext *DC, QualType &R,
8661                                            TypeSourceInfo *TInfo,
8662                                            StorageClass SC,
8663                                            bool &IsVirtualOkay) {
8664   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8665   DeclarationName Name = NameInfo.getName();
8666 
8667   FunctionDecl *NewFD = nullptr;
8668   bool isInline = D.getDeclSpec().isInlineSpecified();
8669 
8670   if (!SemaRef.getLangOpts().CPlusPlus) {
8671     // Determine whether the function was written with a
8672     // prototype. This true when:
8673     //   - there is a prototype in the declarator, or
8674     //   - the type R of the function is some kind of typedef or other non-
8675     //     attributed reference to a type name (which eventually refers to a
8676     //     function type).
8677     bool HasPrototype =
8678       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8679       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8680 
8681     NewFD = FunctionDecl::Create(
8682         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8683         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8684         ConstexprSpecKind::Unspecified,
8685         /*TrailingRequiresClause=*/nullptr);
8686     if (D.isInvalidType())
8687       NewFD->setInvalidDecl();
8688 
8689     return NewFD;
8690   }
8691 
8692   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8693 
8694   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8695   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8696     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8697                  diag::err_constexpr_wrong_decl_kind)
8698         << static_cast<int>(ConstexprKind);
8699     ConstexprKind = ConstexprSpecKind::Unspecified;
8700     D.getMutableDeclSpec().ClearConstexprSpec();
8701   }
8702   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8703 
8704   // Check that the return type is not an abstract class type.
8705   // For record types, this is done by the AbstractClassUsageDiagnoser once
8706   // the class has been completely parsed.
8707   if (!DC->isRecord() &&
8708       SemaRef.RequireNonAbstractType(
8709           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8710           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8711     D.setInvalidType();
8712 
8713   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8714     // This is a C++ constructor declaration.
8715     assert(DC->isRecord() &&
8716            "Constructors can only be declared in a member context");
8717 
8718     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8719     return CXXConstructorDecl::Create(
8720         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8721         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8722         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8723         InheritedConstructor(), TrailingRequiresClause);
8724 
8725   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8726     // This is a C++ destructor declaration.
8727     if (DC->isRecord()) {
8728       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8729       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8730       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8731           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8732           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8733           /*isImplicitlyDeclared=*/false, ConstexprKind,
8734           TrailingRequiresClause);
8735 
8736       // If the destructor needs an implicit exception specification, set it
8737       // now. FIXME: It'd be nice to be able to create the right type to start
8738       // with, but the type needs to reference the destructor declaration.
8739       if (SemaRef.getLangOpts().CPlusPlus11)
8740         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8741 
8742       IsVirtualOkay = true;
8743       return NewDD;
8744 
8745     } else {
8746       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8747       D.setInvalidType();
8748 
8749       // Create a FunctionDecl to satisfy the function definition parsing
8750       // code path.
8751       return FunctionDecl::Create(
8752           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8753           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8754           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8755     }
8756 
8757   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8758     if (!DC->isRecord()) {
8759       SemaRef.Diag(D.getIdentifierLoc(),
8760            diag::err_conv_function_not_member);
8761       return nullptr;
8762     }
8763 
8764     SemaRef.CheckConversionDeclarator(D, R, SC);
8765     if (D.isInvalidType())
8766       return nullptr;
8767 
8768     IsVirtualOkay = true;
8769     return CXXConversionDecl::Create(
8770         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8771         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8772         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8773         TrailingRequiresClause);
8774 
8775   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8776     if (TrailingRequiresClause)
8777       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8778                    diag::err_trailing_requires_clause_on_deduction_guide)
8779           << TrailingRequiresClause->getSourceRange();
8780     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8781 
8782     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8783                                          ExplicitSpecifier, NameInfo, R, TInfo,
8784                                          D.getEndLoc());
8785   } else if (DC->isRecord()) {
8786     // If the name of the function is the same as the name of the record,
8787     // then this must be an invalid constructor that has a return type.
8788     // (The parser checks for a return type and makes the declarator a
8789     // constructor if it has no return type).
8790     if (Name.getAsIdentifierInfo() &&
8791         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8792       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8793         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8794         << SourceRange(D.getIdentifierLoc());
8795       return nullptr;
8796     }
8797 
8798     // This is a C++ method declaration.
8799     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8800         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8801         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8802         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8803     IsVirtualOkay = !Ret->isStatic();
8804     return Ret;
8805   } else {
8806     bool isFriend =
8807         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8808     if (!isFriend && SemaRef.CurContext->isRecord())
8809       return nullptr;
8810 
8811     // Determine whether the function was written with a
8812     // prototype. This true when:
8813     //   - we're in C++ (where every function has a prototype),
8814     return FunctionDecl::Create(
8815         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8816         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8817         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8818   }
8819 }
8820 
8821 enum OpenCLParamType {
8822   ValidKernelParam,
8823   PtrPtrKernelParam,
8824   PtrKernelParam,
8825   InvalidAddrSpacePtrKernelParam,
8826   InvalidKernelParam,
8827   RecordKernelParam
8828 };
8829 
8830 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8831   // Size dependent types are just typedefs to normal integer types
8832   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8833   // integers other than by their names.
8834   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8835 
8836   // Remove typedefs one by one until we reach a typedef
8837   // for a size dependent type.
8838   QualType DesugaredTy = Ty;
8839   do {
8840     ArrayRef<StringRef> Names(SizeTypeNames);
8841     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8842     if (Names.end() != Match)
8843       return true;
8844 
8845     Ty = DesugaredTy;
8846     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8847   } while (DesugaredTy != Ty);
8848 
8849   return false;
8850 }
8851 
8852 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8853   if (PT->isDependentType())
8854     return InvalidKernelParam;
8855 
8856   if (PT->isPointerType() || PT->isReferenceType()) {
8857     QualType PointeeType = PT->getPointeeType();
8858     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8859         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8860         PointeeType.getAddressSpace() == LangAS::Default)
8861       return InvalidAddrSpacePtrKernelParam;
8862 
8863     if (PointeeType->isPointerType()) {
8864       // This is a pointer to pointer parameter.
8865       // Recursively check inner type.
8866       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8867       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8868           ParamKind == InvalidKernelParam)
8869         return ParamKind;
8870 
8871       return PtrPtrKernelParam;
8872     }
8873 
8874     // C++ for OpenCL v1.0 s2.4:
8875     // Moreover the types used in parameters of the kernel functions must be:
8876     // Standard layout types for pointer parameters. The same applies to
8877     // reference if an implementation supports them in kernel parameters.
8878     if (S.getLangOpts().OpenCLCPlusPlus &&
8879         !S.getOpenCLOptions().isAvailableOption(
8880             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8881         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8882         !PointeeType->isStandardLayoutType())
8883       return InvalidKernelParam;
8884 
8885     return PtrKernelParam;
8886   }
8887 
8888   // OpenCL v1.2 s6.9.k:
8889   // Arguments to kernel functions in a program cannot be declared with the
8890   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8891   // uintptr_t or a struct and/or union that contain fields declared to be one
8892   // of these built-in scalar types.
8893   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8894     return InvalidKernelParam;
8895 
8896   if (PT->isImageType())
8897     return PtrKernelParam;
8898 
8899   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8900     return InvalidKernelParam;
8901 
8902   // OpenCL extension spec v1.2 s9.5:
8903   // This extension adds support for half scalar and vector types as built-in
8904   // types that can be used for arithmetic operations, conversions etc.
8905   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8906       PT->isHalfType())
8907     return InvalidKernelParam;
8908 
8909   // Look into an array argument to check if it has a forbidden type.
8910   if (PT->isArrayType()) {
8911     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8912     // Call ourself to check an underlying type of an array. Since the
8913     // getPointeeOrArrayElementType returns an innermost type which is not an
8914     // array, this recursive call only happens once.
8915     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8916   }
8917 
8918   // C++ for OpenCL v1.0 s2.4:
8919   // Moreover the types used in parameters of the kernel functions must be:
8920   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8921   // types) for parameters passed by value;
8922   if (S.getLangOpts().OpenCLCPlusPlus &&
8923       !S.getOpenCLOptions().isAvailableOption(
8924           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8925       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8926     return InvalidKernelParam;
8927 
8928   if (PT->isRecordType())
8929     return RecordKernelParam;
8930 
8931   return ValidKernelParam;
8932 }
8933 
8934 static void checkIsValidOpenCLKernelParameter(
8935   Sema &S,
8936   Declarator &D,
8937   ParmVarDecl *Param,
8938   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8939   QualType PT = Param->getType();
8940 
8941   // Cache the valid types we encounter to avoid rechecking structs that are
8942   // used again
8943   if (ValidTypes.count(PT.getTypePtr()))
8944     return;
8945 
8946   switch (getOpenCLKernelParameterType(S, PT)) {
8947   case PtrPtrKernelParam:
8948     // OpenCL v3.0 s6.11.a:
8949     // A kernel function argument cannot be declared as a pointer to a pointer
8950     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8951     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8952       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8953       D.setInvalidType();
8954       return;
8955     }
8956 
8957     ValidTypes.insert(PT.getTypePtr());
8958     return;
8959 
8960   case InvalidAddrSpacePtrKernelParam:
8961     // OpenCL v1.0 s6.5:
8962     // __kernel function arguments declared to be a pointer of a type can point
8963     // to one of the following address spaces only : __global, __local or
8964     // __constant.
8965     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8966     D.setInvalidType();
8967     return;
8968 
8969     // OpenCL v1.2 s6.9.k:
8970     // Arguments to kernel functions in a program cannot be declared with the
8971     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8972     // uintptr_t or a struct and/or union that contain fields declared to be
8973     // one of these built-in scalar types.
8974 
8975   case InvalidKernelParam:
8976     // OpenCL v1.2 s6.8 n:
8977     // A kernel function argument cannot be declared
8978     // of event_t type.
8979     // Do not diagnose half type since it is diagnosed as invalid argument
8980     // type for any function elsewhere.
8981     if (!PT->isHalfType()) {
8982       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8983 
8984       // Explain what typedefs are involved.
8985       const TypedefType *Typedef = nullptr;
8986       while ((Typedef = PT->getAs<TypedefType>())) {
8987         SourceLocation Loc = Typedef->getDecl()->getLocation();
8988         // SourceLocation may be invalid for a built-in type.
8989         if (Loc.isValid())
8990           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8991         PT = Typedef->desugar();
8992       }
8993     }
8994 
8995     D.setInvalidType();
8996     return;
8997 
8998   case PtrKernelParam:
8999   case ValidKernelParam:
9000     ValidTypes.insert(PT.getTypePtr());
9001     return;
9002 
9003   case RecordKernelParam:
9004     break;
9005   }
9006 
9007   // Track nested structs we will inspect
9008   SmallVector<const Decl *, 4> VisitStack;
9009 
9010   // Track where we are in the nested structs. Items will migrate from
9011   // VisitStack to HistoryStack as we do the DFS for bad field.
9012   SmallVector<const FieldDecl *, 4> HistoryStack;
9013   HistoryStack.push_back(nullptr);
9014 
9015   // At this point we already handled everything except of a RecordType or
9016   // an ArrayType of a RecordType.
9017   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9018   const RecordType *RecTy =
9019       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9020   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9021 
9022   VisitStack.push_back(RecTy->getDecl());
9023   assert(VisitStack.back() && "First decl null?");
9024 
9025   do {
9026     const Decl *Next = VisitStack.pop_back_val();
9027     if (!Next) {
9028       assert(!HistoryStack.empty());
9029       // Found a marker, we have gone up a level
9030       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9031         ValidTypes.insert(Hist->getType().getTypePtr());
9032 
9033       continue;
9034     }
9035 
9036     // Adds everything except the original parameter declaration (which is not a
9037     // field itself) to the history stack.
9038     const RecordDecl *RD;
9039     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9040       HistoryStack.push_back(Field);
9041 
9042       QualType FieldTy = Field->getType();
9043       // Other field types (known to be valid or invalid) are handled while we
9044       // walk around RecordDecl::fields().
9045       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9046              "Unexpected type.");
9047       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9048 
9049       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9050     } else {
9051       RD = cast<RecordDecl>(Next);
9052     }
9053 
9054     // Add a null marker so we know when we've gone back up a level
9055     VisitStack.push_back(nullptr);
9056 
9057     for (const auto *FD : RD->fields()) {
9058       QualType QT = FD->getType();
9059 
9060       if (ValidTypes.count(QT.getTypePtr()))
9061         continue;
9062 
9063       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9064       if (ParamType == ValidKernelParam)
9065         continue;
9066 
9067       if (ParamType == RecordKernelParam) {
9068         VisitStack.push_back(FD);
9069         continue;
9070       }
9071 
9072       // OpenCL v1.2 s6.9.p:
9073       // Arguments to kernel functions that are declared to be a struct or union
9074       // do not allow OpenCL objects to be passed as elements of the struct or
9075       // union.
9076       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9077           ParamType == InvalidAddrSpacePtrKernelParam) {
9078         S.Diag(Param->getLocation(),
9079                diag::err_record_with_pointers_kernel_param)
9080           << PT->isUnionType()
9081           << PT;
9082       } else {
9083         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9084       }
9085 
9086       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9087           << OrigRecDecl->getDeclName();
9088 
9089       // We have an error, now let's go back up through history and show where
9090       // the offending field came from
9091       for (ArrayRef<const FieldDecl *>::const_iterator
9092                I = HistoryStack.begin() + 1,
9093                E = HistoryStack.end();
9094            I != E; ++I) {
9095         const FieldDecl *OuterField = *I;
9096         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9097           << OuterField->getType();
9098       }
9099 
9100       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9101         << QT->isPointerType()
9102         << QT;
9103       D.setInvalidType();
9104       return;
9105     }
9106   } while (!VisitStack.empty());
9107 }
9108 
9109 /// Find the DeclContext in which a tag is implicitly declared if we see an
9110 /// elaborated type specifier in the specified context, and lookup finds
9111 /// nothing.
9112 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9113   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9114     DC = DC->getParent();
9115   return DC;
9116 }
9117 
9118 /// Find the Scope in which a tag is implicitly declared if we see an
9119 /// elaborated type specifier in the specified context, and lookup finds
9120 /// nothing.
9121 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9122   while (S->isClassScope() ||
9123          (LangOpts.CPlusPlus &&
9124           S->isFunctionPrototypeScope()) ||
9125          ((S->getFlags() & Scope::DeclScope) == 0) ||
9126          (S->getEntity() && S->getEntity()->isTransparentContext()))
9127     S = S->getParent();
9128   return S;
9129 }
9130 
9131 NamedDecl*
9132 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9133                               TypeSourceInfo *TInfo, LookupResult &Previous,
9134                               MultiTemplateParamsArg TemplateParamListsRef,
9135                               bool &AddToScope) {
9136   QualType R = TInfo->getType();
9137 
9138   assert(R->isFunctionType());
9139   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9140     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9141 
9142   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9143   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9144   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9145     if (!TemplateParamLists.empty() &&
9146         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9147       TemplateParamLists.back() = Invented;
9148     else
9149       TemplateParamLists.push_back(Invented);
9150   }
9151 
9152   // TODO: consider using NameInfo for diagnostic.
9153   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9154   DeclarationName Name = NameInfo.getName();
9155   StorageClass SC = getFunctionStorageClass(*this, D);
9156 
9157   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9158     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9159          diag::err_invalid_thread)
9160       << DeclSpec::getSpecifierName(TSCS);
9161 
9162   if (D.isFirstDeclarationOfMember())
9163     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9164                            D.getIdentifierLoc());
9165 
9166   bool isFriend = false;
9167   FunctionTemplateDecl *FunctionTemplate = nullptr;
9168   bool isMemberSpecialization = false;
9169   bool isFunctionTemplateSpecialization = false;
9170 
9171   bool isDependentClassScopeExplicitSpecialization = false;
9172   bool HasExplicitTemplateArgs = false;
9173   TemplateArgumentListInfo TemplateArgs;
9174 
9175   bool isVirtualOkay = false;
9176 
9177   DeclContext *OriginalDC = DC;
9178   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9179 
9180   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9181                                               isVirtualOkay);
9182   if (!NewFD) return nullptr;
9183 
9184   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9185     NewFD->setTopLevelDeclInObjCContainer();
9186 
9187   // Set the lexical context. If this is a function-scope declaration, or has a
9188   // C++ scope specifier, or is the object of a friend declaration, the lexical
9189   // context will be different from the semantic context.
9190   NewFD->setLexicalDeclContext(CurContext);
9191 
9192   if (IsLocalExternDecl)
9193     NewFD->setLocalExternDecl();
9194 
9195   if (getLangOpts().CPlusPlus) {
9196     bool isInline = D.getDeclSpec().isInlineSpecified();
9197     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9198     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9199     isFriend = D.getDeclSpec().isFriendSpecified();
9200     if (isFriend && !isInline && D.isFunctionDefinition()) {
9201       // C++ [class.friend]p5
9202       //   A function can be defined in a friend declaration of a
9203       //   class . . . . Such a function is implicitly inline.
9204       NewFD->setImplicitlyInline();
9205     }
9206 
9207     // If this is a method defined in an __interface, and is not a constructor
9208     // or an overloaded operator, then set the pure flag (isVirtual will already
9209     // return true).
9210     if (const CXXRecordDecl *Parent =
9211           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9212       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9213         NewFD->setPure(true);
9214 
9215       // C++ [class.union]p2
9216       //   A union can have member functions, but not virtual functions.
9217       if (isVirtual && Parent->isUnion()) {
9218         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9219         NewFD->setInvalidDecl();
9220       }
9221       if ((Parent->isClass() || Parent->isStruct()) &&
9222           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9223           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9224           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9225         if (auto *Def = Parent->getDefinition())
9226           Def->setInitMethod(true);
9227       }
9228     }
9229 
9230     SetNestedNameSpecifier(*this, NewFD, D);
9231     isMemberSpecialization = false;
9232     isFunctionTemplateSpecialization = false;
9233     if (D.isInvalidType())
9234       NewFD->setInvalidDecl();
9235 
9236     // Match up the template parameter lists with the scope specifier, then
9237     // determine whether we have a template or a template specialization.
9238     bool Invalid = false;
9239     TemplateParameterList *TemplateParams =
9240         MatchTemplateParametersToScopeSpecifier(
9241             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9242             D.getCXXScopeSpec(),
9243             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9244                 ? D.getName().TemplateId
9245                 : nullptr,
9246             TemplateParamLists, isFriend, isMemberSpecialization,
9247             Invalid);
9248     if (TemplateParams) {
9249       // Check that we can declare a template here.
9250       if (CheckTemplateDeclScope(S, TemplateParams))
9251         NewFD->setInvalidDecl();
9252 
9253       if (TemplateParams->size() > 0) {
9254         // This is a function template
9255 
9256         // A destructor cannot be a template.
9257         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9258           Diag(NewFD->getLocation(), diag::err_destructor_template);
9259           NewFD->setInvalidDecl();
9260         }
9261 
9262         // If we're adding a template to a dependent context, we may need to
9263         // rebuilding some of the types used within the template parameter list,
9264         // now that we know what the current instantiation is.
9265         if (DC->isDependentContext()) {
9266           ContextRAII SavedContext(*this, DC);
9267           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9268             Invalid = true;
9269         }
9270 
9271         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9272                                                         NewFD->getLocation(),
9273                                                         Name, TemplateParams,
9274                                                         NewFD);
9275         FunctionTemplate->setLexicalDeclContext(CurContext);
9276         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9277 
9278         // For source fidelity, store the other template param lists.
9279         if (TemplateParamLists.size() > 1) {
9280           NewFD->setTemplateParameterListsInfo(Context,
9281               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9282                   .drop_back(1));
9283         }
9284       } else {
9285         // This is a function template specialization.
9286         isFunctionTemplateSpecialization = true;
9287         // For source fidelity, store all the template param lists.
9288         if (TemplateParamLists.size() > 0)
9289           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9290 
9291         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9292         if (isFriend) {
9293           // We want to remove the "template<>", found here.
9294           SourceRange RemoveRange = TemplateParams->getSourceRange();
9295 
9296           // If we remove the template<> and the name is not a
9297           // template-id, we're actually silently creating a problem:
9298           // the friend declaration will refer to an untemplated decl,
9299           // and clearly the user wants a template specialization.  So
9300           // we need to insert '<>' after the name.
9301           SourceLocation InsertLoc;
9302           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9303             InsertLoc = D.getName().getSourceRange().getEnd();
9304             InsertLoc = getLocForEndOfToken(InsertLoc);
9305           }
9306 
9307           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9308             << Name << RemoveRange
9309             << FixItHint::CreateRemoval(RemoveRange)
9310             << FixItHint::CreateInsertion(InsertLoc, "<>");
9311           Invalid = true;
9312         }
9313       }
9314     } else {
9315       // Check that we can declare a template here.
9316       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9317           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9318         NewFD->setInvalidDecl();
9319 
9320       // All template param lists were matched against the scope specifier:
9321       // this is NOT (an explicit specialization of) a template.
9322       if (TemplateParamLists.size() > 0)
9323         // For source fidelity, store all the template param lists.
9324         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9325     }
9326 
9327     if (Invalid) {
9328       NewFD->setInvalidDecl();
9329       if (FunctionTemplate)
9330         FunctionTemplate->setInvalidDecl();
9331     }
9332 
9333     // C++ [dcl.fct.spec]p5:
9334     //   The virtual specifier shall only be used in declarations of
9335     //   nonstatic class member functions that appear within a
9336     //   member-specification of a class declaration; see 10.3.
9337     //
9338     if (isVirtual && !NewFD->isInvalidDecl()) {
9339       if (!isVirtualOkay) {
9340         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9341              diag::err_virtual_non_function);
9342       } else if (!CurContext->isRecord()) {
9343         // 'virtual' was specified outside of the class.
9344         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9345              diag::err_virtual_out_of_class)
9346           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9347       } else if (NewFD->getDescribedFunctionTemplate()) {
9348         // C++ [temp.mem]p3:
9349         //  A member function template shall not be virtual.
9350         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9351              diag::err_virtual_member_function_template)
9352           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9353       } else {
9354         // Okay: Add virtual to the method.
9355         NewFD->setVirtualAsWritten(true);
9356       }
9357 
9358       if (getLangOpts().CPlusPlus14 &&
9359           NewFD->getReturnType()->isUndeducedType())
9360         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9361     }
9362 
9363     if (getLangOpts().CPlusPlus14 &&
9364         (NewFD->isDependentContext() ||
9365          (isFriend && CurContext->isDependentContext())) &&
9366         NewFD->getReturnType()->isUndeducedType()) {
9367       // If the function template is referenced directly (for instance, as a
9368       // member of the current instantiation), pretend it has a dependent type.
9369       // This is not really justified by the standard, but is the only sane
9370       // thing to do.
9371       // FIXME: For a friend function, we have not marked the function as being
9372       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9373       const FunctionProtoType *FPT =
9374           NewFD->getType()->castAs<FunctionProtoType>();
9375       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9376       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9377                                              FPT->getExtProtoInfo()));
9378     }
9379 
9380     // C++ [dcl.fct.spec]p3:
9381     //  The inline specifier shall not appear on a block scope function
9382     //  declaration.
9383     if (isInline && !NewFD->isInvalidDecl()) {
9384       if (CurContext->isFunctionOrMethod()) {
9385         // 'inline' is not allowed on block scope function declaration.
9386         Diag(D.getDeclSpec().getInlineSpecLoc(),
9387              diag::err_inline_declaration_block_scope) << Name
9388           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9389       }
9390     }
9391 
9392     // C++ [dcl.fct.spec]p6:
9393     //  The explicit specifier shall be used only in the declaration of a
9394     //  constructor or conversion function within its class definition;
9395     //  see 12.3.1 and 12.3.2.
9396     if (hasExplicit && !NewFD->isInvalidDecl() &&
9397         !isa<CXXDeductionGuideDecl>(NewFD)) {
9398       if (!CurContext->isRecord()) {
9399         // 'explicit' was specified outside of the class.
9400         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9401              diag::err_explicit_out_of_class)
9402             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9403       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9404                  !isa<CXXConversionDecl>(NewFD)) {
9405         // 'explicit' was specified on a function that wasn't a constructor
9406         // or conversion function.
9407         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9408              diag::err_explicit_non_ctor_or_conv_function)
9409             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9410       }
9411     }
9412 
9413     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9414     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9415       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9416       // are implicitly inline.
9417       NewFD->setImplicitlyInline();
9418 
9419       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9420       // be either constructors or to return a literal type. Therefore,
9421       // destructors cannot be declared constexpr.
9422       if (isa<CXXDestructorDecl>(NewFD) &&
9423           (!getLangOpts().CPlusPlus20 ||
9424            ConstexprKind == ConstexprSpecKind::Consteval)) {
9425         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9426             << static_cast<int>(ConstexprKind);
9427         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9428                                     ? ConstexprSpecKind::Unspecified
9429                                     : ConstexprSpecKind::Constexpr);
9430       }
9431       // C++20 [dcl.constexpr]p2: An allocation function, or a
9432       // deallocation function shall not be declared with the consteval
9433       // specifier.
9434       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9435           (NewFD->getOverloadedOperator() == OO_New ||
9436            NewFD->getOverloadedOperator() == OO_Array_New ||
9437            NewFD->getOverloadedOperator() == OO_Delete ||
9438            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9439         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9440              diag::err_invalid_consteval_decl_kind)
9441             << NewFD;
9442         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9443       }
9444     }
9445 
9446     // If __module_private__ was specified, mark the function accordingly.
9447     if (D.getDeclSpec().isModulePrivateSpecified()) {
9448       if (isFunctionTemplateSpecialization) {
9449         SourceLocation ModulePrivateLoc
9450           = D.getDeclSpec().getModulePrivateSpecLoc();
9451         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9452           << 0
9453           << FixItHint::CreateRemoval(ModulePrivateLoc);
9454       } else {
9455         NewFD->setModulePrivate();
9456         if (FunctionTemplate)
9457           FunctionTemplate->setModulePrivate();
9458       }
9459     }
9460 
9461     if (isFriend) {
9462       if (FunctionTemplate) {
9463         FunctionTemplate->setObjectOfFriendDecl();
9464         FunctionTemplate->setAccess(AS_public);
9465       }
9466       NewFD->setObjectOfFriendDecl();
9467       NewFD->setAccess(AS_public);
9468     }
9469 
9470     // If a function is defined as defaulted or deleted, mark it as such now.
9471     // We'll do the relevant checks on defaulted / deleted functions later.
9472     switch (D.getFunctionDefinitionKind()) {
9473     case FunctionDefinitionKind::Declaration:
9474     case FunctionDefinitionKind::Definition:
9475       break;
9476 
9477     case FunctionDefinitionKind::Defaulted:
9478       NewFD->setDefaulted();
9479       break;
9480 
9481     case FunctionDefinitionKind::Deleted:
9482       NewFD->setDeletedAsWritten();
9483       break;
9484     }
9485 
9486     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9487         D.isFunctionDefinition()) {
9488       // C++ [class.mfct]p2:
9489       //   A member function may be defined (8.4) in its class definition, in
9490       //   which case it is an inline member function (7.1.2)
9491       NewFD->setImplicitlyInline();
9492     }
9493 
9494     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9495         !CurContext->isRecord()) {
9496       // C++ [class.static]p1:
9497       //   A data or function member of a class may be declared static
9498       //   in a class definition, in which case it is a static member of
9499       //   the class.
9500 
9501       // Complain about the 'static' specifier if it's on an out-of-line
9502       // member function definition.
9503 
9504       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9505       // member function template declaration and class member template
9506       // declaration (MSVC versions before 2015), warn about this.
9507       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9508            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9509              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9510            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9511            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9512         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9513     }
9514 
9515     // C++11 [except.spec]p15:
9516     //   A deallocation function with no exception-specification is treated
9517     //   as if it were specified with noexcept(true).
9518     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9519     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9520          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9521         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9522       NewFD->setType(Context.getFunctionType(
9523           FPT->getReturnType(), FPT->getParamTypes(),
9524           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9525   }
9526 
9527   // Filter out previous declarations that don't match the scope.
9528   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9529                        D.getCXXScopeSpec().isNotEmpty() ||
9530                        isMemberSpecialization ||
9531                        isFunctionTemplateSpecialization);
9532 
9533   // Handle GNU asm-label extension (encoded as an attribute).
9534   if (Expr *E = (Expr*) D.getAsmLabel()) {
9535     // The parser guarantees this is a string.
9536     StringLiteral *SE = cast<StringLiteral>(E);
9537     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9538                                         /*IsLiteralLabel=*/true,
9539                                         SE->getStrTokenLoc(0)));
9540   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9541     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9542       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9543     if (I != ExtnameUndeclaredIdentifiers.end()) {
9544       if (isDeclExternC(NewFD)) {
9545         NewFD->addAttr(I->second);
9546         ExtnameUndeclaredIdentifiers.erase(I);
9547       } else
9548         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9549             << /*Variable*/0 << NewFD;
9550     }
9551   }
9552 
9553   // Copy the parameter declarations from the declarator D to the function
9554   // declaration NewFD, if they are available.  First scavenge them into Params.
9555   SmallVector<ParmVarDecl*, 16> Params;
9556   unsigned FTIIdx;
9557   if (D.isFunctionDeclarator(FTIIdx)) {
9558     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9559 
9560     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9561     // function that takes no arguments, not a function that takes a
9562     // single void argument.
9563     // We let through "const void" here because Sema::GetTypeForDeclarator
9564     // already checks for that case.
9565     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9566       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9567         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9568         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9569         Param->setDeclContext(NewFD);
9570         Params.push_back(Param);
9571 
9572         if (Param->isInvalidDecl())
9573           NewFD->setInvalidDecl();
9574       }
9575     }
9576 
9577     if (!getLangOpts().CPlusPlus) {
9578       // In C, find all the tag declarations from the prototype and move them
9579       // into the function DeclContext. Remove them from the surrounding tag
9580       // injection context of the function, which is typically but not always
9581       // the TU.
9582       DeclContext *PrototypeTagContext =
9583           getTagInjectionContext(NewFD->getLexicalDeclContext());
9584       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9585         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9586 
9587         // We don't want to reparent enumerators. Look at their parent enum
9588         // instead.
9589         if (!TD) {
9590           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9591             TD = cast<EnumDecl>(ECD->getDeclContext());
9592         }
9593         if (!TD)
9594           continue;
9595         DeclContext *TagDC = TD->getLexicalDeclContext();
9596         if (!TagDC->containsDecl(TD))
9597           continue;
9598         TagDC->removeDecl(TD);
9599         TD->setDeclContext(NewFD);
9600         NewFD->addDecl(TD);
9601 
9602         // Preserve the lexical DeclContext if it is not the surrounding tag
9603         // injection context of the FD. In this example, the semantic context of
9604         // E will be f and the lexical context will be S, while both the
9605         // semantic and lexical contexts of S will be f:
9606         //   void f(struct S { enum E { a } f; } s);
9607         if (TagDC != PrototypeTagContext)
9608           TD->setLexicalDeclContext(TagDC);
9609       }
9610     }
9611   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9612     // When we're declaring a function with a typedef, typeof, etc as in the
9613     // following example, we'll need to synthesize (unnamed)
9614     // parameters for use in the declaration.
9615     //
9616     // @code
9617     // typedef void fn(int);
9618     // fn f;
9619     // @endcode
9620 
9621     // Synthesize a parameter for each argument type.
9622     for (const auto &AI : FT->param_types()) {
9623       ParmVarDecl *Param =
9624           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9625       Param->setScopeInfo(0, Params.size());
9626       Params.push_back(Param);
9627     }
9628   } else {
9629     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9630            "Should not need args for typedef of non-prototype fn");
9631   }
9632 
9633   // Finally, we know we have the right number of parameters, install them.
9634   NewFD->setParams(Params);
9635 
9636   if (D.getDeclSpec().isNoreturnSpecified())
9637     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9638                                            D.getDeclSpec().getNoreturnSpecLoc(),
9639                                            AttributeCommonInfo::AS_Keyword));
9640 
9641   // Functions returning a variably modified type violate C99 6.7.5.2p2
9642   // because all functions have linkage.
9643   if (!NewFD->isInvalidDecl() &&
9644       NewFD->getReturnType()->isVariablyModifiedType()) {
9645     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9646     NewFD->setInvalidDecl();
9647   }
9648 
9649   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9650   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9651       !NewFD->hasAttr<SectionAttr>())
9652     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9653         Context, PragmaClangTextSection.SectionName,
9654         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9655 
9656   // Apply an implicit SectionAttr if #pragma code_seg is active.
9657   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9658       !NewFD->hasAttr<SectionAttr>()) {
9659     NewFD->addAttr(SectionAttr::CreateImplicit(
9660         Context, CodeSegStack.CurrentValue->getString(),
9661         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9662         SectionAttr::Declspec_allocate));
9663     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9664                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9665                          ASTContext::PSF_Read,
9666                      NewFD))
9667       NewFD->dropAttr<SectionAttr>();
9668   }
9669 
9670   // Apply an implicit CodeSegAttr from class declspec or
9671   // apply an implicit SectionAttr from #pragma code_seg if active.
9672   if (!NewFD->hasAttr<CodeSegAttr>()) {
9673     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9674                                                                  D.isFunctionDefinition())) {
9675       NewFD->addAttr(SAttr);
9676     }
9677   }
9678 
9679   // Handle attributes.
9680   ProcessDeclAttributes(S, NewFD, D);
9681 
9682   if (getLangOpts().OpenCL) {
9683     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9684     // type declaration will generate a compilation error.
9685     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9686     if (AddressSpace != LangAS::Default) {
9687       Diag(NewFD->getLocation(),
9688            diag::err_opencl_return_value_with_address_space);
9689       NewFD->setInvalidDecl();
9690     }
9691   }
9692 
9693   if (!getLangOpts().CPlusPlus) {
9694     // Perform semantic checking on the function declaration.
9695     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9696       CheckMain(NewFD, D.getDeclSpec());
9697 
9698     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9699       CheckMSVCRTEntryPoint(NewFD);
9700 
9701     if (!NewFD->isInvalidDecl())
9702       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9703                                                   isMemberSpecialization));
9704     else if (!Previous.empty())
9705       // Recover gracefully from an invalid redeclaration.
9706       D.setRedeclaration(true);
9707     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9708             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9709            "previous declaration set still overloaded");
9710 
9711     // Diagnose no-prototype function declarations with calling conventions that
9712     // don't support variadic calls. Only do this in C and do it after merging
9713     // possibly prototyped redeclarations.
9714     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9715     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9716       CallingConv CC = FT->getExtInfo().getCC();
9717       if (!supportsVariadicCall(CC)) {
9718         // Windows system headers sometimes accidentally use stdcall without
9719         // (void) parameters, so we relax this to a warning.
9720         int DiagID =
9721             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9722         Diag(NewFD->getLocation(), DiagID)
9723             << FunctionType::getNameForCallConv(CC);
9724       }
9725     }
9726 
9727    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9728        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9729      checkNonTrivialCUnion(NewFD->getReturnType(),
9730                            NewFD->getReturnTypeSourceRange().getBegin(),
9731                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9732   } else {
9733     // C++11 [replacement.functions]p3:
9734     //  The program's definitions shall not be specified as inline.
9735     //
9736     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9737     //
9738     // Suppress the diagnostic if the function is __attribute__((used)), since
9739     // that forces an external definition to be emitted.
9740     if (D.getDeclSpec().isInlineSpecified() &&
9741         NewFD->isReplaceableGlobalAllocationFunction() &&
9742         !NewFD->hasAttr<UsedAttr>())
9743       Diag(D.getDeclSpec().getInlineSpecLoc(),
9744            diag::ext_operator_new_delete_declared_inline)
9745         << NewFD->getDeclName();
9746 
9747     // If the declarator is a template-id, translate the parser's template
9748     // argument list into our AST format.
9749     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9750       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9751       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9752       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9753       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9754                                          TemplateId->NumArgs);
9755       translateTemplateArguments(TemplateArgsPtr,
9756                                  TemplateArgs);
9757 
9758       HasExplicitTemplateArgs = true;
9759 
9760       if (NewFD->isInvalidDecl()) {
9761         HasExplicitTemplateArgs = false;
9762       } else if (FunctionTemplate) {
9763         // Function template with explicit template arguments.
9764         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9765           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9766 
9767         HasExplicitTemplateArgs = false;
9768       } else {
9769         assert((isFunctionTemplateSpecialization ||
9770                 D.getDeclSpec().isFriendSpecified()) &&
9771                "should have a 'template<>' for this decl");
9772         // "friend void foo<>(int);" is an implicit specialization decl.
9773         isFunctionTemplateSpecialization = true;
9774       }
9775     } else if (isFriend && isFunctionTemplateSpecialization) {
9776       // This combination is only possible in a recovery case;  the user
9777       // wrote something like:
9778       //   template <> friend void foo(int);
9779       // which we're recovering from as if the user had written:
9780       //   friend void foo<>(int);
9781       // Go ahead and fake up a template id.
9782       HasExplicitTemplateArgs = true;
9783       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9784       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9785     }
9786 
9787     // We do not add HD attributes to specializations here because
9788     // they may have different constexpr-ness compared to their
9789     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9790     // may end up with different effective targets. Instead, a
9791     // specialization inherits its target attributes from its template
9792     // in the CheckFunctionTemplateSpecialization() call below.
9793     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9794       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9795 
9796     // If it's a friend (and only if it's a friend), it's possible
9797     // that either the specialized function type or the specialized
9798     // template is dependent, and therefore matching will fail.  In
9799     // this case, don't check the specialization yet.
9800     if (isFunctionTemplateSpecialization && isFriend &&
9801         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9802          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9803              TemplateArgs.arguments()))) {
9804       assert(HasExplicitTemplateArgs &&
9805              "friend function specialization without template args");
9806       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9807                                                        Previous))
9808         NewFD->setInvalidDecl();
9809     } else if (isFunctionTemplateSpecialization) {
9810       if (CurContext->isDependentContext() && CurContext->isRecord()
9811           && !isFriend) {
9812         isDependentClassScopeExplicitSpecialization = true;
9813       } else if (!NewFD->isInvalidDecl() &&
9814                  CheckFunctionTemplateSpecialization(
9815                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9816                      Previous))
9817         NewFD->setInvalidDecl();
9818 
9819       // C++ [dcl.stc]p1:
9820       //   A storage-class-specifier shall not be specified in an explicit
9821       //   specialization (14.7.3)
9822       FunctionTemplateSpecializationInfo *Info =
9823           NewFD->getTemplateSpecializationInfo();
9824       if (Info && SC != SC_None) {
9825         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9826           Diag(NewFD->getLocation(),
9827                diag::err_explicit_specialization_inconsistent_storage_class)
9828             << SC
9829             << FixItHint::CreateRemoval(
9830                                       D.getDeclSpec().getStorageClassSpecLoc());
9831 
9832         else
9833           Diag(NewFD->getLocation(),
9834                diag::ext_explicit_specialization_storage_class)
9835             << FixItHint::CreateRemoval(
9836                                       D.getDeclSpec().getStorageClassSpecLoc());
9837       }
9838     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9839       if (CheckMemberSpecialization(NewFD, Previous))
9840           NewFD->setInvalidDecl();
9841     }
9842 
9843     // Perform semantic checking on the function declaration.
9844     if (!isDependentClassScopeExplicitSpecialization) {
9845       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9846         CheckMain(NewFD, D.getDeclSpec());
9847 
9848       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9849         CheckMSVCRTEntryPoint(NewFD);
9850 
9851       if (!NewFD->isInvalidDecl())
9852         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9853                                                     isMemberSpecialization));
9854       else if (!Previous.empty())
9855         // Recover gracefully from an invalid redeclaration.
9856         D.setRedeclaration(true);
9857     }
9858 
9859     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9860             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9861            "previous declaration set still overloaded");
9862 
9863     NamedDecl *PrincipalDecl = (FunctionTemplate
9864                                 ? cast<NamedDecl>(FunctionTemplate)
9865                                 : NewFD);
9866 
9867     if (isFriend && NewFD->getPreviousDecl()) {
9868       AccessSpecifier Access = AS_public;
9869       if (!NewFD->isInvalidDecl())
9870         Access = NewFD->getPreviousDecl()->getAccess();
9871 
9872       NewFD->setAccess(Access);
9873       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9874     }
9875 
9876     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9877         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9878       PrincipalDecl->setNonMemberOperator();
9879 
9880     // If we have a function template, check the template parameter
9881     // list. This will check and merge default template arguments.
9882     if (FunctionTemplate) {
9883       FunctionTemplateDecl *PrevTemplate =
9884                                      FunctionTemplate->getPreviousDecl();
9885       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9886                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9887                                     : nullptr,
9888                             D.getDeclSpec().isFriendSpecified()
9889                               ? (D.isFunctionDefinition()
9890                                    ? TPC_FriendFunctionTemplateDefinition
9891                                    : TPC_FriendFunctionTemplate)
9892                               : (D.getCXXScopeSpec().isSet() &&
9893                                  DC && DC->isRecord() &&
9894                                  DC->isDependentContext())
9895                                   ? TPC_ClassTemplateMember
9896                                   : TPC_FunctionTemplate);
9897     }
9898 
9899     if (NewFD->isInvalidDecl()) {
9900       // Ignore all the rest of this.
9901     } else if (!D.isRedeclaration()) {
9902       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9903                                        AddToScope };
9904       // Fake up an access specifier if it's supposed to be a class member.
9905       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9906         NewFD->setAccess(AS_public);
9907 
9908       // Qualified decls generally require a previous declaration.
9909       if (D.getCXXScopeSpec().isSet()) {
9910         // ...with the major exception of templated-scope or
9911         // dependent-scope friend declarations.
9912 
9913         // TODO: we currently also suppress this check in dependent
9914         // contexts because (1) the parameter depth will be off when
9915         // matching friend templates and (2) we might actually be
9916         // selecting a friend based on a dependent factor.  But there
9917         // are situations where these conditions don't apply and we
9918         // can actually do this check immediately.
9919         //
9920         // Unless the scope is dependent, it's always an error if qualified
9921         // redeclaration lookup found nothing at all. Diagnose that now;
9922         // nothing will diagnose that error later.
9923         if (isFriend &&
9924             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9925              (!Previous.empty() && CurContext->isDependentContext()))) {
9926           // ignore these
9927         } else if (NewFD->isCPUDispatchMultiVersion() ||
9928                    NewFD->isCPUSpecificMultiVersion()) {
9929           // ignore this, we allow the redeclaration behavior here to create new
9930           // versions of the function.
9931         } else {
9932           // The user tried to provide an out-of-line definition for a
9933           // function that is a member of a class or namespace, but there
9934           // was no such member function declared (C++ [class.mfct]p2,
9935           // C++ [namespace.memdef]p2). For example:
9936           //
9937           // class X {
9938           //   void f() const;
9939           // };
9940           //
9941           // void X::f() { } // ill-formed
9942           //
9943           // Complain about this problem, and attempt to suggest close
9944           // matches (e.g., those that differ only in cv-qualifiers and
9945           // whether the parameter types are references).
9946 
9947           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9948                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9949             AddToScope = ExtraArgs.AddToScope;
9950             return Result;
9951           }
9952         }
9953 
9954         // Unqualified local friend declarations are required to resolve
9955         // to something.
9956       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9957         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9958                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9959           AddToScope = ExtraArgs.AddToScope;
9960           return Result;
9961         }
9962       }
9963     } else if (!D.isFunctionDefinition() &&
9964                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9965                !isFriend && !isFunctionTemplateSpecialization &&
9966                !isMemberSpecialization) {
9967       // An out-of-line member function declaration must also be a
9968       // definition (C++ [class.mfct]p2).
9969       // Note that this is not the case for explicit specializations of
9970       // function templates or member functions of class templates, per
9971       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9972       // extension for compatibility with old SWIG code which likes to
9973       // generate them.
9974       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9975         << D.getCXXScopeSpec().getRange();
9976     }
9977   }
9978 
9979   // If this is the first declaration of a library builtin function, add
9980   // attributes as appropriate.
9981   if (!D.isRedeclaration() &&
9982       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9983     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9984       if (unsigned BuiltinID = II->getBuiltinID()) {
9985         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9986           // Validate the type matches unless this builtin is specified as
9987           // matching regardless of its declared type.
9988           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9989             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9990           } else {
9991             ASTContext::GetBuiltinTypeError Error;
9992             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9993             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9994 
9995             if (!Error && !BuiltinType.isNull() &&
9996                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9997                     NewFD->getType(), BuiltinType))
9998               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9999           }
10000         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
10001                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10002           // FIXME: We should consider this a builtin only in the std namespace.
10003           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10004         }
10005       }
10006     }
10007   }
10008 
10009   ProcessPragmaWeak(S, NewFD);
10010   checkAttributesAfterMerging(*this, *NewFD);
10011 
10012   AddKnownFunctionAttributes(NewFD);
10013 
10014   if (NewFD->hasAttr<OverloadableAttr>() &&
10015       !NewFD->getType()->getAs<FunctionProtoType>()) {
10016     Diag(NewFD->getLocation(),
10017          diag::err_attribute_overloadable_no_prototype)
10018       << NewFD;
10019 
10020     // Turn this into a variadic function with no parameters.
10021     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10022     FunctionProtoType::ExtProtoInfo EPI(
10023         Context.getDefaultCallingConvention(true, false));
10024     EPI.Variadic = true;
10025     EPI.ExtInfo = FT->getExtInfo();
10026 
10027     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10028     NewFD->setType(R);
10029   }
10030 
10031   // If there's a #pragma GCC visibility in scope, and this isn't a class
10032   // member, set the visibility of this function.
10033   if (!DC->isRecord() && NewFD->isExternallyVisible())
10034     AddPushedVisibilityAttribute(NewFD);
10035 
10036   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10037   // marking the function.
10038   AddCFAuditedAttribute(NewFD);
10039 
10040   // If this is a function definition, check if we have to apply optnone due to
10041   // a pragma.
10042   if(D.isFunctionDefinition())
10043     AddRangeBasedOptnone(NewFD);
10044 
10045   // If this is the first declaration of an extern C variable, update
10046   // the map of such variables.
10047   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10048       isIncompleteDeclExternC(*this, NewFD))
10049     RegisterLocallyScopedExternCDecl(NewFD, S);
10050 
10051   // Set this FunctionDecl's range up to the right paren.
10052   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10053 
10054   if (D.isRedeclaration() && !Previous.empty()) {
10055     NamedDecl *Prev = Previous.getRepresentativeDecl();
10056     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10057                                    isMemberSpecialization ||
10058                                        isFunctionTemplateSpecialization,
10059                                    D.isFunctionDefinition());
10060   }
10061 
10062   if (getLangOpts().CUDA) {
10063     IdentifierInfo *II = NewFD->getIdentifier();
10064     if (II && II->isStr(getCudaConfigureFuncName()) &&
10065         !NewFD->isInvalidDecl() &&
10066         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10067       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10068         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10069             << getCudaConfigureFuncName();
10070       Context.setcudaConfigureCallDecl(NewFD);
10071     }
10072 
10073     // Variadic functions, other than a *declaration* of printf, are not allowed
10074     // in device-side CUDA code, unless someone passed
10075     // -fcuda-allow-variadic-functions.
10076     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10077         (NewFD->hasAttr<CUDADeviceAttr>() ||
10078          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10079         !(II && II->isStr("printf") && NewFD->isExternC() &&
10080           !D.isFunctionDefinition())) {
10081       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10082     }
10083   }
10084 
10085   MarkUnusedFileScopedDecl(NewFD);
10086 
10087 
10088 
10089   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10090     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10091     if (SC == SC_Static) {
10092       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10093       D.setInvalidType();
10094     }
10095 
10096     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10097     if (!NewFD->getReturnType()->isVoidType()) {
10098       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10099       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10100           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10101                                 : FixItHint());
10102       D.setInvalidType();
10103     }
10104 
10105     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10106     for (auto Param : NewFD->parameters())
10107       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10108 
10109     if (getLangOpts().OpenCLCPlusPlus) {
10110       if (DC->isRecord()) {
10111         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10112         D.setInvalidType();
10113       }
10114       if (FunctionTemplate) {
10115         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10116         D.setInvalidType();
10117       }
10118     }
10119   }
10120 
10121   if (getLangOpts().CPlusPlus) {
10122     if (FunctionTemplate) {
10123       if (NewFD->isInvalidDecl())
10124         FunctionTemplate->setInvalidDecl();
10125       return FunctionTemplate;
10126     }
10127 
10128     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10129       CompleteMemberSpecialization(NewFD, Previous);
10130   }
10131 
10132   for (const ParmVarDecl *Param : NewFD->parameters()) {
10133     QualType PT = Param->getType();
10134 
10135     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10136     // types.
10137     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10138       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10139         QualType ElemTy = PipeTy->getElementType();
10140           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10141             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10142             D.setInvalidType();
10143           }
10144       }
10145     }
10146   }
10147 
10148   // Here we have an function template explicit specialization at class scope.
10149   // The actual specialization will be postponed to template instatiation
10150   // time via the ClassScopeFunctionSpecializationDecl node.
10151   if (isDependentClassScopeExplicitSpecialization) {
10152     ClassScopeFunctionSpecializationDecl *NewSpec =
10153                          ClassScopeFunctionSpecializationDecl::Create(
10154                                 Context, CurContext, NewFD->getLocation(),
10155                                 cast<CXXMethodDecl>(NewFD),
10156                                 HasExplicitTemplateArgs, TemplateArgs);
10157     CurContext->addDecl(NewSpec);
10158     AddToScope = false;
10159   }
10160 
10161   // Diagnose availability attributes. Availability cannot be used on functions
10162   // that are run during load/unload.
10163   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10164     if (NewFD->hasAttr<ConstructorAttr>()) {
10165       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10166           << 1;
10167       NewFD->dropAttr<AvailabilityAttr>();
10168     }
10169     if (NewFD->hasAttr<DestructorAttr>()) {
10170       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10171           << 2;
10172       NewFD->dropAttr<AvailabilityAttr>();
10173     }
10174   }
10175 
10176   // Diagnose no_builtin attribute on function declaration that are not a
10177   // definition.
10178   // FIXME: We should really be doing this in
10179   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10180   // the FunctionDecl and at this point of the code
10181   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10182   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10183   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10184     switch (D.getFunctionDefinitionKind()) {
10185     case FunctionDefinitionKind::Defaulted:
10186     case FunctionDefinitionKind::Deleted:
10187       Diag(NBA->getLocation(),
10188            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10189           << NBA->getSpelling();
10190       break;
10191     case FunctionDefinitionKind::Declaration:
10192       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10193           << NBA->getSpelling();
10194       break;
10195     case FunctionDefinitionKind::Definition:
10196       break;
10197     }
10198 
10199   return NewFD;
10200 }
10201 
10202 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10203 /// when __declspec(code_seg) "is applied to a class, all member functions of
10204 /// the class and nested classes -- this includes compiler-generated special
10205 /// member functions -- are put in the specified segment."
10206 /// The actual behavior is a little more complicated. The Microsoft compiler
10207 /// won't check outer classes if there is an active value from #pragma code_seg.
10208 /// The CodeSeg is always applied from the direct parent but only from outer
10209 /// classes when the #pragma code_seg stack is empty. See:
10210 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10211 /// available since MS has removed the page.
10212 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10213   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10214   if (!Method)
10215     return nullptr;
10216   const CXXRecordDecl *Parent = Method->getParent();
10217   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10218     Attr *NewAttr = SAttr->clone(S.getASTContext());
10219     NewAttr->setImplicit(true);
10220     return NewAttr;
10221   }
10222 
10223   // The Microsoft compiler won't check outer classes for the CodeSeg
10224   // when the #pragma code_seg stack is active.
10225   if (S.CodeSegStack.CurrentValue)
10226    return nullptr;
10227 
10228   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10229     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10230       Attr *NewAttr = SAttr->clone(S.getASTContext());
10231       NewAttr->setImplicit(true);
10232       return NewAttr;
10233     }
10234   }
10235   return nullptr;
10236 }
10237 
10238 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10239 /// containing class. Otherwise it will return implicit SectionAttr if the
10240 /// function is a definition and there is an active value on CodeSegStack
10241 /// (from the current #pragma code-seg value).
10242 ///
10243 /// \param FD Function being declared.
10244 /// \param IsDefinition Whether it is a definition or just a declarartion.
10245 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10246 ///          nullptr if no attribute should be added.
10247 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10248                                                        bool IsDefinition) {
10249   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10250     return A;
10251   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10252       CodeSegStack.CurrentValue)
10253     return SectionAttr::CreateImplicit(
10254         getASTContext(), CodeSegStack.CurrentValue->getString(),
10255         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10256         SectionAttr::Declspec_allocate);
10257   return nullptr;
10258 }
10259 
10260 /// Determines if we can perform a correct type check for \p D as a
10261 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10262 /// best-effort check.
10263 ///
10264 /// \param NewD The new declaration.
10265 /// \param OldD The old declaration.
10266 /// \param NewT The portion of the type of the new declaration to check.
10267 /// \param OldT The portion of the type of the old declaration to check.
10268 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10269                                           QualType NewT, QualType OldT) {
10270   if (!NewD->getLexicalDeclContext()->isDependentContext())
10271     return true;
10272 
10273   // For dependently-typed local extern declarations and friends, we can't
10274   // perform a correct type check in general until instantiation:
10275   //
10276   //   int f();
10277   //   template<typename T> void g() { T f(); }
10278   //
10279   // (valid if g() is only instantiated with T = int).
10280   if (NewT->isDependentType() &&
10281       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10282     return false;
10283 
10284   // Similarly, if the previous declaration was a dependent local extern
10285   // declaration, we don't really know its type yet.
10286   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10287     return false;
10288 
10289   return true;
10290 }
10291 
10292 /// Checks if the new declaration declared in dependent context must be
10293 /// put in the same redeclaration chain as the specified declaration.
10294 ///
10295 /// \param D Declaration that is checked.
10296 /// \param PrevDecl Previous declaration found with proper lookup method for the
10297 ///                 same declaration name.
10298 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10299 ///          belongs to.
10300 ///
10301 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10302   if (!D->getLexicalDeclContext()->isDependentContext())
10303     return true;
10304 
10305   // Don't chain dependent friend function definitions until instantiation, to
10306   // permit cases like
10307   //
10308   //   void func();
10309   //   template<typename T> class C1 { friend void func() {} };
10310   //   template<typename T> class C2 { friend void func() {} };
10311   //
10312   // ... which is valid if only one of C1 and C2 is ever instantiated.
10313   //
10314   // FIXME: This need only apply to function definitions. For now, we proxy
10315   // this by checking for a file-scope function. We do not want this to apply
10316   // to friend declarations nominating member functions, because that gets in
10317   // the way of access checks.
10318   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10319     return false;
10320 
10321   auto *VD = dyn_cast<ValueDecl>(D);
10322   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10323   return !VD || !PrevVD ||
10324          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10325                                         PrevVD->getType());
10326 }
10327 
10328 /// Check the target attribute of the function for MultiVersion
10329 /// validity.
10330 ///
10331 /// Returns true if there was an error, false otherwise.
10332 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10333   const auto *TA = FD->getAttr<TargetAttr>();
10334   assert(TA && "MultiVersion Candidate requires a target attribute");
10335   ParsedTargetAttr ParseInfo = TA->parse();
10336   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10337   enum ErrType { Feature = 0, Architecture = 1 };
10338 
10339   if (!ParseInfo.Architecture.empty() &&
10340       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10341     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10342         << Architecture << ParseInfo.Architecture;
10343     return true;
10344   }
10345 
10346   for (const auto &Feat : ParseInfo.Features) {
10347     auto BareFeat = StringRef{Feat}.substr(1);
10348     if (Feat[0] == '-') {
10349       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10350           << Feature << ("no-" + BareFeat).str();
10351       return true;
10352     }
10353 
10354     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10355         !TargetInfo.isValidFeatureName(BareFeat)) {
10356       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10357           << Feature << BareFeat;
10358       return true;
10359     }
10360   }
10361   return false;
10362 }
10363 
10364 // Provide a white-list of attributes that are allowed to be combined with
10365 // multiversion functions.
10366 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10367                                            MultiVersionKind MVKind) {
10368   // Note: this list/diagnosis must match the list in
10369   // checkMultiversionAttributesAllSame.
10370   switch (Kind) {
10371   default:
10372     return false;
10373   case attr::Used:
10374     return MVKind == MultiVersionKind::Target;
10375   case attr::NonNull:
10376   case attr::NoThrow:
10377     return true;
10378   }
10379 }
10380 
10381 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10382                                                  const FunctionDecl *FD,
10383                                                  const FunctionDecl *CausedFD,
10384                                                  MultiVersionKind MVKind) {
10385   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10386     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10387         << static_cast<unsigned>(MVKind) << A;
10388     if (CausedFD)
10389       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10390     return true;
10391   };
10392 
10393   for (const Attr *A : FD->attrs()) {
10394     switch (A->getKind()) {
10395     case attr::CPUDispatch:
10396     case attr::CPUSpecific:
10397       if (MVKind != MultiVersionKind::CPUDispatch &&
10398           MVKind != MultiVersionKind::CPUSpecific)
10399         return Diagnose(S, A);
10400       break;
10401     case attr::Target:
10402       if (MVKind != MultiVersionKind::Target)
10403         return Diagnose(S, A);
10404       break;
10405     case attr::TargetClones:
10406       if (MVKind != MultiVersionKind::TargetClones)
10407         return Diagnose(S, A);
10408       break;
10409     default:
10410       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10411         return Diagnose(S, A);
10412       break;
10413     }
10414   }
10415   return false;
10416 }
10417 
10418 bool Sema::areMultiversionVariantFunctionsCompatible(
10419     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10420     const PartialDiagnostic &NoProtoDiagID,
10421     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10422     const PartialDiagnosticAt &NoSupportDiagIDAt,
10423     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10424     bool ConstexprSupported, bool CLinkageMayDiffer) {
10425   enum DoesntSupport {
10426     FuncTemplates = 0,
10427     VirtFuncs = 1,
10428     DeducedReturn = 2,
10429     Constructors = 3,
10430     Destructors = 4,
10431     DeletedFuncs = 5,
10432     DefaultedFuncs = 6,
10433     ConstexprFuncs = 7,
10434     ConstevalFuncs = 8,
10435     Lambda = 9,
10436   };
10437   enum Different {
10438     CallingConv = 0,
10439     ReturnType = 1,
10440     ConstexprSpec = 2,
10441     InlineSpec = 3,
10442     Linkage = 4,
10443     LanguageLinkage = 5,
10444   };
10445 
10446   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10447       !OldFD->getType()->getAs<FunctionProtoType>()) {
10448     Diag(OldFD->getLocation(), NoProtoDiagID);
10449     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10450     return true;
10451   }
10452 
10453   if (NoProtoDiagID.getDiagID() != 0 &&
10454       !NewFD->getType()->getAs<FunctionProtoType>())
10455     return Diag(NewFD->getLocation(), NoProtoDiagID);
10456 
10457   if (!TemplatesSupported &&
10458       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10459     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10460            << FuncTemplates;
10461 
10462   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10463     if (NewCXXFD->isVirtual())
10464       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10465              << VirtFuncs;
10466 
10467     if (isa<CXXConstructorDecl>(NewCXXFD))
10468       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10469              << Constructors;
10470 
10471     if (isa<CXXDestructorDecl>(NewCXXFD))
10472       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10473              << Destructors;
10474   }
10475 
10476   if (NewFD->isDeleted())
10477     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10478            << DeletedFuncs;
10479 
10480   if (NewFD->isDefaulted())
10481     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10482            << DefaultedFuncs;
10483 
10484   if (!ConstexprSupported && NewFD->isConstexpr())
10485     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10486            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10487 
10488   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10489   const auto *NewType = cast<FunctionType>(NewQType);
10490   QualType NewReturnType = NewType->getReturnType();
10491 
10492   if (NewReturnType->isUndeducedType())
10493     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10494            << DeducedReturn;
10495 
10496   // Ensure the return type is identical.
10497   if (OldFD) {
10498     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10499     const auto *OldType = cast<FunctionType>(OldQType);
10500     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10501     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10502 
10503     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10504       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10505 
10506     QualType OldReturnType = OldType->getReturnType();
10507 
10508     if (OldReturnType != NewReturnType)
10509       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10510 
10511     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10512       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10513 
10514     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10515       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10516 
10517     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10518       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10519 
10520     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10521       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10522 
10523     if (CheckEquivalentExceptionSpec(
10524             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10525             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10526       return true;
10527   }
10528   return false;
10529 }
10530 
10531 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10532                                              const FunctionDecl *NewFD,
10533                                              bool CausesMV,
10534                                              MultiVersionKind MVKind) {
10535   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10536     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10537     if (OldFD)
10538       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10539     return true;
10540   }
10541 
10542   bool IsCPUSpecificCPUDispatchMVKind =
10543       MVKind == MultiVersionKind::CPUDispatch ||
10544       MVKind == MultiVersionKind::CPUSpecific;
10545 
10546   if (CausesMV && OldFD &&
10547       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10548     return true;
10549 
10550   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10551     return true;
10552 
10553   // Only allow transition to MultiVersion if it hasn't been used.
10554   if (OldFD && CausesMV && OldFD->isUsed(false))
10555     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10556 
10557   return S.areMultiversionVariantFunctionsCompatible(
10558       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10559       PartialDiagnosticAt(NewFD->getLocation(),
10560                           S.PDiag(diag::note_multiversioning_caused_here)),
10561       PartialDiagnosticAt(NewFD->getLocation(),
10562                           S.PDiag(diag::err_multiversion_doesnt_support)
10563                               << static_cast<unsigned>(MVKind)),
10564       PartialDiagnosticAt(NewFD->getLocation(),
10565                           S.PDiag(diag::err_multiversion_diff)),
10566       /*TemplatesSupported=*/false,
10567       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10568       /*CLinkageMayDiffer=*/false);
10569 }
10570 
10571 /// Check the validity of a multiversion function declaration that is the
10572 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10573 ///
10574 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10575 ///
10576 /// Returns true if there was an error, false otherwise.
10577 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10578                                            MultiVersionKind MVKind,
10579                                            const TargetAttr *TA) {
10580   assert(MVKind != MultiVersionKind::None &&
10581          "Function lacks multiversion attribute");
10582 
10583   // Target only causes MV if it is default, otherwise this is a normal
10584   // function.
10585   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10586     return false;
10587 
10588   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10589     FD->setInvalidDecl();
10590     return true;
10591   }
10592 
10593   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10594     FD->setInvalidDecl();
10595     return true;
10596   }
10597 
10598   FD->setIsMultiVersion();
10599   return false;
10600 }
10601 
10602 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10603   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10604     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10605       return true;
10606   }
10607 
10608   return false;
10609 }
10610 
10611 static bool CheckTargetCausesMultiVersioning(
10612     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10613     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10614   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10615   ParsedTargetAttr NewParsed = NewTA->parse();
10616   // Sort order doesn't matter, it just needs to be consistent.
10617   llvm::sort(NewParsed.Features);
10618 
10619   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10620   // to change, this is a simple redeclaration.
10621   if (!NewTA->isDefaultVersion() &&
10622       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10623     return false;
10624 
10625   // Otherwise, this decl causes MultiVersioning.
10626   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10627                                        MultiVersionKind::Target)) {
10628     NewFD->setInvalidDecl();
10629     return true;
10630   }
10631 
10632   if (CheckMultiVersionValue(S, NewFD)) {
10633     NewFD->setInvalidDecl();
10634     return true;
10635   }
10636 
10637   // If this is 'default', permit the forward declaration.
10638   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10639     Redeclaration = true;
10640     OldDecl = OldFD;
10641     OldFD->setIsMultiVersion();
10642     NewFD->setIsMultiVersion();
10643     return false;
10644   }
10645 
10646   if (CheckMultiVersionValue(S, OldFD)) {
10647     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10648     NewFD->setInvalidDecl();
10649     return true;
10650   }
10651 
10652   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10653 
10654   if (OldParsed == NewParsed) {
10655     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10656     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10657     NewFD->setInvalidDecl();
10658     return true;
10659   }
10660 
10661   for (const auto *FD : OldFD->redecls()) {
10662     const auto *CurTA = FD->getAttr<TargetAttr>();
10663     // We allow forward declarations before ANY multiversioning attributes, but
10664     // nothing after the fact.
10665     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10666         (!CurTA || CurTA->isInherited())) {
10667       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10668           << 0;
10669       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10670       NewFD->setInvalidDecl();
10671       return true;
10672     }
10673   }
10674 
10675   OldFD->setIsMultiVersion();
10676   NewFD->setIsMultiVersion();
10677   Redeclaration = false;
10678   OldDecl = nullptr;
10679   Previous.clear();
10680   return false;
10681 }
10682 
10683 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10684                                         MultiVersionKind New) {
10685   if (Old == New || Old == MultiVersionKind::None ||
10686       New == MultiVersionKind::None)
10687     return true;
10688 
10689   return (Old == MultiVersionKind::CPUDispatch &&
10690           New == MultiVersionKind::CPUSpecific) ||
10691          (Old == MultiVersionKind::CPUSpecific &&
10692           New == MultiVersionKind::CPUDispatch);
10693 }
10694 
10695 /// Check the validity of a new function declaration being added to an existing
10696 /// multiversioned declaration collection.
10697 static bool CheckMultiVersionAdditionalDecl(
10698     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10699     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10700     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10701     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10702     LookupResult &Previous) {
10703 
10704   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10705   // Disallow mixing of multiversioning types.
10706   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10707     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10708     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10709     NewFD->setInvalidDecl();
10710     return true;
10711   }
10712 
10713   ParsedTargetAttr NewParsed;
10714   if (NewTA) {
10715     NewParsed = NewTA->parse();
10716     llvm::sort(NewParsed.Features);
10717   }
10718 
10719   bool UseMemberUsingDeclRules =
10720       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10721 
10722   bool MayNeedOverloadableChecks =
10723       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10724 
10725   // Next, check ALL non-overloads to see if this is a redeclaration of a
10726   // previous member of the MultiVersion set.
10727   for (NamedDecl *ND : Previous) {
10728     FunctionDecl *CurFD = ND->getAsFunction();
10729     if (!CurFD)
10730       continue;
10731     if (MayNeedOverloadableChecks &&
10732         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10733       continue;
10734 
10735     switch (NewMVKind) {
10736     case MultiVersionKind::None:
10737       assert(OldMVKind == MultiVersionKind::TargetClones &&
10738              "Only target_clones can be omitted in subsequent declarations");
10739       break;
10740     case MultiVersionKind::Target: {
10741       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10742       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10743         NewFD->setIsMultiVersion();
10744         Redeclaration = true;
10745         OldDecl = ND;
10746         return false;
10747       }
10748 
10749       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10750       if (CurParsed == NewParsed) {
10751         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10752         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10753         NewFD->setInvalidDecl();
10754         return true;
10755       }
10756       break;
10757     }
10758     case MultiVersionKind::TargetClones: {
10759       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10760       Redeclaration = true;
10761       OldDecl = CurFD;
10762       NewFD->setIsMultiVersion();
10763 
10764       if (CurClones && NewClones &&
10765           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10766            !std::equal(CurClones->featuresStrs_begin(),
10767                        CurClones->featuresStrs_end(),
10768                        NewClones->featuresStrs_begin()))) {
10769         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10770         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10771         NewFD->setInvalidDecl();
10772         return true;
10773       }
10774 
10775       return false;
10776     }
10777     case MultiVersionKind::CPUSpecific:
10778     case MultiVersionKind::CPUDispatch: {
10779       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10780       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10781       // Handle CPUDispatch/CPUSpecific versions.
10782       // Only 1 CPUDispatch function is allowed, this will make it go through
10783       // the redeclaration errors.
10784       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10785           CurFD->hasAttr<CPUDispatchAttr>()) {
10786         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10787             std::equal(
10788                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10789                 NewCPUDisp->cpus_begin(),
10790                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10791                   return Cur->getName() == New->getName();
10792                 })) {
10793           NewFD->setIsMultiVersion();
10794           Redeclaration = true;
10795           OldDecl = ND;
10796           return false;
10797         }
10798 
10799         // If the declarations don't match, this is an error condition.
10800         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10801         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10802         NewFD->setInvalidDecl();
10803         return true;
10804       }
10805       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10806         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10807             std::equal(
10808                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10809                 NewCPUSpec->cpus_begin(),
10810                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10811                   return Cur->getName() == New->getName();
10812                 })) {
10813           NewFD->setIsMultiVersion();
10814           Redeclaration = true;
10815           OldDecl = ND;
10816           return false;
10817         }
10818 
10819         // Only 1 version of CPUSpecific is allowed for each CPU.
10820         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10821           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10822             if (CurII == NewII) {
10823               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10824                   << NewII;
10825               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10826               NewFD->setInvalidDecl();
10827               return true;
10828             }
10829           }
10830         }
10831       }
10832       break;
10833     }
10834     }
10835   }
10836 
10837   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10838   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10839   // handled in the attribute adding step.
10840   if (NewMVKind == MultiVersionKind::Target &&
10841       CheckMultiVersionValue(S, NewFD)) {
10842     NewFD->setInvalidDecl();
10843     return true;
10844   }
10845 
10846   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10847                                        !OldFD->isMultiVersion(), NewMVKind)) {
10848     NewFD->setInvalidDecl();
10849     return true;
10850   }
10851 
10852   // Permit forward declarations in the case where these two are compatible.
10853   if (!OldFD->isMultiVersion()) {
10854     OldFD->setIsMultiVersion();
10855     NewFD->setIsMultiVersion();
10856     Redeclaration = true;
10857     OldDecl = OldFD;
10858     return false;
10859   }
10860 
10861   NewFD->setIsMultiVersion();
10862   Redeclaration = false;
10863   OldDecl = nullptr;
10864   Previous.clear();
10865   return false;
10866 }
10867 
10868 /// Check the validity of a mulitversion function declaration.
10869 /// Also sets the multiversion'ness' of the function itself.
10870 ///
10871 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10872 ///
10873 /// Returns true if there was an error, false otherwise.
10874 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10875                                       bool &Redeclaration, NamedDecl *&OldDecl,
10876                                       LookupResult &Previous) {
10877   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10878   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10879   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10880   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10881   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
10882 
10883   // Main isn't allowed to become a multiversion function, however it IS
10884   // permitted to have 'main' be marked with the 'target' optimization hint.
10885   if (NewFD->isMain()) {
10886     if (MVKind != MultiVersionKind::None &&
10887         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10888       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10889       NewFD->setInvalidDecl();
10890       return true;
10891     }
10892     return false;
10893   }
10894 
10895   if (!OldDecl || !OldDecl->getAsFunction() ||
10896       OldDecl->getDeclContext()->getRedeclContext() !=
10897           NewFD->getDeclContext()->getRedeclContext()) {
10898     // If there's no previous declaration, AND this isn't attempting to cause
10899     // multiversioning, this isn't an error condition.
10900     if (MVKind == MultiVersionKind::None)
10901       return false;
10902     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
10903   }
10904 
10905   FunctionDecl *OldFD = OldDecl->getAsFunction();
10906 
10907   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
10908     return false;
10909 
10910   // Multiversioned redeclarations aren't allowed to omit the attribute, except
10911   // for target_clones.
10912   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
10913       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
10914     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10915         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10916     NewFD->setInvalidDecl();
10917     return true;
10918   }
10919 
10920   if (!OldFD->isMultiVersion()) {
10921     switch (MVKind) {
10922     case MultiVersionKind::Target:
10923       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10924                                               Redeclaration, OldDecl, Previous);
10925     case MultiVersionKind::TargetClones:
10926       if (OldFD->isUsed(false)) {
10927         NewFD->setInvalidDecl();
10928         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10929       }
10930       OldFD->setIsMultiVersion();
10931       break;
10932     case MultiVersionKind::CPUDispatch:
10933     case MultiVersionKind::CPUSpecific:
10934     case MultiVersionKind::None:
10935       break;
10936     }
10937   }
10938 
10939   // At this point, we have a multiversion function decl (in OldFD) AND an
10940   // appropriate attribute in the current function decl.  Resolve that these are
10941   // still compatible with previous declarations.
10942   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
10943                                          NewCPUDisp, NewCPUSpec, NewClones,
10944                                          Redeclaration, OldDecl, Previous);
10945 }
10946 
10947 /// Perform semantic checking of a new function declaration.
10948 ///
10949 /// Performs semantic analysis of the new function declaration
10950 /// NewFD. This routine performs all semantic checking that does not
10951 /// require the actual declarator involved in the declaration, and is
10952 /// used both for the declaration of functions as they are parsed
10953 /// (called via ActOnDeclarator) and for the declaration of functions
10954 /// that have been instantiated via C++ template instantiation (called
10955 /// via InstantiateDecl).
10956 ///
10957 /// \param IsMemberSpecialization whether this new function declaration is
10958 /// a member specialization (that replaces any definition provided by the
10959 /// previous declaration).
10960 ///
10961 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10962 ///
10963 /// \returns true if the function declaration is a redeclaration.
10964 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10965                                     LookupResult &Previous,
10966                                     bool IsMemberSpecialization) {
10967   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10968          "Variably modified return types are not handled here");
10969 
10970   // Determine whether the type of this function should be merged with
10971   // a previous visible declaration. This never happens for functions in C++,
10972   // and always happens in C if the previous declaration was visible.
10973   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10974                                !Previous.isShadowed();
10975 
10976   bool Redeclaration = false;
10977   NamedDecl *OldDecl = nullptr;
10978   bool MayNeedOverloadableChecks = false;
10979 
10980   // Merge or overload the declaration with an existing declaration of
10981   // the same name, if appropriate.
10982   if (!Previous.empty()) {
10983     // Determine whether NewFD is an overload of PrevDecl or
10984     // a declaration that requires merging. If it's an overload,
10985     // there's no more work to do here; we'll just add the new
10986     // function to the scope.
10987     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10988       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10989       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10990         Redeclaration = true;
10991         OldDecl = Candidate;
10992       }
10993     } else {
10994       MayNeedOverloadableChecks = true;
10995       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10996                             /*NewIsUsingDecl*/ false)) {
10997       case Ovl_Match:
10998         Redeclaration = true;
10999         break;
11000 
11001       case Ovl_NonFunction:
11002         Redeclaration = true;
11003         break;
11004 
11005       case Ovl_Overload:
11006         Redeclaration = false;
11007         break;
11008       }
11009     }
11010   }
11011 
11012   // Check for a previous extern "C" declaration with this name.
11013   if (!Redeclaration &&
11014       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11015     if (!Previous.empty()) {
11016       // This is an extern "C" declaration with the same name as a previous
11017       // declaration, and thus redeclares that entity...
11018       Redeclaration = true;
11019       OldDecl = Previous.getFoundDecl();
11020       MergeTypeWithPrevious = false;
11021 
11022       // ... except in the presence of __attribute__((overloadable)).
11023       if (OldDecl->hasAttr<OverloadableAttr>() ||
11024           NewFD->hasAttr<OverloadableAttr>()) {
11025         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11026           MayNeedOverloadableChecks = true;
11027           Redeclaration = false;
11028           OldDecl = nullptr;
11029         }
11030       }
11031     }
11032   }
11033 
11034   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11035     return Redeclaration;
11036 
11037   // PPC MMA non-pointer types are not allowed as function return types.
11038   if (Context.getTargetInfo().getTriple().isPPC64() &&
11039       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11040     NewFD->setInvalidDecl();
11041   }
11042 
11043   // C++11 [dcl.constexpr]p8:
11044   //   A constexpr specifier for a non-static member function that is not
11045   //   a constructor declares that member function to be const.
11046   //
11047   // This needs to be delayed until we know whether this is an out-of-line
11048   // definition of a static member function.
11049   //
11050   // This rule is not present in C++1y, so we produce a backwards
11051   // compatibility warning whenever it happens in C++11.
11052   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11053   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11054       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11055       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11056     CXXMethodDecl *OldMD = nullptr;
11057     if (OldDecl)
11058       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11059     if (!OldMD || !OldMD->isStatic()) {
11060       const FunctionProtoType *FPT =
11061         MD->getType()->castAs<FunctionProtoType>();
11062       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11063       EPI.TypeQuals.addConst();
11064       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11065                                           FPT->getParamTypes(), EPI));
11066 
11067       // Warn that we did this, if we're not performing template instantiation.
11068       // In that case, we'll have warned already when the template was defined.
11069       if (!inTemplateInstantiation()) {
11070         SourceLocation AddConstLoc;
11071         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11072                 .IgnoreParens().getAs<FunctionTypeLoc>())
11073           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11074 
11075         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11076           << FixItHint::CreateInsertion(AddConstLoc, " const");
11077       }
11078     }
11079   }
11080 
11081   if (Redeclaration) {
11082     // NewFD and OldDecl represent declarations that need to be
11083     // merged.
11084     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11085       NewFD->setInvalidDecl();
11086       return Redeclaration;
11087     }
11088 
11089     Previous.clear();
11090     Previous.addDecl(OldDecl);
11091 
11092     if (FunctionTemplateDecl *OldTemplateDecl =
11093             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11094       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11095       FunctionTemplateDecl *NewTemplateDecl
11096         = NewFD->getDescribedFunctionTemplate();
11097       assert(NewTemplateDecl && "Template/non-template mismatch");
11098 
11099       // The call to MergeFunctionDecl above may have created some state in
11100       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11101       // can add it as a redeclaration.
11102       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11103 
11104       NewFD->setPreviousDeclaration(OldFD);
11105       if (NewFD->isCXXClassMember()) {
11106         NewFD->setAccess(OldTemplateDecl->getAccess());
11107         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11108       }
11109 
11110       // If this is an explicit specialization of a member that is a function
11111       // template, mark it as a member specialization.
11112       if (IsMemberSpecialization &&
11113           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11114         NewTemplateDecl->setMemberSpecialization();
11115         assert(OldTemplateDecl->isMemberSpecialization());
11116         // Explicit specializations of a member template do not inherit deleted
11117         // status from the parent member template that they are specializing.
11118         if (OldFD->isDeleted()) {
11119           // FIXME: This assert will not hold in the presence of modules.
11120           assert(OldFD->getCanonicalDecl() == OldFD);
11121           // FIXME: We need an update record for this AST mutation.
11122           OldFD->setDeletedAsWritten(false);
11123         }
11124       }
11125 
11126     } else {
11127       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11128         auto *OldFD = cast<FunctionDecl>(OldDecl);
11129         // This needs to happen first so that 'inline' propagates.
11130         NewFD->setPreviousDeclaration(OldFD);
11131         if (NewFD->isCXXClassMember())
11132           NewFD->setAccess(OldFD->getAccess());
11133       }
11134     }
11135   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11136              !NewFD->getAttr<OverloadableAttr>()) {
11137     assert((Previous.empty() ||
11138             llvm::any_of(Previous,
11139                          [](const NamedDecl *ND) {
11140                            return ND->hasAttr<OverloadableAttr>();
11141                          })) &&
11142            "Non-redecls shouldn't happen without overloadable present");
11143 
11144     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11145       const auto *FD = dyn_cast<FunctionDecl>(ND);
11146       return FD && !FD->hasAttr<OverloadableAttr>();
11147     });
11148 
11149     if (OtherUnmarkedIter != Previous.end()) {
11150       Diag(NewFD->getLocation(),
11151            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11152       Diag((*OtherUnmarkedIter)->getLocation(),
11153            diag::note_attribute_overloadable_prev_overload)
11154           << false;
11155 
11156       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11157     }
11158   }
11159 
11160   if (LangOpts.OpenMP)
11161     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11162 
11163   // Semantic checking for this function declaration (in isolation).
11164 
11165   if (getLangOpts().CPlusPlus) {
11166     // C++-specific checks.
11167     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11168       CheckConstructor(Constructor);
11169     } else if (CXXDestructorDecl *Destructor =
11170                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11171       CXXRecordDecl *Record = Destructor->getParent();
11172       QualType ClassType = Context.getTypeDeclType(Record);
11173 
11174       // FIXME: Shouldn't we be able to perform this check even when the class
11175       // type is dependent? Both gcc and edg can handle that.
11176       if (!ClassType->isDependentType()) {
11177         DeclarationName Name
11178           = Context.DeclarationNames.getCXXDestructorName(
11179                                         Context.getCanonicalType(ClassType));
11180         if (NewFD->getDeclName() != Name) {
11181           Diag(NewFD->getLocation(), diag::err_destructor_name);
11182           NewFD->setInvalidDecl();
11183           return Redeclaration;
11184         }
11185       }
11186     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11187       if (auto *TD = Guide->getDescribedFunctionTemplate())
11188         CheckDeductionGuideTemplate(TD);
11189 
11190       // A deduction guide is not on the list of entities that can be
11191       // explicitly specialized.
11192       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11193         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11194             << /*explicit specialization*/ 1;
11195     }
11196 
11197     // Find any virtual functions that this function overrides.
11198     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11199       if (!Method->isFunctionTemplateSpecialization() &&
11200           !Method->getDescribedFunctionTemplate() &&
11201           Method->isCanonicalDecl()) {
11202         AddOverriddenMethods(Method->getParent(), Method);
11203       }
11204       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11205         // C++2a [class.virtual]p6
11206         // A virtual method shall not have a requires-clause.
11207         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11208              diag::err_constrained_virtual_method);
11209 
11210       if (Method->isStatic())
11211         checkThisInStaticMemberFunctionType(Method);
11212     }
11213 
11214     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11215       ActOnConversionDeclarator(Conversion);
11216 
11217     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11218     if (NewFD->isOverloadedOperator() &&
11219         CheckOverloadedOperatorDeclaration(NewFD)) {
11220       NewFD->setInvalidDecl();
11221       return Redeclaration;
11222     }
11223 
11224     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11225     if (NewFD->getLiteralIdentifier() &&
11226         CheckLiteralOperatorDeclaration(NewFD)) {
11227       NewFD->setInvalidDecl();
11228       return Redeclaration;
11229     }
11230 
11231     // In C++, check default arguments now that we have merged decls. Unless
11232     // the lexical context is the class, because in this case this is done
11233     // during delayed parsing anyway.
11234     if (!CurContext->isRecord())
11235       CheckCXXDefaultArguments(NewFD);
11236 
11237     // If this function is declared as being extern "C", then check to see if
11238     // the function returns a UDT (class, struct, or union type) that is not C
11239     // compatible, and if it does, warn the user.
11240     // But, issue any diagnostic on the first declaration only.
11241     if (Previous.empty() && NewFD->isExternC()) {
11242       QualType R = NewFD->getReturnType();
11243       if (R->isIncompleteType() && !R->isVoidType())
11244         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11245             << NewFD << R;
11246       else if (!R.isPODType(Context) && !R->isVoidType() &&
11247                !R->isObjCObjectPointerType())
11248         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11249     }
11250 
11251     // C++1z [dcl.fct]p6:
11252     //   [...] whether the function has a non-throwing exception-specification
11253     //   [is] part of the function type
11254     //
11255     // This results in an ABI break between C++14 and C++17 for functions whose
11256     // declared type includes an exception-specification in a parameter or
11257     // return type. (Exception specifications on the function itself are OK in
11258     // most cases, and exception specifications are not permitted in most other
11259     // contexts where they could make it into a mangling.)
11260     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11261       auto HasNoexcept = [&](QualType T) -> bool {
11262         // Strip off declarator chunks that could be between us and a function
11263         // type. We don't need to look far, exception specifications are very
11264         // restricted prior to C++17.
11265         if (auto *RT = T->getAs<ReferenceType>())
11266           T = RT->getPointeeType();
11267         else if (T->isAnyPointerType())
11268           T = T->getPointeeType();
11269         else if (auto *MPT = T->getAs<MemberPointerType>())
11270           T = MPT->getPointeeType();
11271         if (auto *FPT = T->getAs<FunctionProtoType>())
11272           if (FPT->isNothrow())
11273             return true;
11274         return false;
11275       };
11276 
11277       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11278       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11279       for (QualType T : FPT->param_types())
11280         AnyNoexcept |= HasNoexcept(T);
11281       if (AnyNoexcept)
11282         Diag(NewFD->getLocation(),
11283              diag::warn_cxx17_compat_exception_spec_in_signature)
11284             << NewFD;
11285     }
11286 
11287     if (!Redeclaration && LangOpts.CUDA)
11288       checkCUDATargetOverload(NewFD, Previous);
11289   }
11290   return Redeclaration;
11291 }
11292 
11293 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11294   // C++11 [basic.start.main]p3:
11295   //   A program that [...] declares main to be inline, static or
11296   //   constexpr is ill-formed.
11297   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11298   //   appear in a declaration of main.
11299   // static main is not an error under C99, but we should warn about it.
11300   // We accept _Noreturn main as an extension.
11301   if (FD->getStorageClass() == SC_Static)
11302     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11303          ? diag::err_static_main : diag::warn_static_main)
11304       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11305   if (FD->isInlineSpecified())
11306     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11307       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11308   if (DS.isNoreturnSpecified()) {
11309     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11310     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11311     Diag(NoreturnLoc, diag::ext_noreturn_main);
11312     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11313       << FixItHint::CreateRemoval(NoreturnRange);
11314   }
11315   if (FD->isConstexpr()) {
11316     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11317         << FD->isConsteval()
11318         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11319     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11320   }
11321 
11322   if (getLangOpts().OpenCL) {
11323     Diag(FD->getLocation(), diag::err_opencl_no_main)
11324         << FD->hasAttr<OpenCLKernelAttr>();
11325     FD->setInvalidDecl();
11326     return;
11327   }
11328 
11329   // Functions named main in hlsl are default entries, but don't have specific
11330   // signatures they are required to conform to.
11331   if (getLangOpts().HLSL)
11332     return;
11333 
11334   QualType T = FD->getType();
11335   assert(T->isFunctionType() && "function decl is not of function type");
11336   const FunctionType* FT = T->castAs<FunctionType>();
11337 
11338   // Set default calling convention for main()
11339   if (FT->getCallConv() != CC_C) {
11340     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11341     FD->setType(QualType(FT, 0));
11342     T = Context.getCanonicalType(FD->getType());
11343   }
11344 
11345   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11346     // In C with GNU extensions we allow main() to have non-integer return
11347     // type, but we should warn about the extension, and we disable the
11348     // implicit-return-zero rule.
11349 
11350     // GCC in C mode accepts qualified 'int'.
11351     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11352       FD->setHasImplicitReturnZero(true);
11353     else {
11354       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11355       SourceRange RTRange = FD->getReturnTypeSourceRange();
11356       if (RTRange.isValid())
11357         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11358             << FixItHint::CreateReplacement(RTRange, "int");
11359     }
11360   } else {
11361     // In C and C++, main magically returns 0 if you fall off the end;
11362     // set the flag which tells us that.
11363     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11364 
11365     // All the standards say that main() should return 'int'.
11366     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11367       FD->setHasImplicitReturnZero(true);
11368     else {
11369       // Otherwise, this is just a flat-out error.
11370       SourceRange RTRange = FD->getReturnTypeSourceRange();
11371       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11372           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11373                                 : FixItHint());
11374       FD->setInvalidDecl(true);
11375     }
11376   }
11377 
11378   // Treat protoless main() as nullary.
11379   if (isa<FunctionNoProtoType>(FT)) return;
11380 
11381   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11382   unsigned nparams = FTP->getNumParams();
11383   assert(FD->getNumParams() == nparams);
11384 
11385   bool HasExtraParameters = (nparams > 3);
11386 
11387   if (FTP->isVariadic()) {
11388     Diag(FD->getLocation(), diag::ext_variadic_main);
11389     // FIXME: if we had information about the location of the ellipsis, we
11390     // could add a FixIt hint to remove it as a parameter.
11391   }
11392 
11393   // Darwin passes an undocumented fourth argument of type char**.  If
11394   // other platforms start sprouting these, the logic below will start
11395   // getting shifty.
11396   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11397     HasExtraParameters = false;
11398 
11399   if (HasExtraParameters) {
11400     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11401     FD->setInvalidDecl(true);
11402     nparams = 3;
11403   }
11404 
11405   // FIXME: a lot of the following diagnostics would be improved
11406   // if we had some location information about types.
11407 
11408   QualType CharPP =
11409     Context.getPointerType(Context.getPointerType(Context.CharTy));
11410   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11411 
11412   for (unsigned i = 0; i < nparams; ++i) {
11413     QualType AT = FTP->getParamType(i);
11414 
11415     bool mismatch = true;
11416 
11417     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11418       mismatch = false;
11419     else if (Expected[i] == CharPP) {
11420       // As an extension, the following forms are okay:
11421       //   char const **
11422       //   char const * const *
11423       //   char * const *
11424 
11425       QualifierCollector qs;
11426       const PointerType* PT;
11427       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11428           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11429           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11430                               Context.CharTy)) {
11431         qs.removeConst();
11432         mismatch = !qs.empty();
11433       }
11434     }
11435 
11436     if (mismatch) {
11437       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11438       // TODO: suggest replacing given type with expected type
11439       FD->setInvalidDecl(true);
11440     }
11441   }
11442 
11443   if (nparams == 1 && !FD->isInvalidDecl()) {
11444     Diag(FD->getLocation(), diag::warn_main_one_arg);
11445   }
11446 
11447   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11448     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11449     FD->setInvalidDecl();
11450   }
11451 }
11452 
11453 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11454 
11455   // Default calling convention for main and wmain is __cdecl
11456   if (FD->getName() == "main" || FD->getName() == "wmain")
11457     return false;
11458 
11459   // Default calling convention for MinGW is __cdecl
11460   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11461   if (T.isWindowsGNUEnvironment())
11462     return false;
11463 
11464   // Default calling convention for WinMain, wWinMain and DllMain
11465   // is __stdcall on 32 bit Windows
11466   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11467     return true;
11468 
11469   return false;
11470 }
11471 
11472 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11473   QualType T = FD->getType();
11474   assert(T->isFunctionType() && "function decl is not of function type");
11475   const FunctionType *FT = T->castAs<FunctionType>();
11476 
11477   // Set an implicit return of 'zero' if the function can return some integral,
11478   // enumeration, pointer or nullptr type.
11479   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11480       FT->getReturnType()->isAnyPointerType() ||
11481       FT->getReturnType()->isNullPtrType())
11482     // DllMain is exempt because a return value of zero means it failed.
11483     if (FD->getName() != "DllMain")
11484       FD->setHasImplicitReturnZero(true);
11485 
11486   // Explicity specified calling conventions are applied to MSVC entry points
11487   if (!hasExplicitCallingConv(T)) {
11488     if (isDefaultStdCall(FD, *this)) {
11489       if (FT->getCallConv() != CC_X86StdCall) {
11490         FT = Context.adjustFunctionType(
11491             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11492         FD->setType(QualType(FT, 0));
11493       }
11494     } else if (FT->getCallConv() != CC_C) {
11495       FT = Context.adjustFunctionType(FT,
11496                                       FT->getExtInfo().withCallingConv(CC_C));
11497       FD->setType(QualType(FT, 0));
11498     }
11499   }
11500 
11501   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11502     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11503     FD->setInvalidDecl();
11504   }
11505 }
11506 
11507 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11508   // FIXME: Need strict checking.  In C89, we need to check for
11509   // any assignment, increment, decrement, function-calls, or
11510   // commas outside of a sizeof.  In C99, it's the same list,
11511   // except that the aforementioned are allowed in unevaluated
11512   // expressions.  Everything else falls under the
11513   // "may accept other forms of constant expressions" exception.
11514   //
11515   // Regular C++ code will not end up here (exceptions: language extensions,
11516   // OpenCL C++ etc), so the constant expression rules there don't matter.
11517   if (Init->isValueDependent()) {
11518     assert(Init->containsErrors() &&
11519            "Dependent code should only occur in error-recovery path.");
11520     return true;
11521   }
11522   const Expr *Culprit;
11523   if (Init->isConstantInitializer(Context, false, &Culprit))
11524     return false;
11525   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11526     << Culprit->getSourceRange();
11527   return true;
11528 }
11529 
11530 namespace {
11531   // Visits an initialization expression to see if OrigDecl is evaluated in
11532   // its own initialization and throws a warning if it does.
11533   class SelfReferenceChecker
11534       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11535     Sema &S;
11536     Decl *OrigDecl;
11537     bool isRecordType;
11538     bool isPODType;
11539     bool isReferenceType;
11540 
11541     bool isInitList;
11542     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11543 
11544   public:
11545     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11546 
11547     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11548                                                     S(S), OrigDecl(OrigDecl) {
11549       isPODType = false;
11550       isRecordType = false;
11551       isReferenceType = false;
11552       isInitList = false;
11553       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11554         isPODType = VD->getType().isPODType(S.Context);
11555         isRecordType = VD->getType()->isRecordType();
11556         isReferenceType = VD->getType()->isReferenceType();
11557       }
11558     }
11559 
11560     // For most expressions, just call the visitor.  For initializer lists,
11561     // track the index of the field being initialized since fields are
11562     // initialized in order allowing use of previously initialized fields.
11563     void CheckExpr(Expr *E) {
11564       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11565       if (!InitList) {
11566         Visit(E);
11567         return;
11568       }
11569 
11570       // Track and increment the index here.
11571       isInitList = true;
11572       InitFieldIndex.push_back(0);
11573       for (auto Child : InitList->children()) {
11574         CheckExpr(cast<Expr>(Child));
11575         ++InitFieldIndex.back();
11576       }
11577       InitFieldIndex.pop_back();
11578     }
11579 
11580     // Returns true if MemberExpr is checked and no further checking is needed.
11581     // Returns false if additional checking is required.
11582     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11583       llvm::SmallVector<FieldDecl*, 4> Fields;
11584       Expr *Base = E;
11585       bool ReferenceField = false;
11586 
11587       // Get the field members used.
11588       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11589         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11590         if (!FD)
11591           return false;
11592         Fields.push_back(FD);
11593         if (FD->getType()->isReferenceType())
11594           ReferenceField = true;
11595         Base = ME->getBase()->IgnoreParenImpCasts();
11596       }
11597 
11598       // Keep checking only if the base Decl is the same.
11599       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11600       if (!DRE || DRE->getDecl() != OrigDecl)
11601         return false;
11602 
11603       // A reference field can be bound to an unininitialized field.
11604       if (CheckReference && !ReferenceField)
11605         return true;
11606 
11607       // Convert FieldDecls to their index number.
11608       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11609       for (const FieldDecl *I : llvm::reverse(Fields))
11610         UsedFieldIndex.push_back(I->getFieldIndex());
11611 
11612       // See if a warning is needed by checking the first difference in index
11613       // numbers.  If field being used has index less than the field being
11614       // initialized, then the use is safe.
11615       for (auto UsedIter = UsedFieldIndex.begin(),
11616                 UsedEnd = UsedFieldIndex.end(),
11617                 OrigIter = InitFieldIndex.begin(),
11618                 OrigEnd = InitFieldIndex.end();
11619            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11620         if (*UsedIter < *OrigIter)
11621           return true;
11622         if (*UsedIter > *OrigIter)
11623           break;
11624       }
11625 
11626       // TODO: Add a different warning which will print the field names.
11627       HandleDeclRefExpr(DRE);
11628       return true;
11629     }
11630 
11631     // For most expressions, the cast is directly above the DeclRefExpr.
11632     // For conditional operators, the cast can be outside the conditional
11633     // operator if both expressions are DeclRefExpr's.
11634     void HandleValue(Expr *E) {
11635       E = E->IgnoreParens();
11636       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11637         HandleDeclRefExpr(DRE);
11638         return;
11639       }
11640 
11641       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11642         Visit(CO->getCond());
11643         HandleValue(CO->getTrueExpr());
11644         HandleValue(CO->getFalseExpr());
11645         return;
11646       }
11647 
11648       if (BinaryConditionalOperator *BCO =
11649               dyn_cast<BinaryConditionalOperator>(E)) {
11650         Visit(BCO->getCond());
11651         HandleValue(BCO->getFalseExpr());
11652         return;
11653       }
11654 
11655       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11656         HandleValue(OVE->getSourceExpr());
11657         return;
11658       }
11659 
11660       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11661         if (BO->getOpcode() == BO_Comma) {
11662           Visit(BO->getLHS());
11663           HandleValue(BO->getRHS());
11664           return;
11665         }
11666       }
11667 
11668       if (isa<MemberExpr>(E)) {
11669         if (isInitList) {
11670           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11671                                       false /*CheckReference*/))
11672             return;
11673         }
11674 
11675         Expr *Base = E->IgnoreParenImpCasts();
11676         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11677           // Check for static member variables and don't warn on them.
11678           if (!isa<FieldDecl>(ME->getMemberDecl()))
11679             return;
11680           Base = ME->getBase()->IgnoreParenImpCasts();
11681         }
11682         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11683           HandleDeclRefExpr(DRE);
11684         return;
11685       }
11686 
11687       Visit(E);
11688     }
11689 
11690     // Reference types not handled in HandleValue are handled here since all
11691     // uses of references are bad, not just r-value uses.
11692     void VisitDeclRefExpr(DeclRefExpr *E) {
11693       if (isReferenceType)
11694         HandleDeclRefExpr(E);
11695     }
11696 
11697     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11698       if (E->getCastKind() == CK_LValueToRValue) {
11699         HandleValue(E->getSubExpr());
11700         return;
11701       }
11702 
11703       Inherited::VisitImplicitCastExpr(E);
11704     }
11705 
11706     void VisitMemberExpr(MemberExpr *E) {
11707       if (isInitList) {
11708         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11709           return;
11710       }
11711 
11712       // Don't warn on arrays since they can be treated as pointers.
11713       if (E->getType()->canDecayToPointerType()) return;
11714 
11715       // Warn when a non-static method call is followed by non-static member
11716       // field accesses, which is followed by a DeclRefExpr.
11717       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11718       bool Warn = (MD && !MD->isStatic());
11719       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11720       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11721         if (!isa<FieldDecl>(ME->getMemberDecl()))
11722           Warn = false;
11723         Base = ME->getBase()->IgnoreParenImpCasts();
11724       }
11725 
11726       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11727         if (Warn)
11728           HandleDeclRefExpr(DRE);
11729         return;
11730       }
11731 
11732       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11733       // Visit that expression.
11734       Visit(Base);
11735     }
11736 
11737     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11738       Expr *Callee = E->getCallee();
11739 
11740       if (isa<UnresolvedLookupExpr>(Callee))
11741         return Inherited::VisitCXXOperatorCallExpr(E);
11742 
11743       Visit(Callee);
11744       for (auto Arg: E->arguments())
11745         HandleValue(Arg->IgnoreParenImpCasts());
11746     }
11747 
11748     void VisitUnaryOperator(UnaryOperator *E) {
11749       // For POD record types, addresses of its own members are well-defined.
11750       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11751           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11752         if (!isPODType)
11753           HandleValue(E->getSubExpr());
11754         return;
11755       }
11756 
11757       if (E->isIncrementDecrementOp()) {
11758         HandleValue(E->getSubExpr());
11759         return;
11760       }
11761 
11762       Inherited::VisitUnaryOperator(E);
11763     }
11764 
11765     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11766 
11767     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11768       if (E->getConstructor()->isCopyConstructor()) {
11769         Expr *ArgExpr = E->getArg(0);
11770         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11771           if (ILE->getNumInits() == 1)
11772             ArgExpr = ILE->getInit(0);
11773         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11774           if (ICE->getCastKind() == CK_NoOp)
11775             ArgExpr = ICE->getSubExpr();
11776         HandleValue(ArgExpr);
11777         return;
11778       }
11779       Inherited::VisitCXXConstructExpr(E);
11780     }
11781 
11782     void VisitCallExpr(CallExpr *E) {
11783       // Treat std::move as a use.
11784       if (E->isCallToStdMove()) {
11785         HandleValue(E->getArg(0));
11786         return;
11787       }
11788 
11789       Inherited::VisitCallExpr(E);
11790     }
11791 
11792     void VisitBinaryOperator(BinaryOperator *E) {
11793       if (E->isCompoundAssignmentOp()) {
11794         HandleValue(E->getLHS());
11795         Visit(E->getRHS());
11796         return;
11797       }
11798 
11799       Inherited::VisitBinaryOperator(E);
11800     }
11801 
11802     // A custom visitor for BinaryConditionalOperator is needed because the
11803     // regular visitor would check the condition and true expression separately
11804     // but both point to the same place giving duplicate diagnostics.
11805     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11806       Visit(E->getCond());
11807       Visit(E->getFalseExpr());
11808     }
11809 
11810     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11811       Decl* ReferenceDecl = DRE->getDecl();
11812       if (OrigDecl != ReferenceDecl) return;
11813       unsigned diag;
11814       if (isReferenceType) {
11815         diag = diag::warn_uninit_self_reference_in_reference_init;
11816       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11817         diag = diag::warn_static_self_reference_in_init;
11818       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11819                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11820                  DRE->getDecl()->getType()->isRecordType()) {
11821         diag = diag::warn_uninit_self_reference_in_init;
11822       } else {
11823         // Local variables will be handled by the CFG analysis.
11824         return;
11825       }
11826 
11827       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11828                             S.PDiag(diag)
11829                                 << DRE->getDecl() << OrigDecl->getLocation()
11830                                 << DRE->getSourceRange());
11831     }
11832   };
11833 
11834   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11835   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11836                                  bool DirectInit) {
11837     // Parameters arguments are occassionially constructed with itself,
11838     // for instance, in recursive functions.  Skip them.
11839     if (isa<ParmVarDecl>(OrigDecl))
11840       return;
11841 
11842     E = E->IgnoreParens();
11843 
11844     // Skip checking T a = a where T is not a record or reference type.
11845     // Doing so is a way to silence uninitialized warnings.
11846     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11847       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11848         if (ICE->getCastKind() == CK_LValueToRValue)
11849           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11850             if (DRE->getDecl() == OrigDecl)
11851               return;
11852 
11853     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11854   }
11855 } // end anonymous namespace
11856 
11857 namespace {
11858   // Simple wrapper to add the name of a variable or (if no variable is
11859   // available) a DeclarationName into a diagnostic.
11860   struct VarDeclOrName {
11861     VarDecl *VDecl;
11862     DeclarationName Name;
11863 
11864     friend const Sema::SemaDiagnosticBuilder &
11865     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11866       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11867     }
11868   };
11869 } // end anonymous namespace
11870 
11871 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11872                                             DeclarationName Name, QualType Type,
11873                                             TypeSourceInfo *TSI,
11874                                             SourceRange Range, bool DirectInit,
11875                                             Expr *Init) {
11876   bool IsInitCapture = !VDecl;
11877   assert((!VDecl || !VDecl->isInitCapture()) &&
11878          "init captures are expected to be deduced prior to initialization");
11879 
11880   VarDeclOrName VN{VDecl, Name};
11881 
11882   DeducedType *Deduced = Type->getContainedDeducedType();
11883   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11884 
11885   // C++11 [dcl.spec.auto]p3
11886   if (!Init) {
11887     assert(VDecl && "no init for init capture deduction?");
11888 
11889     // Except for class argument deduction, and then for an initializing
11890     // declaration only, i.e. no static at class scope or extern.
11891     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11892         VDecl->hasExternalStorage() ||
11893         VDecl->isStaticDataMember()) {
11894       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11895         << VDecl->getDeclName() << Type;
11896       return QualType();
11897     }
11898   }
11899 
11900   ArrayRef<Expr*> DeduceInits;
11901   if (Init)
11902     DeduceInits = Init;
11903 
11904   if (DirectInit) {
11905     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11906       DeduceInits = PL->exprs();
11907   }
11908 
11909   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11910     assert(VDecl && "non-auto type for init capture deduction?");
11911     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11912     InitializationKind Kind = InitializationKind::CreateForInit(
11913         VDecl->getLocation(), DirectInit, Init);
11914     // FIXME: Initialization should not be taking a mutable list of inits.
11915     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11916     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11917                                                        InitsCopy);
11918   }
11919 
11920   if (DirectInit) {
11921     if (auto *IL = dyn_cast<InitListExpr>(Init))
11922       DeduceInits = IL->inits();
11923   }
11924 
11925   // Deduction only works if we have exactly one source expression.
11926   if (DeduceInits.empty()) {
11927     // It isn't possible to write this directly, but it is possible to
11928     // end up in this situation with "auto x(some_pack...);"
11929     Diag(Init->getBeginLoc(), IsInitCapture
11930                                   ? diag::err_init_capture_no_expression
11931                                   : diag::err_auto_var_init_no_expression)
11932         << VN << Type << Range;
11933     return QualType();
11934   }
11935 
11936   if (DeduceInits.size() > 1) {
11937     Diag(DeduceInits[1]->getBeginLoc(),
11938          IsInitCapture ? diag::err_init_capture_multiple_expressions
11939                        : diag::err_auto_var_init_multiple_expressions)
11940         << VN << Type << Range;
11941     return QualType();
11942   }
11943 
11944   Expr *DeduceInit = DeduceInits[0];
11945   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11946     Diag(Init->getBeginLoc(), IsInitCapture
11947                                   ? diag::err_init_capture_paren_braces
11948                                   : diag::err_auto_var_init_paren_braces)
11949         << isa<InitListExpr>(Init) << VN << Type << Range;
11950     return QualType();
11951   }
11952 
11953   // Expressions default to 'id' when we're in a debugger.
11954   bool DefaultedAnyToId = false;
11955   if (getLangOpts().DebuggerCastResultToId &&
11956       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11957     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11958     if (Result.isInvalid()) {
11959       return QualType();
11960     }
11961     Init = Result.get();
11962     DefaultedAnyToId = true;
11963   }
11964 
11965   // C++ [dcl.decomp]p1:
11966   //   If the assignment-expression [...] has array type A and no ref-qualifier
11967   //   is present, e has type cv A
11968   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11969       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11970       DeduceInit->getType()->isConstantArrayType())
11971     return Context.getQualifiedType(DeduceInit->getType(),
11972                                     Type.getQualifiers());
11973 
11974   QualType DeducedType;
11975   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11976     if (!IsInitCapture)
11977       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11978     else if (isa<InitListExpr>(Init))
11979       Diag(Range.getBegin(),
11980            diag::err_init_capture_deduction_failure_from_init_list)
11981           << VN
11982           << (DeduceInit->getType().isNull() ? TSI->getType()
11983                                              : DeduceInit->getType())
11984           << DeduceInit->getSourceRange();
11985     else
11986       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11987           << VN << TSI->getType()
11988           << (DeduceInit->getType().isNull() ? TSI->getType()
11989                                              : DeduceInit->getType())
11990           << DeduceInit->getSourceRange();
11991   }
11992 
11993   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11994   // 'id' instead of a specific object type prevents most of our usual
11995   // checks.
11996   // We only want to warn outside of template instantiations, though:
11997   // inside a template, the 'id' could have come from a parameter.
11998   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11999       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12000     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12001     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12002   }
12003 
12004   return DeducedType;
12005 }
12006 
12007 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12008                                          Expr *Init) {
12009   assert(!Init || !Init->containsErrors());
12010   QualType DeducedType = deduceVarTypeFromInitializer(
12011       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12012       VDecl->getSourceRange(), DirectInit, Init);
12013   if (DeducedType.isNull()) {
12014     VDecl->setInvalidDecl();
12015     return true;
12016   }
12017 
12018   VDecl->setType(DeducedType);
12019   assert(VDecl->isLinkageValid());
12020 
12021   // In ARC, infer lifetime.
12022   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12023     VDecl->setInvalidDecl();
12024 
12025   if (getLangOpts().OpenCL)
12026     deduceOpenCLAddressSpace(VDecl);
12027 
12028   // If this is a redeclaration, check that the type we just deduced matches
12029   // the previously declared type.
12030   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12031     // We never need to merge the type, because we cannot form an incomplete
12032     // array of auto, nor deduce such a type.
12033     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12034   }
12035 
12036   // Check the deduced type is valid for a variable declaration.
12037   CheckVariableDeclarationType(VDecl);
12038   return VDecl->isInvalidDecl();
12039 }
12040 
12041 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12042                                               SourceLocation Loc) {
12043   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12044     Init = EWC->getSubExpr();
12045 
12046   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12047     Init = CE->getSubExpr();
12048 
12049   QualType InitType = Init->getType();
12050   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12051           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12052          "shouldn't be called if type doesn't have a non-trivial C struct");
12053   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12054     for (auto I : ILE->inits()) {
12055       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12056           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12057         continue;
12058       SourceLocation SL = I->getExprLoc();
12059       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12060     }
12061     return;
12062   }
12063 
12064   if (isa<ImplicitValueInitExpr>(Init)) {
12065     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12066       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12067                             NTCUK_Init);
12068   } else {
12069     // Assume all other explicit initializers involving copying some existing
12070     // object.
12071     // TODO: ignore any explicit initializers where we can guarantee
12072     // copy-elision.
12073     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12074       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12075   }
12076 }
12077 
12078 namespace {
12079 
12080 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12081   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12082   // in the source code or implicitly by the compiler if it is in a union
12083   // defined in a system header and has non-trivial ObjC ownership
12084   // qualifications. We don't want those fields to participate in determining
12085   // whether the containing union is non-trivial.
12086   return FD->hasAttr<UnavailableAttr>();
12087 }
12088 
12089 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12090     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12091                                     void> {
12092   using Super =
12093       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12094                                     void>;
12095 
12096   DiagNonTrivalCUnionDefaultInitializeVisitor(
12097       QualType OrigTy, SourceLocation OrigLoc,
12098       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12099       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12100 
12101   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12102                      const FieldDecl *FD, bool InNonTrivialUnion) {
12103     if (const auto *AT = S.Context.getAsArrayType(QT))
12104       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12105                                      InNonTrivialUnion);
12106     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12107   }
12108 
12109   void visitARCStrong(QualType QT, const FieldDecl *FD,
12110                       bool InNonTrivialUnion) {
12111     if (InNonTrivialUnion)
12112       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12113           << 1 << 0 << QT << FD->getName();
12114   }
12115 
12116   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12117     if (InNonTrivialUnion)
12118       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12119           << 1 << 0 << QT << FD->getName();
12120   }
12121 
12122   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12123     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12124     if (RD->isUnion()) {
12125       if (OrigLoc.isValid()) {
12126         bool IsUnion = false;
12127         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12128           IsUnion = OrigRD->isUnion();
12129         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12130             << 0 << OrigTy << IsUnion << UseContext;
12131         // Reset OrigLoc so that this diagnostic is emitted only once.
12132         OrigLoc = SourceLocation();
12133       }
12134       InNonTrivialUnion = true;
12135     }
12136 
12137     if (InNonTrivialUnion)
12138       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12139           << 0 << 0 << QT.getUnqualifiedType() << "";
12140 
12141     for (const FieldDecl *FD : RD->fields())
12142       if (!shouldIgnoreForRecordTriviality(FD))
12143         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12144   }
12145 
12146   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12147 
12148   // The non-trivial C union type or the struct/union type that contains a
12149   // non-trivial C union.
12150   QualType OrigTy;
12151   SourceLocation OrigLoc;
12152   Sema::NonTrivialCUnionContext UseContext;
12153   Sema &S;
12154 };
12155 
12156 struct DiagNonTrivalCUnionDestructedTypeVisitor
12157     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12158   using Super =
12159       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12160 
12161   DiagNonTrivalCUnionDestructedTypeVisitor(
12162       QualType OrigTy, SourceLocation OrigLoc,
12163       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12164       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12165 
12166   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12167                      const FieldDecl *FD, bool InNonTrivialUnion) {
12168     if (const auto *AT = S.Context.getAsArrayType(QT))
12169       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12170                                      InNonTrivialUnion);
12171     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12172   }
12173 
12174   void visitARCStrong(QualType QT, const FieldDecl *FD,
12175                       bool InNonTrivialUnion) {
12176     if (InNonTrivialUnion)
12177       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12178           << 1 << 1 << QT << FD->getName();
12179   }
12180 
12181   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12182     if (InNonTrivialUnion)
12183       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12184           << 1 << 1 << QT << FD->getName();
12185   }
12186 
12187   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12188     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12189     if (RD->isUnion()) {
12190       if (OrigLoc.isValid()) {
12191         bool IsUnion = false;
12192         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12193           IsUnion = OrigRD->isUnion();
12194         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12195             << 1 << OrigTy << IsUnion << UseContext;
12196         // Reset OrigLoc so that this diagnostic is emitted only once.
12197         OrigLoc = SourceLocation();
12198       }
12199       InNonTrivialUnion = true;
12200     }
12201 
12202     if (InNonTrivialUnion)
12203       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12204           << 0 << 1 << QT.getUnqualifiedType() << "";
12205 
12206     for (const FieldDecl *FD : RD->fields())
12207       if (!shouldIgnoreForRecordTriviality(FD))
12208         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12209   }
12210 
12211   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12212   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12213                           bool InNonTrivialUnion) {}
12214 
12215   // The non-trivial C union type or the struct/union type that contains a
12216   // non-trivial C union.
12217   QualType OrigTy;
12218   SourceLocation OrigLoc;
12219   Sema::NonTrivialCUnionContext UseContext;
12220   Sema &S;
12221 };
12222 
12223 struct DiagNonTrivalCUnionCopyVisitor
12224     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12225   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12226 
12227   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12228                                  Sema::NonTrivialCUnionContext UseContext,
12229                                  Sema &S)
12230       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12231 
12232   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12233                      const FieldDecl *FD, bool InNonTrivialUnion) {
12234     if (const auto *AT = S.Context.getAsArrayType(QT))
12235       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12236                                      InNonTrivialUnion);
12237     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12238   }
12239 
12240   void visitARCStrong(QualType QT, const FieldDecl *FD,
12241                       bool InNonTrivialUnion) {
12242     if (InNonTrivialUnion)
12243       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12244           << 1 << 2 << QT << FD->getName();
12245   }
12246 
12247   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12248     if (InNonTrivialUnion)
12249       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12250           << 1 << 2 << QT << FD->getName();
12251   }
12252 
12253   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12254     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12255     if (RD->isUnion()) {
12256       if (OrigLoc.isValid()) {
12257         bool IsUnion = false;
12258         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12259           IsUnion = OrigRD->isUnion();
12260         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12261             << 2 << OrigTy << IsUnion << UseContext;
12262         // Reset OrigLoc so that this diagnostic is emitted only once.
12263         OrigLoc = SourceLocation();
12264       }
12265       InNonTrivialUnion = true;
12266     }
12267 
12268     if (InNonTrivialUnion)
12269       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12270           << 0 << 2 << QT.getUnqualifiedType() << "";
12271 
12272     for (const FieldDecl *FD : RD->fields())
12273       if (!shouldIgnoreForRecordTriviality(FD))
12274         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12275   }
12276 
12277   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12278                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12279   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12280   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12281                             bool InNonTrivialUnion) {}
12282 
12283   // The non-trivial C union type or the struct/union type that contains a
12284   // non-trivial C union.
12285   QualType OrigTy;
12286   SourceLocation OrigLoc;
12287   Sema::NonTrivialCUnionContext UseContext;
12288   Sema &S;
12289 };
12290 
12291 } // namespace
12292 
12293 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12294                                  NonTrivialCUnionContext UseContext,
12295                                  unsigned NonTrivialKind) {
12296   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12297           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12298           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12299          "shouldn't be called if type doesn't have a non-trivial C union");
12300 
12301   if ((NonTrivialKind & NTCUK_Init) &&
12302       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12303     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12304         .visit(QT, nullptr, false);
12305   if ((NonTrivialKind & NTCUK_Destruct) &&
12306       QT.hasNonTrivialToPrimitiveDestructCUnion())
12307     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12308         .visit(QT, nullptr, false);
12309   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12310     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12311         .visit(QT, nullptr, false);
12312 }
12313 
12314 /// AddInitializerToDecl - Adds the initializer Init to the
12315 /// declaration dcl. If DirectInit is true, this is C++ direct
12316 /// initialization rather than copy initialization.
12317 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12318   // If there is no declaration, there was an error parsing it.  Just ignore
12319   // the initializer.
12320   if (!RealDecl || RealDecl->isInvalidDecl()) {
12321     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12322     return;
12323   }
12324 
12325   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12326     // Pure-specifiers are handled in ActOnPureSpecifier.
12327     Diag(Method->getLocation(), diag::err_member_function_initialization)
12328       << Method->getDeclName() << Init->getSourceRange();
12329     Method->setInvalidDecl();
12330     return;
12331   }
12332 
12333   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12334   if (!VDecl) {
12335     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12336     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12337     RealDecl->setInvalidDecl();
12338     return;
12339   }
12340 
12341   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12342   if (VDecl->getType()->isUndeducedType()) {
12343     // Attempt typo correction early so that the type of the init expression can
12344     // be deduced based on the chosen correction if the original init contains a
12345     // TypoExpr.
12346     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12347     if (!Res.isUsable()) {
12348       // There are unresolved typos in Init, just drop them.
12349       // FIXME: improve the recovery strategy to preserve the Init.
12350       RealDecl->setInvalidDecl();
12351       return;
12352     }
12353     if (Res.get()->containsErrors()) {
12354       // Invalidate the decl as we don't know the type for recovery-expr yet.
12355       RealDecl->setInvalidDecl();
12356       VDecl->setInit(Res.get());
12357       return;
12358     }
12359     Init = Res.get();
12360 
12361     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12362       return;
12363   }
12364 
12365   // dllimport cannot be used on variable definitions.
12366   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12367     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12368     VDecl->setInvalidDecl();
12369     return;
12370   }
12371 
12372   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12373     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12374     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12375     VDecl->setInvalidDecl();
12376     return;
12377   }
12378 
12379   if (!VDecl->getType()->isDependentType()) {
12380     // A definition must end up with a complete type, which means it must be
12381     // complete with the restriction that an array type might be completed by
12382     // the initializer; note that later code assumes this restriction.
12383     QualType BaseDeclType = VDecl->getType();
12384     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12385       BaseDeclType = Array->getElementType();
12386     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12387                             diag::err_typecheck_decl_incomplete_type)) {
12388       RealDecl->setInvalidDecl();
12389       return;
12390     }
12391 
12392     // The variable can not have an abstract class type.
12393     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12394                                diag::err_abstract_type_in_decl,
12395                                AbstractVariableType))
12396       VDecl->setInvalidDecl();
12397   }
12398 
12399   // If adding the initializer will turn this declaration into a definition,
12400   // and we already have a definition for this variable, diagnose or otherwise
12401   // handle the situation.
12402   if (VarDecl *Def = VDecl->getDefinition())
12403     if (Def != VDecl &&
12404         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12405         !VDecl->isThisDeclarationADemotedDefinition() &&
12406         checkVarDeclRedefinition(Def, VDecl))
12407       return;
12408 
12409   if (getLangOpts().CPlusPlus) {
12410     // C++ [class.static.data]p4
12411     //   If a static data member is of const integral or const
12412     //   enumeration type, its declaration in the class definition can
12413     //   specify a constant-initializer which shall be an integral
12414     //   constant expression (5.19). In that case, the member can appear
12415     //   in integral constant expressions. The member shall still be
12416     //   defined in a namespace scope if it is used in the program and the
12417     //   namespace scope definition shall not contain an initializer.
12418     //
12419     // We already performed a redefinition check above, but for static
12420     // data members we also need to check whether there was an in-class
12421     // declaration with an initializer.
12422     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12423       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12424           << VDecl->getDeclName();
12425       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12426            diag::note_previous_initializer)
12427           << 0;
12428       return;
12429     }
12430 
12431     if (VDecl->hasLocalStorage())
12432       setFunctionHasBranchProtectedScope();
12433 
12434     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12435       VDecl->setInvalidDecl();
12436       return;
12437     }
12438   }
12439 
12440   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12441   // a kernel function cannot be initialized."
12442   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12443     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12444     VDecl->setInvalidDecl();
12445     return;
12446   }
12447 
12448   // The LoaderUninitialized attribute acts as a definition (of undef).
12449   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12450     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12451     VDecl->setInvalidDecl();
12452     return;
12453   }
12454 
12455   // Get the decls type and save a reference for later, since
12456   // CheckInitializerTypes may change it.
12457   QualType DclT = VDecl->getType(), SavT = DclT;
12458 
12459   // Expressions default to 'id' when we're in a debugger
12460   // and we are assigning it to a variable of Objective-C pointer type.
12461   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12462       Init->getType() == Context.UnknownAnyTy) {
12463     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12464     if (Result.isInvalid()) {
12465       VDecl->setInvalidDecl();
12466       return;
12467     }
12468     Init = Result.get();
12469   }
12470 
12471   // Perform the initialization.
12472   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12473   if (!VDecl->isInvalidDecl()) {
12474     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12475     InitializationKind Kind = InitializationKind::CreateForInit(
12476         VDecl->getLocation(), DirectInit, Init);
12477 
12478     MultiExprArg Args = Init;
12479     if (CXXDirectInit)
12480       Args = MultiExprArg(CXXDirectInit->getExprs(),
12481                           CXXDirectInit->getNumExprs());
12482 
12483     // Try to correct any TypoExprs in the initialization arguments.
12484     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12485       ExprResult Res = CorrectDelayedTyposInExpr(
12486           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12487           [this, Entity, Kind](Expr *E) {
12488             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12489             return Init.Failed() ? ExprError() : E;
12490           });
12491       if (Res.isInvalid()) {
12492         VDecl->setInvalidDecl();
12493       } else if (Res.get() != Args[Idx]) {
12494         Args[Idx] = Res.get();
12495       }
12496     }
12497     if (VDecl->isInvalidDecl())
12498       return;
12499 
12500     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12501                                    /*TopLevelOfInitList=*/false,
12502                                    /*TreatUnavailableAsInvalid=*/false);
12503     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12504     if (Result.isInvalid()) {
12505       // If the provided initializer fails to initialize the var decl,
12506       // we attach a recovery expr for better recovery.
12507       auto RecoveryExpr =
12508           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12509       if (RecoveryExpr.get())
12510         VDecl->setInit(RecoveryExpr.get());
12511       return;
12512     }
12513 
12514     Init = Result.getAs<Expr>();
12515   }
12516 
12517   // Check for self-references within variable initializers.
12518   // Variables declared within a function/method body (except for references)
12519   // are handled by a dataflow analysis.
12520   // This is undefined behavior in C++, but valid in C.
12521   if (getLangOpts().CPlusPlus)
12522     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12523         VDecl->getType()->isReferenceType())
12524       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12525 
12526   // If the type changed, it means we had an incomplete type that was
12527   // completed by the initializer. For example:
12528   //   int ary[] = { 1, 3, 5 };
12529   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12530   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12531     VDecl->setType(DclT);
12532 
12533   if (!VDecl->isInvalidDecl()) {
12534     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12535 
12536     if (VDecl->hasAttr<BlocksAttr>())
12537       checkRetainCycles(VDecl, Init);
12538 
12539     // It is safe to assign a weak reference into a strong variable.
12540     // Although this code can still have problems:
12541     //   id x = self.weakProp;
12542     //   id y = self.weakProp;
12543     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12544     // paths through the function. This should be revisited if
12545     // -Wrepeated-use-of-weak is made flow-sensitive.
12546     if (FunctionScopeInfo *FSI = getCurFunction())
12547       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12548            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12549           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12550                            Init->getBeginLoc()))
12551         FSI->markSafeWeakUse(Init);
12552   }
12553 
12554   // The initialization is usually a full-expression.
12555   //
12556   // FIXME: If this is a braced initialization of an aggregate, it is not
12557   // an expression, and each individual field initializer is a separate
12558   // full-expression. For instance, in:
12559   //
12560   //   struct Temp { ~Temp(); };
12561   //   struct S { S(Temp); };
12562   //   struct T { S a, b; } t = { Temp(), Temp() }
12563   //
12564   // we should destroy the first Temp before constructing the second.
12565   ExprResult Result =
12566       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12567                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12568   if (Result.isInvalid()) {
12569     VDecl->setInvalidDecl();
12570     return;
12571   }
12572   Init = Result.get();
12573 
12574   // Attach the initializer to the decl.
12575   VDecl->setInit(Init);
12576 
12577   if (VDecl->isLocalVarDecl()) {
12578     // Don't check the initializer if the declaration is malformed.
12579     if (VDecl->isInvalidDecl()) {
12580       // do nothing
12581 
12582     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12583     // This is true even in C++ for OpenCL.
12584     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12585       CheckForConstantInitializer(Init, DclT);
12586 
12587     // Otherwise, C++ does not restrict the initializer.
12588     } else if (getLangOpts().CPlusPlus) {
12589       // do nothing
12590 
12591     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12592     // static storage duration shall be constant expressions or string literals.
12593     } else if (VDecl->getStorageClass() == SC_Static) {
12594       CheckForConstantInitializer(Init, DclT);
12595 
12596     // C89 is stricter than C99 for aggregate initializers.
12597     // C89 6.5.7p3: All the expressions [...] in an initializer list
12598     // for an object that has aggregate or union type shall be
12599     // constant expressions.
12600     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12601                isa<InitListExpr>(Init)) {
12602       const Expr *Culprit;
12603       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12604         Diag(Culprit->getExprLoc(),
12605              diag::ext_aggregate_init_not_constant)
12606           << Culprit->getSourceRange();
12607       }
12608     }
12609 
12610     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12611       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12612         if (VDecl->hasLocalStorage())
12613           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12614   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12615              VDecl->getLexicalDeclContext()->isRecord()) {
12616     // This is an in-class initialization for a static data member, e.g.,
12617     //
12618     // struct S {
12619     //   static const int value = 17;
12620     // };
12621 
12622     // C++ [class.mem]p4:
12623     //   A member-declarator can contain a constant-initializer only
12624     //   if it declares a static member (9.4) of const integral or
12625     //   const enumeration type, see 9.4.2.
12626     //
12627     // C++11 [class.static.data]p3:
12628     //   If a non-volatile non-inline const static data member is of integral
12629     //   or enumeration type, its declaration in the class definition can
12630     //   specify a brace-or-equal-initializer in which every initializer-clause
12631     //   that is an assignment-expression is a constant expression. A static
12632     //   data member of literal type can be declared in the class definition
12633     //   with the constexpr specifier; if so, its declaration shall specify a
12634     //   brace-or-equal-initializer in which every initializer-clause that is
12635     //   an assignment-expression is a constant expression.
12636 
12637     // Do nothing on dependent types.
12638     if (DclT->isDependentType()) {
12639 
12640     // Allow any 'static constexpr' members, whether or not they are of literal
12641     // type. We separately check that every constexpr variable is of literal
12642     // type.
12643     } else if (VDecl->isConstexpr()) {
12644 
12645     // Require constness.
12646     } else if (!DclT.isConstQualified()) {
12647       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12648         << Init->getSourceRange();
12649       VDecl->setInvalidDecl();
12650 
12651     // We allow integer constant expressions in all cases.
12652     } else if (DclT->isIntegralOrEnumerationType()) {
12653       // Check whether the expression is a constant expression.
12654       SourceLocation Loc;
12655       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12656         // In C++11, a non-constexpr const static data member with an
12657         // in-class initializer cannot be volatile.
12658         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12659       else if (Init->isValueDependent())
12660         ; // Nothing to check.
12661       else if (Init->isIntegerConstantExpr(Context, &Loc))
12662         ; // Ok, it's an ICE!
12663       else if (Init->getType()->isScopedEnumeralType() &&
12664                Init->isCXX11ConstantExpr(Context))
12665         ; // Ok, it is a scoped-enum constant expression.
12666       else if (Init->isEvaluatable(Context)) {
12667         // If we can constant fold the initializer through heroics, accept it,
12668         // but report this as a use of an extension for -pedantic.
12669         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12670           << Init->getSourceRange();
12671       } else {
12672         // Otherwise, this is some crazy unknown case.  Report the issue at the
12673         // location provided by the isIntegerConstantExpr failed check.
12674         Diag(Loc, diag::err_in_class_initializer_non_constant)
12675           << Init->getSourceRange();
12676         VDecl->setInvalidDecl();
12677       }
12678 
12679     // We allow foldable floating-point constants as an extension.
12680     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12681       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12682       // it anyway and provide a fixit to add the 'constexpr'.
12683       if (getLangOpts().CPlusPlus11) {
12684         Diag(VDecl->getLocation(),
12685              diag::ext_in_class_initializer_float_type_cxx11)
12686             << DclT << Init->getSourceRange();
12687         Diag(VDecl->getBeginLoc(),
12688              diag::note_in_class_initializer_float_type_cxx11)
12689             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12690       } else {
12691         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12692           << DclT << Init->getSourceRange();
12693 
12694         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12695           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12696             << Init->getSourceRange();
12697           VDecl->setInvalidDecl();
12698         }
12699       }
12700 
12701     // Suggest adding 'constexpr' in C++11 for literal types.
12702     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12703       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12704           << DclT << Init->getSourceRange()
12705           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12706       VDecl->setConstexpr(true);
12707 
12708     } else {
12709       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12710         << DclT << Init->getSourceRange();
12711       VDecl->setInvalidDecl();
12712     }
12713   } else if (VDecl->isFileVarDecl()) {
12714     // In C, extern is typically used to avoid tentative definitions when
12715     // declaring variables in headers, but adding an intializer makes it a
12716     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12717     // In C++, extern is often used to give implictly static const variables
12718     // external linkage, so don't warn in that case. If selectany is present,
12719     // this might be header code intended for C and C++ inclusion, so apply the
12720     // C++ rules.
12721     if (VDecl->getStorageClass() == SC_Extern &&
12722         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12723          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12724         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12725         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12726       Diag(VDecl->getLocation(), diag::warn_extern_init);
12727 
12728     // In Microsoft C++ mode, a const variable defined in namespace scope has
12729     // external linkage by default if the variable is declared with
12730     // __declspec(dllexport).
12731     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12732         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12733         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12734       VDecl->setStorageClass(SC_Extern);
12735 
12736     // C99 6.7.8p4. All file scoped initializers need to be constant.
12737     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12738       CheckForConstantInitializer(Init, DclT);
12739   }
12740 
12741   QualType InitType = Init->getType();
12742   if (!InitType.isNull() &&
12743       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12744        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12745     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12746 
12747   // We will represent direct-initialization similarly to copy-initialization:
12748   //    int x(1);  -as-> int x = 1;
12749   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12750   //
12751   // Clients that want to distinguish between the two forms, can check for
12752   // direct initializer using VarDecl::getInitStyle().
12753   // A major benefit is that clients that don't particularly care about which
12754   // exactly form was it (like the CodeGen) can handle both cases without
12755   // special case code.
12756 
12757   // C++ 8.5p11:
12758   // The form of initialization (using parentheses or '=') is generally
12759   // insignificant, but does matter when the entity being initialized has a
12760   // class type.
12761   if (CXXDirectInit) {
12762     assert(DirectInit && "Call-style initializer must be direct init.");
12763     VDecl->setInitStyle(VarDecl::CallInit);
12764   } else if (DirectInit) {
12765     // This must be list-initialization. No other way is direct-initialization.
12766     VDecl->setInitStyle(VarDecl::ListInit);
12767   }
12768 
12769   if (LangOpts.OpenMP &&
12770       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12771       VDecl->isFileVarDecl())
12772     DeclsToCheckForDeferredDiags.insert(VDecl);
12773   CheckCompleteVariableDeclaration(VDecl);
12774 }
12775 
12776 /// ActOnInitializerError - Given that there was an error parsing an
12777 /// initializer for the given declaration, try to at least re-establish
12778 /// invariants such as whether a variable's type is either dependent or
12779 /// complete.
12780 void Sema::ActOnInitializerError(Decl *D) {
12781   // Our main concern here is re-establishing invariants like "a
12782   // variable's type is either dependent or complete".
12783   if (!D || D->isInvalidDecl()) return;
12784 
12785   VarDecl *VD = dyn_cast<VarDecl>(D);
12786   if (!VD) return;
12787 
12788   // Bindings are not usable if we can't make sense of the initializer.
12789   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12790     for (auto *BD : DD->bindings())
12791       BD->setInvalidDecl();
12792 
12793   // Auto types are meaningless if we can't make sense of the initializer.
12794   if (VD->getType()->isUndeducedType()) {
12795     D->setInvalidDecl();
12796     return;
12797   }
12798 
12799   QualType Ty = VD->getType();
12800   if (Ty->isDependentType()) return;
12801 
12802   // Require a complete type.
12803   if (RequireCompleteType(VD->getLocation(),
12804                           Context.getBaseElementType(Ty),
12805                           diag::err_typecheck_decl_incomplete_type)) {
12806     VD->setInvalidDecl();
12807     return;
12808   }
12809 
12810   // Require a non-abstract type.
12811   if (RequireNonAbstractType(VD->getLocation(), Ty,
12812                              diag::err_abstract_type_in_decl,
12813                              AbstractVariableType)) {
12814     VD->setInvalidDecl();
12815     return;
12816   }
12817 
12818   // Don't bother complaining about constructors or destructors,
12819   // though.
12820 }
12821 
12822 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12823   // If there is no declaration, there was an error parsing it. Just ignore it.
12824   if (!RealDecl)
12825     return;
12826 
12827   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12828     QualType Type = Var->getType();
12829 
12830     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12831     if (isa<DecompositionDecl>(RealDecl)) {
12832       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12833       Var->setInvalidDecl();
12834       return;
12835     }
12836 
12837     if (Type->isUndeducedType() &&
12838         DeduceVariableDeclarationType(Var, false, nullptr))
12839       return;
12840 
12841     // C++11 [class.static.data]p3: A static data member can be declared with
12842     // the constexpr specifier; if so, its declaration shall specify
12843     // a brace-or-equal-initializer.
12844     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12845     // the definition of a variable [...] or the declaration of a static data
12846     // member.
12847     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12848         !Var->isThisDeclarationADemotedDefinition()) {
12849       if (Var->isStaticDataMember()) {
12850         // C++1z removes the relevant rule; the in-class declaration is always
12851         // a definition there.
12852         if (!getLangOpts().CPlusPlus17 &&
12853             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12854           Diag(Var->getLocation(),
12855                diag::err_constexpr_static_mem_var_requires_init)
12856               << Var;
12857           Var->setInvalidDecl();
12858           return;
12859         }
12860       } else {
12861         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12862         Var->setInvalidDecl();
12863         return;
12864       }
12865     }
12866 
12867     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12868     // be initialized.
12869     if (!Var->isInvalidDecl() &&
12870         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12871         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12872       bool HasConstExprDefaultConstructor = false;
12873       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12874         for (auto *Ctor : RD->ctors()) {
12875           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12876               Ctor->getMethodQualifiers().getAddressSpace() ==
12877                   LangAS::opencl_constant) {
12878             HasConstExprDefaultConstructor = true;
12879           }
12880         }
12881       }
12882       if (!HasConstExprDefaultConstructor) {
12883         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12884         Var->setInvalidDecl();
12885         return;
12886       }
12887     }
12888 
12889     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12890       if (Var->getStorageClass() == SC_Extern) {
12891         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12892             << Var;
12893         Var->setInvalidDecl();
12894         return;
12895       }
12896       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12897                               diag::err_typecheck_decl_incomplete_type)) {
12898         Var->setInvalidDecl();
12899         return;
12900       }
12901       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12902         if (!RD->hasTrivialDefaultConstructor()) {
12903           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12904           Var->setInvalidDecl();
12905           return;
12906         }
12907       }
12908       // The declaration is unitialized, no need for further checks.
12909       return;
12910     }
12911 
12912     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12913     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12914         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12915       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12916                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12917 
12918 
12919     switch (DefKind) {
12920     case VarDecl::Definition:
12921       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12922         break;
12923 
12924       // We have an out-of-line definition of a static data member
12925       // that has an in-class initializer, so we type-check this like
12926       // a declaration.
12927       //
12928       LLVM_FALLTHROUGH;
12929 
12930     case VarDecl::DeclarationOnly:
12931       // It's only a declaration.
12932 
12933       // Block scope. C99 6.7p7: If an identifier for an object is
12934       // declared with no linkage (C99 6.2.2p6), the type for the
12935       // object shall be complete.
12936       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12937           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12938           RequireCompleteType(Var->getLocation(), Type,
12939                               diag::err_typecheck_decl_incomplete_type))
12940         Var->setInvalidDecl();
12941 
12942       // Make sure that the type is not abstract.
12943       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12944           RequireNonAbstractType(Var->getLocation(), Type,
12945                                  diag::err_abstract_type_in_decl,
12946                                  AbstractVariableType))
12947         Var->setInvalidDecl();
12948       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12949           Var->getStorageClass() == SC_PrivateExtern) {
12950         Diag(Var->getLocation(), diag::warn_private_extern);
12951         Diag(Var->getLocation(), diag::note_private_extern);
12952       }
12953 
12954       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12955           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12956         ExternalDeclarations.push_back(Var);
12957 
12958       return;
12959 
12960     case VarDecl::TentativeDefinition:
12961       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12962       // object that has file scope without an initializer, and without a
12963       // storage-class specifier or with the storage-class specifier "static",
12964       // constitutes a tentative definition. Note: A tentative definition with
12965       // external linkage is valid (C99 6.2.2p5).
12966       if (!Var->isInvalidDecl()) {
12967         if (const IncompleteArrayType *ArrayT
12968                                     = Context.getAsIncompleteArrayType(Type)) {
12969           if (RequireCompleteSizedType(
12970                   Var->getLocation(), ArrayT->getElementType(),
12971                   diag::err_array_incomplete_or_sizeless_type))
12972             Var->setInvalidDecl();
12973         } else if (Var->getStorageClass() == SC_Static) {
12974           // C99 6.9.2p3: If the declaration of an identifier for an object is
12975           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12976           // declared type shall not be an incomplete type.
12977           // NOTE: code such as the following
12978           //     static struct s;
12979           //     struct s { int a; };
12980           // is accepted by gcc. Hence here we issue a warning instead of
12981           // an error and we do not invalidate the static declaration.
12982           // NOTE: to avoid multiple warnings, only check the first declaration.
12983           if (Var->isFirstDecl())
12984             RequireCompleteType(Var->getLocation(), Type,
12985                                 diag::ext_typecheck_decl_incomplete_type);
12986         }
12987       }
12988 
12989       // Record the tentative definition; we're done.
12990       if (!Var->isInvalidDecl())
12991         TentativeDefinitions.push_back(Var);
12992       return;
12993     }
12994 
12995     // Provide a specific diagnostic for uninitialized variable
12996     // definitions with incomplete array type.
12997     if (Type->isIncompleteArrayType()) {
12998       Diag(Var->getLocation(),
12999            diag::err_typecheck_incomplete_array_needs_initializer);
13000       Var->setInvalidDecl();
13001       return;
13002     }
13003 
13004     // Provide a specific diagnostic for uninitialized variable
13005     // definitions with reference type.
13006     if (Type->isReferenceType()) {
13007       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13008           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13009       Var->setInvalidDecl();
13010       return;
13011     }
13012 
13013     // Do not attempt to type-check the default initializer for a
13014     // variable with dependent type.
13015     if (Type->isDependentType())
13016       return;
13017 
13018     if (Var->isInvalidDecl())
13019       return;
13020 
13021     if (!Var->hasAttr<AliasAttr>()) {
13022       if (RequireCompleteType(Var->getLocation(),
13023                               Context.getBaseElementType(Type),
13024                               diag::err_typecheck_decl_incomplete_type)) {
13025         Var->setInvalidDecl();
13026         return;
13027       }
13028     } else {
13029       return;
13030     }
13031 
13032     // The variable can not have an abstract class type.
13033     if (RequireNonAbstractType(Var->getLocation(), Type,
13034                                diag::err_abstract_type_in_decl,
13035                                AbstractVariableType)) {
13036       Var->setInvalidDecl();
13037       return;
13038     }
13039 
13040     // Check for jumps past the implicit initializer.  C++0x
13041     // clarifies that this applies to a "variable with automatic
13042     // storage duration", not a "local variable".
13043     // C++11 [stmt.dcl]p3
13044     //   A program that jumps from a point where a variable with automatic
13045     //   storage duration is not in scope to a point where it is in scope is
13046     //   ill-formed unless the variable has scalar type, class type with a
13047     //   trivial default constructor and a trivial destructor, a cv-qualified
13048     //   version of one of these types, or an array of one of the preceding
13049     //   types and is declared without an initializer.
13050     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13051       if (const RecordType *Record
13052             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13053         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13054         // Mark the function (if we're in one) for further checking even if the
13055         // looser rules of C++11 do not require such checks, so that we can
13056         // diagnose incompatibilities with C++98.
13057         if (!CXXRecord->isPOD())
13058           setFunctionHasBranchProtectedScope();
13059       }
13060     }
13061     // In OpenCL, we can't initialize objects in the __local address space,
13062     // even implicitly, so don't synthesize an implicit initializer.
13063     if (getLangOpts().OpenCL &&
13064         Var->getType().getAddressSpace() == LangAS::opencl_local)
13065       return;
13066     // C++03 [dcl.init]p9:
13067     //   If no initializer is specified for an object, and the
13068     //   object is of (possibly cv-qualified) non-POD class type (or
13069     //   array thereof), the object shall be default-initialized; if
13070     //   the object is of const-qualified type, the underlying class
13071     //   type shall have a user-declared default
13072     //   constructor. Otherwise, if no initializer is specified for
13073     //   a non- static object, the object and its subobjects, if
13074     //   any, have an indeterminate initial value); if the object
13075     //   or any of its subobjects are of const-qualified type, the
13076     //   program is ill-formed.
13077     // C++0x [dcl.init]p11:
13078     //   If no initializer is specified for an object, the object is
13079     //   default-initialized; [...].
13080     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13081     InitializationKind Kind
13082       = InitializationKind::CreateDefault(Var->getLocation());
13083 
13084     InitializationSequence InitSeq(*this, Entity, Kind, None);
13085     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13086 
13087     if (Init.get()) {
13088       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13089       // This is important for template substitution.
13090       Var->setInitStyle(VarDecl::CallInit);
13091     } else if (Init.isInvalid()) {
13092       // If default-init fails, attach a recovery-expr initializer to track
13093       // that initialization was attempted and failed.
13094       auto RecoveryExpr =
13095           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13096       if (RecoveryExpr.get())
13097         Var->setInit(RecoveryExpr.get());
13098     }
13099 
13100     CheckCompleteVariableDeclaration(Var);
13101   }
13102 }
13103 
13104 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13105   // If there is no declaration, there was an error parsing it. Ignore it.
13106   if (!D)
13107     return;
13108 
13109   VarDecl *VD = dyn_cast<VarDecl>(D);
13110   if (!VD) {
13111     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13112     D->setInvalidDecl();
13113     return;
13114   }
13115 
13116   VD->setCXXForRangeDecl(true);
13117 
13118   // for-range-declaration cannot be given a storage class specifier.
13119   int Error = -1;
13120   switch (VD->getStorageClass()) {
13121   case SC_None:
13122     break;
13123   case SC_Extern:
13124     Error = 0;
13125     break;
13126   case SC_Static:
13127     Error = 1;
13128     break;
13129   case SC_PrivateExtern:
13130     Error = 2;
13131     break;
13132   case SC_Auto:
13133     Error = 3;
13134     break;
13135   case SC_Register:
13136     Error = 4;
13137     break;
13138   }
13139 
13140   // for-range-declaration cannot be given a storage class specifier con't.
13141   switch (VD->getTSCSpec()) {
13142   case TSCS_thread_local:
13143     Error = 6;
13144     break;
13145   case TSCS___thread:
13146   case TSCS__Thread_local:
13147   case TSCS_unspecified:
13148     break;
13149   }
13150 
13151   if (Error != -1) {
13152     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13153         << VD << Error;
13154     D->setInvalidDecl();
13155   }
13156 }
13157 
13158 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13159                                             IdentifierInfo *Ident,
13160                                             ParsedAttributes &Attrs) {
13161   // C++1y [stmt.iter]p1:
13162   //   A range-based for statement of the form
13163   //      for ( for-range-identifier : for-range-initializer ) statement
13164   //   is equivalent to
13165   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13166   DeclSpec DS(Attrs.getPool().getFactory());
13167 
13168   const char *PrevSpec;
13169   unsigned DiagID;
13170   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13171                      getPrintingPolicy());
13172 
13173   Declarator D(DS, DeclaratorContext::ForInit);
13174   D.SetIdentifier(Ident, IdentLoc);
13175   D.takeAttributes(Attrs);
13176 
13177   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13178                 IdentLoc);
13179   Decl *Var = ActOnDeclarator(S, D);
13180   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13181   FinalizeDeclaration(Var);
13182   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13183                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13184                                                       : IdentLoc);
13185 }
13186 
13187 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13188   if (var->isInvalidDecl()) return;
13189 
13190   MaybeAddCUDAConstantAttr(var);
13191 
13192   if (getLangOpts().OpenCL) {
13193     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13194     // initialiser
13195     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13196         !var->hasInit()) {
13197       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13198           << 1 /*Init*/;
13199       var->setInvalidDecl();
13200       return;
13201     }
13202   }
13203 
13204   // In Objective-C, don't allow jumps past the implicit initialization of a
13205   // local retaining variable.
13206   if (getLangOpts().ObjC &&
13207       var->hasLocalStorage()) {
13208     switch (var->getType().getObjCLifetime()) {
13209     case Qualifiers::OCL_None:
13210     case Qualifiers::OCL_ExplicitNone:
13211     case Qualifiers::OCL_Autoreleasing:
13212       break;
13213 
13214     case Qualifiers::OCL_Weak:
13215     case Qualifiers::OCL_Strong:
13216       setFunctionHasBranchProtectedScope();
13217       break;
13218     }
13219   }
13220 
13221   if (var->hasLocalStorage() &&
13222       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13223     setFunctionHasBranchProtectedScope();
13224 
13225   // Warn about externally-visible variables being defined without a
13226   // prior declaration.  We only want to do this for global
13227   // declarations, but we also specifically need to avoid doing it for
13228   // class members because the linkage of an anonymous class can
13229   // change if it's later given a typedef name.
13230   if (var->isThisDeclarationADefinition() &&
13231       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13232       var->isExternallyVisible() && var->hasLinkage() &&
13233       !var->isInline() && !var->getDescribedVarTemplate() &&
13234       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13235       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13236       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13237                                   var->getLocation())) {
13238     // Find a previous declaration that's not a definition.
13239     VarDecl *prev = var->getPreviousDecl();
13240     while (prev && prev->isThisDeclarationADefinition())
13241       prev = prev->getPreviousDecl();
13242 
13243     if (!prev) {
13244       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13245       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13246           << /* variable */ 0;
13247     }
13248   }
13249 
13250   // Cache the result of checking for constant initialization.
13251   Optional<bool> CacheHasConstInit;
13252   const Expr *CacheCulprit = nullptr;
13253   auto checkConstInit = [&]() mutable {
13254     if (!CacheHasConstInit)
13255       CacheHasConstInit = var->getInit()->isConstantInitializer(
13256             Context, var->getType()->isReferenceType(), &CacheCulprit);
13257     return *CacheHasConstInit;
13258   };
13259 
13260   if (var->getTLSKind() == VarDecl::TLS_Static) {
13261     if (var->getType().isDestructedType()) {
13262       // GNU C++98 edits for __thread, [basic.start.term]p3:
13263       //   The type of an object with thread storage duration shall not
13264       //   have a non-trivial destructor.
13265       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13266       if (getLangOpts().CPlusPlus11)
13267         Diag(var->getLocation(), diag::note_use_thread_local);
13268     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13269       if (!checkConstInit()) {
13270         // GNU C++98 edits for __thread, [basic.start.init]p4:
13271         //   An object of thread storage duration shall not require dynamic
13272         //   initialization.
13273         // FIXME: Need strict checking here.
13274         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13275           << CacheCulprit->getSourceRange();
13276         if (getLangOpts().CPlusPlus11)
13277           Diag(var->getLocation(), diag::note_use_thread_local);
13278       }
13279     }
13280   }
13281 
13282 
13283   if (!var->getType()->isStructureType() && var->hasInit() &&
13284       isa<InitListExpr>(var->getInit())) {
13285     const auto *ILE = cast<InitListExpr>(var->getInit());
13286     unsigned NumInits = ILE->getNumInits();
13287     if (NumInits > 2)
13288       for (unsigned I = 0; I < NumInits; ++I) {
13289         const auto *Init = ILE->getInit(I);
13290         if (!Init)
13291           break;
13292         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13293         if (!SL)
13294           break;
13295 
13296         unsigned NumConcat = SL->getNumConcatenated();
13297         // Diagnose missing comma in string array initialization.
13298         // Do not warn when all the elements in the initializer are concatenated
13299         // together. Do not warn for macros too.
13300         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13301           bool OnlyOneMissingComma = true;
13302           for (unsigned J = I + 1; J < NumInits; ++J) {
13303             const auto *Init = ILE->getInit(J);
13304             if (!Init)
13305               break;
13306             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13307             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13308               OnlyOneMissingComma = false;
13309               break;
13310             }
13311           }
13312 
13313           if (OnlyOneMissingComma) {
13314             SmallVector<FixItHint, 1> Hints;
13315             for (unsigned i = 0; i < NumConcat - 1; ++i)
13316               Hints.push_back(FixItHint::CreateInsertion(
13317                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13318 
13319             Diag(SL->getStrTokenLoc(1),
13320                  diag::warn_concatenated_literal_array_init)
13321                 << Hints;
13322             Diag(SL->getBeginLoc(),
13323                  diag::note_concatenated_string_literal_silence);
13324           }
13325           // In any case, stop now.
13326           break;
13327         }
13328       }
13329   }
13330 
13331 
13332   QualType type = var->getType();
13333 
13334   if (var->hasAttr<BlocksAttr>())
13335     getCurFunction()->addByrefBlockVar(var);
13336 
13337   Expr *Init = var->getInit();
13338   bool GlobalStorage = var->hasGlobalStorage();
13339   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13340   QualType baseType = Context.getBaseElementType(type);
13341   bool HasConstInit = true;
13342 
13343   // Check whether the initializer is sufficiently constant.
13344   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13345       !Init->isValueDependent() &&
13346       (GlobalStorage || var->isConstexpr() ||
13347        var->mightBeUsableInConstantExpressions(Context))) {
13348     // If this variable might have a constant initializer or might be usable in
13349     // constant expressions, check whether or not it actually is now.  We can't
13350     // do this lazily, because the result might depend on things that change
13351     // later, such as which constexpr functions happen to be defined.
13352     SmallVector<PartialDiagnosticAt, 8> Notes;
13353     if (!getLangOpts().CPlusPlus11) {
13354       // Prior to C++11, in contexts where a constant initializer is required,
13355       // the set of valid constant initializers is described by syntactic rules
13356       // in [expr.const]p2-6.
13357       // FIXME: Stricter checking for these rules would be useful for constinit /
13358       // -Wglobal-constructors.
13359       HasConstInit = checkConstInit();
13360 
13361       // Compute and cache the constant value, and remember that we have a
13362       // constant initializer.
13363       if (HasConstInit) {
13364         (void)var->checkForConstantInitialization(Notes);
13365         Notes.clear();
13366       } else if (CacheCulprit) {
13367         Notes.emplace_back(CacheCulprit->getExprLoc(),
13368                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13369         Notes.back().second << CacheCulprit->getSourceRange();
13370       }
13371     } else {
13372       // Evaluate the initializer to see if it's a constant initializer.
13373       HasConstInit = var->checkForConstantInitialization(Notes);
13374     }
13375 
13376     if (HasConstInit) {
13377       // FIXME: Consider replacing the initializer with a ConstantExpr.
13378     } else if (var->isConstexpr()) {
13379       SourceLocation DiagLoc = var->getLocation();
13380       // If the note doesn't add any useful information other than a source
13381       // location, fold it into the primary diagnostic.
13382       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13383                                    diag::note_invalid_subexpr_in_const_expr) {
13384         DiagLoc = Notes[0].first;
13385         Notes.clear();
13386       }
13387       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13388           << var << Init->getSourceRange();
13389       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13390         Diag(Notes[I].first, Notes[I].second);
13391     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13392       auto *Attr = var->getAttr<ConstInitAttr>();
13393       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13394           << Init->getSourceRange();
13395       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13396           << Attr->getRange() << Attr->isConstinit();
13397       for (auto &it : Notes)
13398         Diag(it.first, it.second);
13399     } else if (IsGlobal &&
13400                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13401                                            var->getLocation())) {
13402       // Warn about globals which don't have a constant initializer.  Don't
13403       // warn about globals with a non-trivial destructor because we already
13404       // warned about them.
13405       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13406       if (!(RD && !RD->hasTrivialDestructor())) {
13407         // checkConstInit() here permits trivial default initialization even in
13408         // C++11 onwards, where such an initializer is not a constant initializer
13409         // but nonetheless doesn't require a global constructor.
13410         if (!checkConstInit())
13411           Diag(var->getLocation(), diag::warn_global_constructor)
13412               << Init->getSourceRange();
13413       }
13414     }
13415   }
13416 
13417   // Apply section attributes and pragmas to global variables.
13418   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13419       !inTemplateInstantiation()) {
13420     PragmaStack<StringLiteral *> *Stack = nullptr;
13421     int SectionFlags = ASTContext::PSF_Read;
13422     if (var->getType().isConstQualified()) {
13423       if (HasConstInit)
13424         Stack = &ConstSegStack;
13425       else {
13426         Stack = &BSSSegStack;
13427         SectionFlags |= ASTContext::PSF_Write;
13428       }
13429     } else if (var->hasInit() && HasConstInit) {
13430       Stack = &DataSegStack;
13431       SectionFlags |= ASTContext::PSF_Write;
13432     } else {
13433       Stack = &BSSSegStack;
13434       SectionFlags |= ASTContext::PSF_Write;
13435     }
13436     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13437       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13438         SectionFlags |= ASTContext::PSF_Implicit;
13439       UnifySection(SA->getName(), SectionFlags, var);
13440     } else if (Stack->CurrentValue) {
13441       SectionFlags |= ASTContext::PSF_Implicit;
13442       auto SectionName = Stack->CurrentValue->getString();
13443       var->addAttr(SectionAttr::CreateImplicit(
13444           Context, SectionName, Stack->CurrentPragmaLocation,
13445           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13446       if (UnifySection(SectionName, SectionFlags, var))
13447         var->dropAttr<SectionAttr>();
13448     }
13449 
13450     // Apply the init_seg attribute if this has an initializer.  If the
13451     // initializer turns out to not be dynamic, we'll end up ignoring this
13452     // attribute.
13453     if (CurInitSeg && var->getInit())
13454       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13455                                                CurInitSegLoc,
13456                                                AttributeCommonInfo::AS_Pragma));
13457   }
13458 
13459   // All the following checks are C++ only.
13460   if (!getLangOpts().CPlusPlus) {
13461     // If this variable must be emitted, add it as an initializer for the
13462     // current module.
13463     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13464       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13465     return;
13466   }
13467 
13468   // Require the destructor.
13469   if (!type->isDependentType())
13470     if (const RecordType *recordType = baseType->getAs<RecordType>())
13471       FinalizeVarWithDestructor(var, recordType);
13472 
13473   // If this variable must be emitted, add it as an initializer for the current
13474   // module.
13475   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13476     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13477 
13478   // Build the bindings if this is a structured binding declaration.
13479   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13480     CheckCompleteDecompositionDeclaration(DD);
13481 }
13482 
13483 /// Check if VD needs to be dllexport/dllimport due to being in a
13484 /// dllexport/import function.
13485 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13486   assert(VD->isStaticLocal());
13487 
13488   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13489 
13490   // Find outermost function when VD is in lambda function.
13491   while (FD && !getDLLAttr(FD) &&
13492          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13493          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13494     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13495   }
13496 
13497   if (!FD)
13498     return;
13499 
13500   // Static locals inherit dll attributes from their function.
13501   if (Attr *A = getDLLAttr(FD)) {
13502     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13503     NewAttr->setInherited(true);
13504     VD->addAttr(NewAttr);
13505   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13506     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13507     NewAttr->setInherited(true);
13508     VD->addAttr(NewAttr);
13509 
13510     // Export this function to enforce exporting this static variable even
13511     // if it is not used in this compilation unit.
13512     if (!FD->hasAttr<DLLExportAttr>())
13513       FD->addAttr(NewAttr);
13514 
13515   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13516     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13517     NewAttr->setInherited(true);
13518     VD->addAttr(NewAttr);
13519   }
13520 }
13521 
13522 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13523 /// any semantic actions necessary after any initializer has been attached.
13524 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13525   // Note that we are no longer parsing the initializer for this declaration.
13526   ParsingInitForAutoVars.erase(ThisDecl);
13527 
13528   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13529   if (!VD)
13530     return;
13531 
13532   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13533   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13534       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13535     if (PragmaClangBSSSection.Valid)
13536       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13537           Context, PragmaClangBSSSection.SectionName,
13538           PragmaClangBSSSection.PragmaLocation,
13539           AttributeCommonInfo::AS_Pragma));
13540     if (PragmaClangDataSection.Valid)
13541       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13542           Context, PragmaClangDataSection.SectionName,
13543           PragmaClangDataSection.PragmaLocation,
13544           AttributeCommonInfo::AS_Pragma));
13545     if (PragmaClangRodataSection.Valid)
13546       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13547           Context, PragmaClangRodataSection.SectionName,
13548           PragmaClangRodataSection.PragmaLocation,
13549           AttributeCommonInfo::AS_Pragma));
13550     if (PragmaClangRelroSection.Valid)
13551       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13552           Context, PragmaClangRelroSection.SectionName,
13553           PragmaClangRelroSection.PragmaLocation,
13554           AttributeCommonInfo::AS_Pragma));
13555   }
13556 
13557   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13558     for (auto *BD : DD->bindings()) {
13559       FinalizeDeclaration(BD);
13560     }
13561   }
13562 
13563   checkAttributesAfterMerging(*this, *VD);
13564 
13565   // Perform TLS alignment check here after attributes attached to the variable
13566   // which may affect the alignment have been processed. Only perform the check
13567   // if the target has a maximum TLS alignment (zero means no constraints).
13568   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13569     // Protect the check so that it's not performed on dependent types and
13570     // dependent alignments (we can't determine the alignment in that case).
13571     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13572       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13573       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13574         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13575           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13576           << (unsigned)MaxAlignChars.getQuantity();
13577       }
13578     }
13579   }
13580 
13581   if (VD->isStaticLocal())
13582     CheckStaticLocalForDllExport(VD);
13583 
13584   // Perform check for initializers of device-side global variables.
13585   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13586   // 7.5). We must also apply the same checks to all __shared__
13587   // variables whether they are local or not. CUDA also allows
13588   // constant initializers for __constant__ and __device__ variables.
13589   if (getLangOpts().CUDA)
13590     checkAllowedCUDAInitializer(VD);
13591 
13592   // Grab the dllimport or dllexport attribute off of the VarDecl.
13593   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13594 
13595   // Imported static data members cannot be defined out-of-line.
13596   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13597     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13598         VD->isThisDeclarationADefinition()) {
13599       // We allow definitions of dllimport class template static data members
13600       // with a warning.
13601       CXXRecordDecl *Context =
13602         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13603       bool IsClassTemplateMember =
13604           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13605           Context->getDescribedClassTemplate();
13606 
13607       Diag(VD->getLocation(),
13608            IsClassTemplateMember
13609                ? diag::warn_attribute_dllimport_static_field_definition
13610                : diag::err_attribute_dllimport_static_field_definition);
13611       Diag(IA->getLocation(), diag::note_attribute);
13612       if (!IsClassTemplateMember)
13613         VD->setInvalidDecl();
13614     }
13615   }
13616 
13617   // dllimport/dllexport variables cannot be thread local, their TLS index
13618   // isn't exported with the variable.
13619   if (DLLAttr && VD->getTLSKind()) {
13620     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13621     if (F && getDLLAttr(F)) {
13622       assert(VD->isStaticLocal());
13623       // But if this is a static local in a dlimport/dllexport function, the
13624       // function will never be inlined, which means the var would never be
13625       // imported, so having it marked import/export is safe.
13626     } else {
13627       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13628                                                                     << DLLAttr;
13629       VD->setInvalidDecl();
13630     }
13631   }
13632 
13633   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13634     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13635       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13636           << Attr;
13637       VD->dropAttr<UsedAttr>();
13638     }
13639   }
13640   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13641     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13642       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13643           << Attr;
13644       VD->dropAttr<RetainAttr>();
13645     }
13646   }
13647 
13648   const DeclContext *DC = VD->getDeclContext();
13649   // If there's a #pragma GCC visibility in scope, and this isn't a class
13650   // member, set the visibility of this variable.
13651   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13652     AddPushedVisibilityAttribute(VD);
13653 
13654   // FIXME: Warn on unused var template partial specializations.
13655   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13656     MarkUnusedFileScopedDecl(VD);
13657 
13658   // Now we have parsed the initializer and can update the table of magic
13659   // tag values.
13660   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13661       !VD->getType()->isIntegralOrEnumerationType())
13662     return;
13663 
13664   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13665     const Expr *MagicValueExpr = VD->getInit();
13666     if (!MagicValueExpr) {
13667       continue;
13668     }
13669     Optional<llvm::APSInt> MagicValueInt;
13670     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13671       Diag(I->getRange().getBegin(),
13672            diag::err_type_tag_for_datatype_not_ice)
13673         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13674       continue;
13675     }
13676     if (MagicValueInt->getActiveBits() > 64) {
13677       Diag(I->getRange().getBegin(),
13678            diag::err_type_tag_for_datatype_too_large)
13679         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13680       continue;
13681     }
13682     uint64_t MagicValue = MagicValueInt->getZExtValue();
13683     RegisterTypeTagForDatatype(I->getArgumentKind(),
13684                                MagicValue,
13685                                I->getMatchingCType(),
13686                                I->getLayoutCompatible(),
13687                                I->getMustBeNull());
13688   }
13689 }
13690 
13691 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13692   auto *VD = dyn_cast<VarDecl>(DD);
13693   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13694 }
13695 
13696 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13697                                                    ArrayRef<Decl *> Group) {
13698   SmallVector<Decl*, 8> Decls;
13699 
13700   if (DS.isTypeSpecOwned())
13701     Decls.push_back(DS.getRepAsDecl());
13702 
13703   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13704   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13705   bool DiagnosedMultipleDecomps = false;
13706   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13707   bool DiagnosedNonDeducedAuto = false;
13708 
13709   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13710     if (Decl *D = Group[i]) {
13711       // For declarators, there are some additional syntactic-ish checks we need
13712       // to perform.
13713       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13714         if (!FirstDeclaratorInGroup)
13715           FirstDeclaratorInGroup = DD;
13716         if (!FirstDecompDeclaratorInGroup)
13717           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13718         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13719             !hasDeducedAuto(DD))
13720           FirstNonDeducedAutoInGroup = DD;
13721 
13722         if (FirstDeclaratorInGroup != DD) {
13723           // A decomposition declaration cannot be combined with any other
13724           // declaration in the same group.
13725           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13726             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13727                  diag::err_decomp_decl_not_alone)
13728                 << FirstDeclaratorInGroup->getSourceRange()
13729                 << DD->getSourceRange();
13730             DiagnosedMultipleDecomps = true;
13731           }
13732 
13733           // A declarator that uses 'auto' in any way other than to declare a
13734           // variable with a deduced type cannot be combined with any other
13735           // declarator in the same group.
13736           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13737             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13738                  diag::err_auto_non_deduced_not_alone)
13739                 << FirstNonDeducedAutoInGroup->getType()
13740                        ->hasAutoForTrailingReturnType()
13741                 << FirstDeclaratorInGroup->getSourceRange()
13742                 << DD->getSourceRange();
13743             DiagnosedNonDeducedAuto = true;
13744           }
13745         }
13746       }
13747 
13748       Decls.push_back(D);
13749     }
13750   }
13751 
13752   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13753     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13754       handleTagNumbering(Tag, S);
13755       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13756           getLangOpts().CPlusPlus)
13757         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13758     }
13759   }
13760 
13761   return BuildDeclaratorGroup(Decls);
13762 }
13763 
13764 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13765 /// group, performing any necessary semantic checking.
13766 Sema::DeclGroupPtrTy
13767 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13768   // C++14 [dcl.spec.auto]p7: (DR1347)
13769   //   If the type that replaces the placeholder type is not the same in each
13770   //   deduction, the program is ill-formed.
13771   if (Group.size() > 1) {
13772     QualType Deduced;
13773     VarDecl *DeducedDecl = nullptr;
13774     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13775       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13776       if (!D || D->isInvalidDecl())
13777         break;
13778       DeducedType *DT = D->getType()->getContainedDeducedType();
13779       if (!DT || DT->getDeducedType().isNull())
13780         continue;
13781       if (Deduced.isNull()) {
13782         Deduced = DT->getDeducedType();
13783         DeducedDecl = D;
13784       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13785         auto *AT = dyn_cast<AutoType>(DT);
13786         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13787                         diag::err_auto_different_deductions)
13788                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13789                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13790                    << D->getDeclName();
13791         if (DeducedDecl->hasInit())
13792           Dia << DeducedDecl->getInit()->getSourceRange();
13793         if (D->getInit())
13794           Dia << D->getInit()->getSourceRange();
13795         D->setInvalidDecl();
13796         break;
13797       }
13798     }
13799   }
13800 
13801   ActOnDocumentableDecls(Group);
13802 
13803   return DeclGroupPtrTy::make(
13804       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13805 }
13806 
13807 void Sema::ActOnDocumentableDecl(Decl *D) {
13808   ActOnDocumentableDecls(D);
13809 }
13810 
13811 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13812   // Don't parse the comment if Doxygen diagnostics are ignored.
13813   if (Group.empty() || !Group[0])
13814     return;
13815 
13816   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13817                       Group[0]->getLocation()) &&
13818       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13819                       Group[0]->getLocation()))
13820     return;
13821 
13822   if (Group.size() >= 2) {
13823     // This is a decl group.  Normally it will contain only declarations
13824     // produced from declarator list.  But in case we have any definitions or
13825     // additional declaration references:
13826     //   'typedef struct S {} S;'
13827     //   'typedef struct S *S;'
13828     //   'struct S *pS;'
13829     // FinalizeDeclaratorGroup adds these as separate declarations.
13830     Decl *MaybeTagDecl = Group[0];
13831     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13832       Group = Group.slice(1);
13833     }
13834   }
13835 
13836   // FIMXE: We assume every Decl in the group is in the same file.
13837   // This is false when preprocessor constructs the group from decls in
13838   // different files (e. g. macros or #include).
13839   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13840 }
13841 
13842 /// Common checks for a parameter-declaration that should apply to both function
13843 /// parameters and non-type template parameters.
13844 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13845   // Check that there are no default arguments inside the type of this
13846   // parameter.
13847   if (getLangOpts().CPlusPlus)
13848     CheckExtraCXXDefaultArguments(D);
13849 
13850   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13851   if (D.getCXXScopeSpec().isSet()) {
13852     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13853       << D.getCXXScopeSpec().getRange();
13854   }
13855 
13856   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13857   // simple identifier except [...irrelevant cases...].
13858   switch (D.getName().getKind()) {
13859   case UnqualifiedIdKind::IK_Identifier:
13860     break;
13861 
13862   case UnqualifiedIdKind::IK_OperatorFunctionId:
13863   case UnqualifiedIdKind::IK_ConversionFunctionId:
13864   case UnqualifiedIdKind::IK_LiteralOperatorId:
13865   case UnqualifiedIdKind::IK_ConstructorName:
13866   case UnqualifiedIdKind::IK_DestructorName:
13867   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13868   case UnqualifiedIdKind::IK_DeductionGuideName:
13869     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13870       << GetNameForDeclarator(D).getName();
13871     break;
13872 
13873   case UnqualifiedIdKind::IK_TemplateId:
13874   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13875     // GetNameForDeclarator would not produce a useful name in this case.
13876     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13877     break;
13878   }
13879 }
13880 
13881 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13882 /// to introduce parameters into function prototype scope.
13883 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13884   const DeclSpec &DS = D.getDeclSpec();
13885 
13886   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13887 
13888   // C++03 [dcl.stc]p2 also permits 'auto'.
13889   StorageClass SC = SC_None;
13890   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13891     SC = SC_Register;
13892     // In C++11, the 'register' storage class specifier is deprecated.
13893     // In C++17, it is not allowed, but we tolerate it as an extension.
13894     if (getLangOpts().CPlusPlus11) {
13895       Diag(DS.getStorageClassSpecLoc(),
13896            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13897                                      : diag::warn_deprecated_register)
13898         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13899     }
13900   } else if (getLangOpts().CPlusPlus &&
13901              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13902     SC = SC_Auto;
13903   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13904     Diag(DS.getStorageClassSpecLoc(),
13905          diag::err_invalid_storage_class_in_func_decl);
13906     D.getMutableDeclSpec().ClearStorageClassSpecs();
13907   }
13908 
13909   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13910     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13911       << DeclSpec::getSpecifierName(TSCS);
13912   if (DS.isInlineSpecified())
13913     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13914         << getLangOpts().CPlusPlus17;
13915   if (DS.hasConstexprSpecifier())
13916     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13917         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13918 
13919   DiagnoseFunctionSpecifiers(DS);
13920 
13921   CheckFunctionOrTemplateParamDeclarator(S, D);
13922 
13923   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13924   QualType parmDeclType = TInfo->getType();
13925 
13926   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13927   IdentifierInfo *II = D.getIdentifier();
13928   if (II) {
13929     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13930                    ForVisibleRedeclaration);
13931     LookupName(R, S);
13932     if (R.isSingleResult()) {
13933       NamedDecl *PrevDecl = R.getFoundDecl();
13934       if (PrevDecl->isTemplateParameter()) {
13935         // Maybe we will complain about the shadowed template parameter.
13936         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13937         // Just pretend that we didn't see the previous declaration.
13938         PrevDecl = nullptr;
13939       } else if (S->isDeclScope(PrevDecl)) {
13940         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13941         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13942 
13943         // Recover by removing the name
13944         II = nullptr;
13945         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13946         D.setInvalidType(true);
13947       }
13948     }
13949   }
13950 
13951   // Temporarily put parameter variables in the translation unit, not
13952   // the enclosing context.  This prevents them from accidentally
13953   // looking like class members in C++.
13954   ParmVarDecl *New =
13955       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13956                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13957 
13958   if (D.isInvalidType())
13959     New->setInvalidDecl();
13960 
13961   assert(S->isFunctionPrototypeScope());
13962   assert(S->getFunctionPrototypeDepth() >= 1);
13963   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13964                     S->getNextFunctionPrototypeIndex());
13965 
13966   // Add the parameter declaration into this scope.
13967   S->AddDecl(New);
13968   if (II)
13969     IdResolver.AddDecl(New);
13970 
13971   ProcessDeclAttributes(S, New, D);
13972 
13973   if (D.getDeclSpec().isModulePrivateSpecified())
13974     Diag(New->getLocation(), diag::err_module_private_local)
13975         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13976         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13977 
13978   if (New->hasAttr<BlocksAttr>()) {
13979     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13980   }
13981 
13982   if (getLangOpts().OpenCL)
13983     deduceOpenCLAddressSpace(New);
13984 
13985   return New;
13986 }
13987 
13988 /// Synthesizes a variable for a parameter arising from a
13989 /// typedef.
13990 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13991                                               SourceLocation Loc,
13992                                               QualType T) {
13993   /* FIXME: setting StartLoc == Loc.
13994      Would it be worth to modify callers so as to provide proper source
13995      location for the unnamed parameters, embedding the parameter's type? */
13996   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13997                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13998                                            SC_None, nullptr);
13999   Param->setImplicit();
14000   return Param;
14001 }
14002 
14003 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14004   // Don't diagnose unused-parameter errors in template instantiations; we
14005   // will already have done so in the template itself.
14006   if (inTemplateInstantiation())
14007     return;
14008 
14009   for (const ParmVarDecl *Parameter : Parameters) {
14010     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14011         !Parameter->hasAttr<UnusedAttr>()) {
14012       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14013         << Parameter->getDeclName();
14014     }
14015   }
14016 }
14017 
14018 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14019     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14020   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14021     return;
14022 
14023   // Warn if the return value is pass-by-value and larger than the specified
14024   // threshold.
14025   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14026     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14027     if (Size > LangOpts.NumLargeByValueCopy)
14028       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14029   }
14030 
14031   // Warn if any parameter is pass-by-value and larger than the specified
14032   // threshold.
14033   for (const ParmVarDecl *Parameter : Parameters) {
14034     QualType T = Parameter->getType();
14035     if (T->isDependentType() || !T.isPODType(Context))
14036       continue;
14037     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14038     if (Size > LangOpts.NumLargeByValueCopy)
14039       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14040           << Parameter << Size;
14041   }
14042 }
14043 
14044 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14045                                   SourceLocation NameLoc, IdentifierInfo *Name,
14046                                   QualType T, TypeSourceInfo *TSInfo,
14047                                   StorageClass SC) {
14048   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14049   if (getLangOpts().ObjCAutoRefCount &&
14050       T.getObjCLifetime() == Qualifiers::OCL_None &&
14051       T->isObjCLifetimeType()) {
14052 
14053     Qualifiers::ObjCLifetime lifetime;
14054 
14055     // Special cases for arrays:
14056     //   - if it's const, use __unsafe_unretained
14057     //   - otherwise, it's an error
14058     if (T->isArrayType()) {
14059       if (!T.isConstQualified()) {
14060         if (DelayedDiagnostics.shouldDelayDiagnostics())
14061           DelayedDiagnostics.add(
14062               sema::DelayedDiagnostic::makeForbiddenType(
14063               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14064         else
14065           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14066               << TSInfo->getTypeLoc().getSourceRange();
14067       }
14068       lifetime = Qualifiers::OCL_ExplicitNone;
14069     } else {
14070       lifetime = T->getObjCARCImplicitLifetime();
14071     }
14072     T = Context.getLifetimeQualifiedType(T, lifetime);
14073   }
14074 
14075   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14076                                          Context.getAdjustedParameterType(T),
14077                                          TSInfo, SC, nullptr);
14078 
14079   // Make a note if we created a new pack in the scope of a lambda, so that
14080   // we know that references to that pack must also be expanded within the
14081   // lambda scope.
14082   if (New->isParameterPack())
14083     if (auto *LSI = getEnclosingLambda())
14084       LSI->LocalPacks.push_back(New);
14085 
14086   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14087       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14088     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14089                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14090 
14091   // Parameters can not be abstract class types.
14092   // For record types, this is done by the AbstractClassUsageDiagnoser once
14093   // the class has been completely parsed.
14094   if (!CurContext->isRecord() &&
14095       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14096                              AbstractParamType))
14097     New->setInvalidDecl();
14098 
14099   // Parameter declarators cannot be interface types. All ObjC objects are
14100   // passed by reference.
14101   if (T->isObjCObjectType()) {
14102     SourceLocation TypeEndLoc =
14103         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14104     Diag(NameLoc,
14105          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14106       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14107     T = Context.getObjCObjectPointerType(T);
14108     New->setType(T);
14109   }
14110 
14111   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14112   // duration shall not be qualified by an address-space qualifier."
14113   // Since all parameters have automatic store duration, they can not have
14114   // an address space.
14115   if (T.getAddressSpace() != LangAS::Default &&
14116       // OpenCL allows function arguments declared to be an array of a type
14117       // to be qualified with an address space.
14118       !(getLangOpts().OpenCL &&
14119         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14120     Diag(NameLoc, diag::err_arg_with_address_space);
14121     New->setInvalidDecl();
14122   }
14123 
14124   // PPC MMA non-pointer types are not allowed as function argument types.
14125   if (Context.getTargetInfo().getTriple().isPPC64() &&
14126       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14127     New->setInvalidDecl();
14128   }
14129 
14130   return New;
14131 }
14132 
14133 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14134                                            SourceLocation LocAfterDecls) {
14135   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14136 
14137   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14138   // for a K&R function.
14139   if (!FTI.hasPrototype) {
14140     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14141       --i;
14142       if (FTI.Params[i].Param == nullptr) {
14143         SmallString<256> Code;
14144         llvm::raw_svector_ostream(Code)
14145             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14146         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14147             << FTI.Params[i].Ident
14148             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14149 
14150         // Implicitly declare the argument as type 'int' for lack of a better
14151         // type.
14152         AttributeFactory attrs;
14153         DeclSpec DS(attrs);
14154         const char* PrevSpec; // unused
14155         unsigned DiagID; // unused
14156         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14157                            DiagID, Context.getPrintingPolicy());
14158         // Use the identifier location for the type source range.
14159         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14160         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14161         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14162         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14163         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14164       }
14165     }
14166   }
14167 }
14168 
14169 Decl *
14170 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14171                               MultiTemplateParamsArg TemplateParameterLists,
14172                               SkipBodyInfo *SkipBody) {
14173   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14174   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14175   Scope *ParentScope = FnBodyScope->getParent();
14176 
14177   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14178   // we define a non-templated function definition, we will create a declaration
14179   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14180   // The base function declaration will have the equivalent of an `omp declare
14181   // variant` annotation which specifies the mangled definition as a
14182   // specialization function under the OpenMP context defined as part of the
14183   // `omp begin declare variant`.
14184   SmallVector<FunctionDecl *, 4> Bases;
14185   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14186     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14187         ParentScope, D, TemplateParameterLists, Bases);
14188 
14189   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14190   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14191   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14192 
14193   if (!Bases.empty())
14194     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14195 
14196   return Dcl;
14197 }
14198 
14199 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14200   Consumer.HandleInlineFunctionDefinition(D);
14201 }
14202 
14203 static bool
14204 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14205                                 const FunctionDecl *&PossiblePrototype) {
14206   // Don't warn about invalid declarations.
14207   if (FD->isInvalidDecl())
14208     return false;
14209 
14210   // Or declarations that aren't global.
14211   if (!FD->isGlobal())
14212     return false;
14213 
14214   // Don't warn about C++ member functions.
14215   if (isa<CXXMethodDecl>(FD))
14216     return false;
14217 
14218   // Don't warn about 'main'.
14219   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14220     if (IdentifierInfo *II = FD->getIdentifier())
14221       if (II->isStr("main") || II->isStr("efi_main"))
14222         return false;
14223 
14224   // Don't warn about inline functions.
14225   if (FD->isInlined())
14226     return false;
14227 
14228   // Don't warn about function templates.
14229   if (FD->getDescribedFunctionTemplate())
14230     return false;
14231 
14232   // Don't warn about function template specializations.
14233   if (FD->isFunctionTemplateSpecialization())
14234     return false;
14235 
14236   // Don't warn for OpenCL kernels.
14237   if (FD->hasAttr<OpenCLKernelAttr>())
14238     return false;
14239 
14240   // Don't warn on explicitly deleted functions.
14241   if (FD->isDeleted())
14242     return false;
14243 
14244   // Don't warn on implicitly local functions (such as having local-typed
14245   // parameters).
14246   if (!FD->isExternallyVisible())
14247     return false;
14248 
14249   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14250        Prev; Prev = Prev->getPreviousDecl()) {
14251     // Ignore any declarations that occur in function or method
14252     // scope, because they aren't visible from the header.
14253     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14254       continue;
14255 
14256     PossiblePrototype = Prev;
14257     return Prev->getType()->isFunctionNoProtoType();
14258   }
14259 
14260   return true;
14261 }
14262 
14263 void
14264 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14265                                    const FunctionDecl *EffectiveDefinition,
14266                                    SkipBodyInfo *SkipBody) {
14267   const FunctionDecl *Definition = EffectiveDefinition;
14268   if (!Definition &&
14269       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14270     return;
14271 
14272   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14273     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14274       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14275         // A merged copy of the same function, instantiated as a member of
14276         // the same class, is OK.
14277         if (declaresSameEntity(OrigFD, OrigDef) &&
14278             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14279                                cast<Decl>(FD->getLexicalDeclContext())))
14280           return;
14281       }
14282     }
14283   }
14284 
14285   if (canRedefineFunction(Definition, getLangOpts()))
14286     return;
14287 
14288   // Don't emit an error when this is redefinition of a typo-corrected
14289   // definition.
14290   if (TypoCorrectedFunctionDefinitions.count(Definition))
14291     return;
14292 
14293   // If we don't have a visible definition of the function, and it's inline or
14294   // a template, skip the new definition.
14295   if (SkipBody && !hasVisibleDefinition(Definition) &&
14296       (Definition->getFormalLinkage() == InternalLinkage ||
14297        Definition->isInlined() ||
14298        Definition->getDescribedFunctionTemplate() ||
14299        Definition->getNumTemplateParameterLists())) {
14300     SkipBody->ShouldSkip = true;
14301     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14302     if (auto *TD = Definition->getDescribedFunctionTemplate())
14303       makeMergedDefinitionVisible(TD);
14304     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14305     return;
14306   }
14307 
14308   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14309       Definition->getStorageClass() == SC_Extern)
14310     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14311         << FD << getLangOpts().CPlusPlus;
14312   else
14313     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14314 
14315   Diag(Definition->getLocation(), diag::note_previous_definition);
14316   FD->setInvalidDecl();
14317 }
14318 
14319 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14320                                    Sema &S) {
14321   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14322 
14323   LambdaScopeInfo *LSI = S.PushLambdaScope();
14324   LSI->CallOperator = CallOperator;
14325   LSI->Lambda = LambdaClass;
14326   LSI->ReturnType = CallOperator->getReturnType();
14327   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14328 
14329   if (LCD == LCD_None)
14330     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14331   else if (LCD == LCD_ByCopy)
14332     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14333   else if (LCD == LCD_ByRef)
14334     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14335   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14336 
14337   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14338   LSI->Mutable = !CallOperator->isConst();
14339 
14340   // Add the captures to the LSI so they can be noted as already
14341   // captured within tryCaptureVar.
14342   auto I = LambdaClass->field_begin();
14343   for (const auto &C : LambdaClass->captures()) {
14344     if (C.capturesVariable()) {
14345       VarDecl *VD = C.getCapturedVar();
14346       if (VD->isInitCapture())
14347         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14348       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14349       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14350           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14351           /*EllipsisLoc*/C.isPackExpansion()
14352                          ? C.getEllipsisLoc() : SourceLocation(),
14353           I->getType(), /*Invalid*/false);
14354 
14355     } else if (C.capturesThis()) {
14356       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14357                           C.getCaptureKind() == LCK_StarThis);
14358     } else {
14359       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14360                              I->getType());
14361     }
14362     ++I;
14363   }
14364 }
14365 
14366 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14367                                     SkipBodyInfo *SkipBody) {
14368   if (!D) {
14369     // Parsing the function declaration failed in some way. Push on a fake scope
14370     // anyway so we can try to parse the function body.
14371     PushFunctionScope();
14372     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14373     return D;
14374   }
14375 
14376   FunctionDecl *FD = nullptr;
14377 
14378   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14379     FD = FunTmpl->getTemplatedDecl();
14380   else
14381     FD = cast<FunctionDecl>(D);
14382 
14383   // Do not push if it is a lambda because one is already pushed when building
14384   // the lambda in ActOnStartOfLambdaDefinition().
14385   if (!isLambdaCallOperator(FD))
14386     PushExpressionEvaluationContext(
14387         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14388                           : ExprEvalContexts.back().Context);
14389 
14390   // Check for defining attributes before the check for redefinition.
14391   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14392     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14393     FD->dropAttr<AliasAttr>();
14394     FD->setInvalidDecl();
14395   }
14396   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14397     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14398     FD->dropAttr<IFuncAttr>();
14399     FD->setInvalidDecl();
14400   }
14401 
14402   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14403     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14404         Ctor->isDefaultConstructor() &&
14405         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14406       // If this is an MS ABI dllexport default constructor, instantiate any
14407       // default arguments.
14408       InstantiateDefaultCtorDefaultArgs(Ctor);
14409     }
14410   }
14411 
14412   // See if this is a redefinition. If 'will have body' (or similar) is already
14413   // set, then these checks were already performed when it was set.
14414   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14415       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14416     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14417 
14418     // If we're skipping the body, we're done. Don't enter the scope.
14419     if (SkipBody && SkipBody->ShouldSkip)
14420       return D;
14421   }
14422 
14423   // Mark this function as "will have a body eventually".  This lets users to
14424   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14425   // this function.
14426   FD->setWillHaveBody();
14427 
14428   // If we are instantiating a generic lambda call operator, push
14429   // a LambdaScopeInfo onto the function stack.  But use the information
14430   // that's already been calculated (ActOnLambdaExpr) to prime the current
14431   // LambdaScopeInfo.
14432   // When the template operator is being specialized, the LambdaScopeInfo,
14433   // has to be properly restored so that tryCaptureVariable doesn't try
14434   // and capture any new variables. In addition when calculating potential
14435   // captures during transformation of nested lambdas, it is necessary to
14436   // have the LSI properly restored.
14437   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14438     assert(inTemplateInstantiation() &&
14439            "There should be an active template instantiation on the stack "
14440            "when instantiating a generic lambda!");
14441     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14442   } else {
14443     // Enter a new function scope
14444     PushFunctionScope();
14445   }
14446 
14447   // Builtin functions cannot be defined.
14448   if (unsigned BuiltinID = FD->getBuiltinID()) {
14449     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14450         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14451       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14452       FD->setInvalidDecl();
14453     }
14454   }
14455 
14456   // The return type of a function definition must be complete
14457   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14458   QualType ResultType = FD->getReturnType();
14459   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14460       !FD->isInvalidDecl() &&
14461       RequireCompleteType(FD->getLocation(), ResultType,
14462                           diag::err_func_def_incomplete_result))
14463     FD->setInvalidDecl();
14464 
14465   if (FnBodyScope)
14466     PushDeclContext(FnBodyScope, FD);
14467 
14468   // Check the validity of our function parameters
14469   CheckParmsForFunctionDef(FD->parameters(),
14470                            /*CheckParameterNames=*/true);
14471 
14472   // Add non-parameter declarations already in the function to the current
14473   // scope.
14474   if (FnBodyScope) {
14475     for (Decl *NPD : FD->decls()) {
14476       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14477       if (!NonParmDecl)
14478         continue;
14479       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14480              "parameters should not be in newly created FD yet");
14481 
14482       // If the decl has a name, make it accessible in the current scope.
14483       if (NonParmDecl->getDeclName())
14484         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14485 
14486       // Similarly, dive into enums and fish their constants out, making them
14487       // accessible in this scope.
14488       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14489         for (auto *EI : ED->enumerators())
14490           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14491       }
14492     }
14493   }
14494 
14495   // Introduce our parameters into the function scope
14496   for (auto Param : FD->parameters()) {
14497     Param->setOwningFunction(FD);
14498 
14499     // If this has an identifier, add it to the scope stack.
14500     if (Param->getIdentifier() && FnBodyScope) {
14501       CheckShadow(FnBodyScope, Param);
14502 
14503       PushOnScopeChains(Param, FnBodyScope);
14504     }
14505   }
14506 
14507   // Ensure that the function's exception specification is instantiated.
14508   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14509     ResolveExceptionSpec(D->getLocation(), FPT);
14510 
14511   // dllimport cannot be applied to non-inline function definitions.
14512   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14513       !FD->isTemplateInstantiation()) {
14514     assert(!FD->hasAttr<DLLExportAttr>());
14515     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14516     FD->setInvalidDecl();
14517     return D;
14518   }
14519   // We want to attach documentation to original Decl (which might be
14520   // a function template).
14521   ActOnDocumentableDecl(D);
14522   if (getCurLexicalContext()->isObjCContainer() &&
14523       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14524       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14525     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14526 
14527   return D;
14528 }
14529 
14530 /// Given the set of return statements within a function body,
14531 /// compute the variables that are subject to the named return value
14532 /// optimization.
14533 ///
14534 /// Each of the variables that is subject to the named return value
14535 /// optimization will be marked as NRVO variables in the AST, and any
14536 /// return statement that has a marked NRVO variable as its NRVO candidate can
14537 /// use the named return value optimization.
14538 ///
14539 /// This function applies a very simplistic algorithm for NRVO: if every return
14540 /// statement in the scope of a variable has the same NRVO candidate, that
14541 /// candidate is an NRVO variable.
14542 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14543   ReturnStmt **Returns = Scope->Returns.data();
14544 
14545   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14546     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14547       if (!NRVOCandidate->isNRVOVariable())
14548         Returns[I]->setNRVOCandidate(nullptr);
14549     }
14550   }
14551 }
14552 
14553 bool Sema::canDelayFunctionBody(const Declarator &D) {
14554   // We can't delay parsing the body of a constexpr function template (yet).
14555   if (D.getDeclSpec().hasConstexprSpecifier())
14556     return false;
14557 
14558   // We can't delay parsing the body of a function template with a deduced
14559   // return type (yet).
14560   if (D.getDeclSpec().hasAutoTypeSpec()) {
14561     // If the placeholder introduces a non-deduced trailing return type,
14562     // we can still delay parsing it.
14563     if (D.getNumTypeObjects()) {
14564       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14565       if (Outer.Kind == DeclaratorChunk::Function &&
14566           Outer.Fun.hasTrailingReturnType()) {
14567         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14568         return Ty.isNull() || !Ty->isUndeducedType();
14569       }
14570     }
14571     return false;
14572   }
14573 
14574   return true;
14575 }
14576 
14577 bool Sema::canSkipFunctionBody(Decl *D) {
14578   // We cannot skip the body of a function (or function template) which is
14579   // constexpr, since we may need to evaluate its body in order to parse the
14580   // rest of the file.
14581   // We cannot skip the body of a function with an undeduced return type,
14582   // because any callers of that function need to know the type.
14583   if (const FunctionDecl *FD = D->getAsFunction()) {
14584     if (FD->isConstexpr())
14585       return false;
14586     // We can't simply call Type::isUndeducedType here, because inside template
14587     // auto can be deduced to a dependent type, which is not considered
14588     // "undeduced".
14589     if (FD->getReturnType()->getContainedDeducedType())
14590       return false;
14591   }
14592   return Consumer.shouldSkipFunctionBody(D);
14593 }
14594 
14595 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14596   if (!Decl)
14597     return nullptr;
14598   if (FunctionDecl *FD = Decl->getAsFunction())
14599     FD->setHasSkippedBody();
14600   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14601     MD->setHasSkippedBody();
14602   return Decl;
14603 }
14604 
14605 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14606   return ActOnFinishFunctionBody(D, BodyArg, false);
14607 }
14608 
14609 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14610 /// body.
14611 class ExitFunctionBodyRAII {
14612 public:
14613   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14614   ~ExitFunctionBodyRAII() {
14615     if (!IsLambda)
14616       S.PopExpressionEvaluationContext();
14617   }
14618 
14619 private:
14620   Sema &S;
14621   bool IsLambda = false;
14622 };
14623 
14624 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14625   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14626 
14627   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14628     if (EscapeInfo.count(BD))
14629       return EscapeInfo[BD];
14630 
14631     bool R = false;
14632     const BlockDecl *CurBD = BD;
14633 
14634     do {
14635       R = !CurBD->doesNotEscape();
14636       if (R)
14637         break;
14638       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14639     } while (CurBD);
14640 
14641     return EscapeInfo[BD] = R;
14642   };
14643 
14644   // If the location where 'self' is implicitly retained is inside a escaping
14645   // block, emit a diagnostic.
14646   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14647        S.ImplicitlyRetainedSelfLocs)
14648     if (IsOrNestedInEscapingBlock(P.second))
14649       S.Diag(P.first, diag::warn_implicitly_retains_self)
14650           << FixItHint::CreateInsertion(P.first, "self->");
14651 }
14652 
14653 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14654                                     bool IsInstantiation) {
14655   FunctionScopeInfo *FSI = getCurFunction();
14656   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14657 
14658   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14659     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14660 
14661   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14662   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14663 
14664   if (getLangOpts().Coroutines && FSI->isCoroutine())
14665     CheckCompletedCoroutineBody(FD, Body);
14666 
14667   {
14668     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14669     // one is already popped when finishing the lambda in BuildLambdaExpr().
14670     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14671     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14672 
14673     if (FD) {
14674       FD->setBody(Body);
14675       FD->setWillHaveBody(false);
14676 
14677       if (getLangOpts().CPlusPlus14) {
14678         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14679             FD->getReturnType()->isUndeducedType()) {
14680           // For a function with a deduced result type to return void,
14681           // the result type as written must be 'auto' or 'decltype(auto)',
14682           // possibly cv-qualified or constrained, but not ref-qualified.
14683           if (!FD->getReturnType()->getAs<AutoType>()) {
14684             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14685                 << FD->getReturnType();
14686             FD->setInvalidDecl();
14687           } else {
14688             // Falling off the end of the function is the same as 'return;'.
14689             Expr *Dummy = nullptr;
14690             if (DeduceFunctionTypeFromReturnExpr(
14691                     FD, dcl->getLocation(), Dummy,
14692                     FD->getReturnType()->getAs<AutoType>()))
14693               FD->setInvalidDecl();
14694           }
14695         }
14696       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14697         // In C++11, we don't use 'auto' deduction rules for lambda call
14698         // operators because we don't support return type deduction.
14699         auto *LSI = getCurLambda();
14700         if (LSI->HasImplicitReturnType) {
14701           deduceClosureReturnType(*LSI);
14702 
14703           // C++11 [expr.prim.lambda]p4:
14704           //   [...] if there are no return statements in the compound-statement
14705           //   [the deduced type is] the type void
14706           QualType RetType =
14707               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14708 
14709           // Update the return type to the deduced type.
14710           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14711           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14712                                               Proto->getExtProtoInfo()));
14713         }
14714       }
14715 
14716       // If the function implicitly returns zero (like 'main') or is naked,
14717       // don't complain about missing return statements.
14718       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14719         WP.disableCheckFallThrough();
14720 
14721       // MSVC permits the use of pure specifier (=0) on function definition,
14722       // defined at class scope, warn about this non-standard construct.
14723       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14724         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14725 
14726       if (!FD->isInvalidDecl()) {
14727         // Don't diagnose unused parameters of defaulted, deleted or naked
14728         // functions.
14729         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14730             !FD->hasAttr<NakedAttr>())
14731           DiagnoseUnusedParameters(FD->parameters());
14732         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14733                                                FD->getReturnType(), FD);
14734 
14735         // If this is a structor, we need a vtable.
14736         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14737           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14738         else if (CXXDestructorDecl *Destructor =
14739                      dyn_cast<CXXDestructorDecl>(FD))
14740           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14741 
14742         // Try to apply the named return value optimization. We have to check
14743         // if we can do this here because lambdas keep return statements around
14744         // to deduce an implicit return type.
14745         if (FD->getReturnType()->isRecordType() &&
14746             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14747           computeNRVO(Body, FSI);
14748       }
14749 
14750       // GNU warning -Wmissing-prototypes:
14751       //   Warn if a global function is defined without a previous
14752       //   prototype declaration. This warning is issued even if the
14753       //   definition itself provides a prototype. The aim is to detect
14754       //   global functions that fail to be declared in header files.
14755       const FunctionDecl *PossiblePrototype = nullptr;
14756       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14757         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14758 
14759         if (PossiblePrototype) {
14760           // We found a declaration that is not a prototype,
14761           // but that could be a zero-parameter prototype
14762           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14763             TypeLoc TL = TI->getTypeLoc();
14764             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14765               Diag(PossiblePrototype->getLocation(),
14766                    diag::note_declaration_not_a_prototype)
14767                   << (FD->getNumParams() != 0)
14768                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14769                                                     FTL.getRParenLoc(), "void")
14770                                               : FixItHint{});
14771           }
14772         } else {
14773           // Returns true if the token beginning at this Loc is `const`.
14774           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14775                                   const LangOptions &LangOpts) {
14776             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14777             if (LocInfo.first.isInvalid())
14778               return false;
14779 
14780             bool Invalid = false;
14781             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14782             if (Invalid)
14783               return false;
14784 
14785             if (LocInfo.second > Buffer.size())
14786               return false;
14787 
14788             const char *LexStart = Buffer.data() + LocInfo.second;
14789             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14790 
14791             return StartTok.consume_front("const") &&
14792                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14793                     StartTok.startswith("/*") || StartTok.startswith("//"));
14794           };
14795 
14796           auto findBeginLoc = [&]() {
14797             // If the return type has `const` qualifier, we want to insert
14798             // `static` before `const` (and not before the typename).
14799             if ((FD->getReturnType()->isAnyPointerType() &&
14800                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14801                 FD->getReturnType().isConstQualified()) {
14802               // But only do this if we can determine where the `const` is.
14803 
14804               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14805                                getLangOpts()))
14806 
14807                 return FD->getBeginLoc();
14808             }
14809             return FD->getTypeSpecStartLoc();
14810           };
14811           Diag(FD->getTypeSpecStartLoc(),
14812                diag::note_static_for_internal_linkage)
14813               << /* function */ 1
14814               << (FD->getStorageClass() == SC_None
14815                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14816                       : FixItHint{});
14817         }
14818 
14819         // GNU warning -Wstrict-prototypes
14820         //   Warn if K&R function is defined without a previous declaration.
14821         //   This warning is issued only if the definition itself does not
14822         //   provide a prototype. Only K&R definitions do not provide a
14823         //   prototype.
14824         if (!FD->hasWrittenPrototype()) {
14825           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14826           TypeLoc TL = TI->getTypeLoc();
14827           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14828           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14829         }
14830       }
14831 
14832       // Warn on CPUDispatch with an actual body.
14833       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14834         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14835           if (!CmpndBody->body_empty())
14836             Diag(CmpndBody->body_front()->getBeginLoc(),
14837                  diag::warn_dispatch_body_ignored);
14838 
14839       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14840         const CXXMethodDecl *KeyFunction;
14841         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14842             MD->isVirtual() &&
14843             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14844             MD == KeyFunction->getCanonicalDecl()) {
14845           // Update the key-function state if necessary for this ABI.
14846           if (FD->isInlined() &&
14847               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14848             Context.setNonKeyFunction(MD);
14849 
14850             // If the newly-chosen key function is already defined, then we
14851             // need to mark the vtable as used retroactively.
14852             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14853             const FunctionDecl *Definition;
14854             if (KeyFunction && KeyFunction->isDefined(Definition))
14855               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14856           } else {
14857             // We just defined they key function; mark the vtable as used.
14858             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14859           }
14860         }
14861       }
14862 
14863       assert(
14864           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14865           "Function parsing confused");
14866     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14867       assert(MD == getCurMethodDecl() && "Method parsing confused");
14868       MD->setBody(Body);
14869       if (!MD->isInvalidDecl()) {
14870         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14871                                                MD->getReturnType(), MD);
14872 
14873         if (Body)
14874           computeNRVO(Body, FSI);
14875       }
14876       if (FSI->ObjCShouldCallSuper) {
14877         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14878             << MD->getSelector().getAsString();
14879         FSI->ObjCShouldCallSuper = false;
14880       }
14881       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14882         const ObjCMethodDecl *InitMethod = nullptr;
14883         bool isDesignated =
14884             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14885         assert(isDesignated && InitMethod);
14886         (void)isDesignated;
14887 
14888         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14889           auto IFace = MD->getClassInterface();
14890           if (!IFace)
14891             return false;
14892           auto SuperD = IFace->getSuperClass();
14893           if (!SuperD)
14894             return false;
14895           return SuperD->getIdentifier() ==
14896                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14897         };
14898         // Don't issue this warning for unavailable inits or direct subclasses
14899         // of NSObject.
14900         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14901           Diag(MD->getLocation(),
14902                diag::warn_objc_designated_init_missing_super_call);
14903           Diag(InitMethod->getLocation(),
14904                diag::note_objc_designated_init_marked_here);
14905         }
14906         FSI->ObjCWarnForNoDesignatedInitChain = false;
14907       }
14908       if (FSI->ObjCWarnForNoInitDelegation) {
14909         // Don't issue this warning for unavaialable inits.
14910         if (!MD->isUnavailable())
14911           Diag(MD->getLocation(),
14912                diag::warn_objc_secondary_init_missing_init_call);
14913         FSI->ObjCWarnForNoInitDelegation = false;
14914       }
14915 
14916       diagnoseImplicitlyRetainedSelf(*this);
14917     } else {
14918       // Parsing the function declaration failed in some way. Pop the fake scope
14919       // we pushed on.
14920       PopFunctionScopeInfo(ActivePolicy, dcl);
14921       return nullptr;
14922     }
14923 
14924     if (Body && FSI->HasPotentialAvailabilityViolations)
14925       DiagnoseUnguardedAvailabilityViolations(dcl);
14926 
14927     assert(!FSI->ObjCShouldCallSuper &&
14928            "This should only be set for ObjC methods, which should have been "
14929            "handled in the block above.");
14930 
14931     // Verify and clean out per-function state.
14932     if (Body && (!FD || !FD->isDefaulted())) {
14933       // C++ constructors that have function-try-blocks can't have return
14934       // statements in the handlers of that block. (C++ [except.handle]p14)
14935       // Verify this.
14936       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14937         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14938 
14939       // Verify that gotos and switch cases don't jump into scopes illegally.
14940       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14941         DiagnoseInvalidJumps(Body);
14942 
14943       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14944         if (!Destructor->getParent()->isDependentType())
14945           CheckDestructor(Destructor);
14946 
14947         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14948                                                Destructor->getParent());
14949       }
14950 
14951       // If any errors have occurred, clear out any temporaries that may have
14952       // been leftover. This ensures that these temporaries won't be picked up
14953       // for deletion in some later function.
14954       if (hasUncompilableErrorOccurred() ||
14955           getDiagnostics().getSuppressAllDiagnostics()) {
14956         DiscardCleanupsInEvaluationContext();
14957       }
14958       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14959         // Since the body is valid, issue any analysis-based warnings that are
14960         // enabled.
14961         ActivePolicy = &WP;
14962       }
14963 
14964       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14965           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14966         FD->setInvalidDecl();
14967 
14968       if (FD && FD->hasAttr<NakedAttr>()) {
14969         for (const Stmt *S : Body->children()) {
14970           // Allow local register variables without initializer as they don't
14971           // require prologue.
14972           bool RegisterVariables = false;
14973           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14974             for (const auto *Decl : DS->decls()) {
14975               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14976                 RegisterVariables =
14977                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14978                 if (!RegisterVariables)
14979                   break;
14980               }
14981             }
14982           }
14983           if (RegisterVariables)
14984             continue;
14985           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14986             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14987             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14988             FD->setInvalidDecl();
14989             break;
14990           }
14991         }
14992       }
14993 
14994       assert(ExprCleanupObjects.size() ==
14995                  ExprEvalContexts.back().NumCleanupObjects &&
14996              "Leftover temporaries in function");
14997       assert(!Cleanup.exprNeedsCleanups() &&
14998              "Unaccounted cleanups in function");
14999       assert(MaybeODRUseExprs.empty() &&
15000              "Leftover expressions for odr-use checking");
15001     }
15002   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15003     // the declaration context below. Otherwise, we're unable to transform
15004     // 'this' expressions when transforming immediate context functions.
15005 
15006   if (!IsInstantiation)
15007     PopDeclContext();
15008 
15009   PopFunctionScopeInfo(ActivePolicy, dcl);
15010   // If any errors have occurred, clear out any temporaries that may have
15011   // been leftover. This ensures that these temporaries won't be picked up for
15012   // deletion in some later function.
15013   if (hasUncompilableErrorOccurred()) {
15014     DiscardCleanupsInEvaluationContext();
15015   }
15016 
15017   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15018                                   !LangOpts.OMPTargetTriples.empty())) ||
15019              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15020     auto ES = getEmissionStatus(FD);
15021     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15022         ES == Sema::FunctionEmissionStatus::Unknown)
15023       DeclsToCheckForDeferredDiags.insert(FD);
15024   }
15025 
15026   if (FD && !FD->isDeleted())
15027     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15028 
15029   return dcl;
15030 }
15031 
15032 /// When we finish delayed parsing of an attribute, we must attach it to the
15033 /// relevant Decl.
15034 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15035                                        ParsedAttributes &Attrs) {
15036   // Always attach attributes to the underlying decl.
15037   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15038     D = TD->getTemplatedDecl();
15039   ProcessDeclAttributeList(S, D, Attrs);
15040 
15041   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15042     if (Method->isStatic())
15043       checkThisInStaticMemberFunctionAttributes(Method);
15044 }
15045 
15046 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15047 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15048 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15049                                           IdentifierInfo &II, Scope *S) {
15050   // Find the scope in which the identifier is injected and the corresponding
15051   // DeclContext.
15052   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15053   // In that case, we inject the declaration into the translation unit scope
15054   // instead.
15055   Scope *BlockScope = S;
15056   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15057     BlockScope = BlockScope->getParent();
15058 
15059   Scope *ContextScope = BlockScope;
15060   while (!ContextScope->getEntity())
15061     ContextScope = ContextScope->getParent();
15062   ContextRAII SavedContext(*this, ContextScope->getEntity());
15063 
15064   // Before we produce a declaration for an implicitly defined
15065   // function, see whether there was a locally-scoped declaration of
15066   // this name as a function or variable. If so, use that
15067   // (non-visible) declaration, and complain about it.
15068   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15069   if (ExternCPrev) {
15070     // We still need to inject the function into the enclosing block scope so
15071     // that later (non-call) uses can see it.
15072     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15073 
15074     // C89 footnote 38:
15075     //   If in fact it is not defined as having type "function returning int",
15076     //   the behavior is undefined.
15077     if (!isa<FunctionDecl>(ExternCPrev) ||
15078         !Context.typesAreCompatible(
15079             cast<FunctionDecl>(ExternCPrev)->getType(),
15080             Context.getFunctionNoProtoType(Context.IntTy))) {
15081       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15082           << ExternCPrev << !getLangOpts().C99;
15083       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15084       return ExternCPrev;
15085     }
15086   }
15087 
15088   // Extension in C99.  Legal in C90, but warn about it.
15089   unsigned diag_id;
15090   if (II.getName().startswith("__builtin_"))
15091     diag_id = diag::warn_builtin_unknown;
15092   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15093   else if (getLangOpts().OpenCL)
15094     diag_id = diag::err_opencl_implicit_function_decl;
15095   else if (getLangOpts().C99)
15096     diag_id = diag::ext_implicit_function_decl;
15097   else
15098     diag_id = diag::warn_implicit_function_decl;
15099 
15100   TypoCorrection Corrected;
15101   // Because typo correction is expensive, only do it if the implicit
15102   // function declaration is going to be treated as an error.
15103   //
15104   // Perform the corection before issuing the main diagnostic, as some consumers
15105   // use typo-correction callbacks to enhance the main diagnostic.
15106   if (S && !ExternCPrev &&
15107       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15108     DeclFilterCCC<FunctionDecl> CCC{};
15109     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15110                             S, nullptr, CCC, CTK_NonError);
15111   }
15112 
15113   Diag(Loc, diag_id) << &II;
15114   if (Corrected)
15115     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15116                  /*ErrorRecovery*/ false);
15117 
15118   // If we found a prior declaration of this function, don't bother building
15119   // another one. We've already pushed that one into scope, so there's nothing
15120   // more to do.
15121   if (ExternCPrev)
15122     return ExternCPrev;
15123 
15124   // Set a Declarator for the implicit definition: int foo();
15125   const char *Dummy;
15126   AttributeFactory attrFactory;
15127   DeclSpec DS(attrFactory);
15128   unsigned DiagID;
15129   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15130                                   Context.getPrintingPolicy());
15131   (void)Error; // Silence warning.
15132   assert(!Error && "Error setting up implicit decl!");
15133   SourceLocation NoLoc;
15134   Declarator D(DS, DeclaratorContext::Block);
15135   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15136                                              /*IsAmbiguous=*/false,
15137                                              /*LParenLoc=*/NoLoc,
15138                                              /*Params=*/nullptr,
15139                                              /*NumParams=*/0,
15140                                              /*EllipsisLoc=*/NoLoc,
15141                                              /*RParenLoc=*/NoLoc,
15142                                              /*RefQualifierIsLvalueRef=*/true,
15143                                              /*RefQualifierLoc=*/NoLoc,
15144                                              /*MutableLoc=*/NoLoc, EST_None,
15145                                              /*ESpecRange=*/SourceRange(),
15146                                              /*Exceptions=*/nullptr,
15147                                              /*ExceptionRanges=*/nullptr,
15148                                              /*NumExceptions=*/0,
15149                                              /*NoexceptExpr=*/nullptr,
15150                                              /*ExceptionSpecTokens=*/nullptr,
15151                                              /*DeclsInPrototype=*/None, Loc,
15152                                              Loc, D),
15153                 std::move(DS.getAttributes()), SourceLocation());
15154   D.SetIdentifier(&II, Loc);
15155 
15156   // Insert this function into the enclosing block scope.
15157   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15158   FD->setImplicit();
15159 
15160   AddKnownFunctionAttributes(FD);
15161 
15162   return FD;
15163 }
15164 
15165 /// If this function is a C++ replaceable global allocation function
15166 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15167 /// adds any function attributes that we know a priori based on the standard.
15168 ///
15169 /// We need to check for duplicate attributes both here and where user-written
15170 /// attributes are applied to declarations.
15171 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15172     FunctionDecl *FD) {
15173   if (FD->isInvalidDecl())
15174     return;
15175 
15176   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15177       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15178     return;
15179 
15180   Optional<unsigned> AlignmentParam;
15181   bool IsNothrow = false;
15182   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15183     return;
15184 
15185   // C++2a [basic.stc.dynamic.allocation]p4:
15186   //   An allocation function that has a non-throwing exception specification
15187   //   indicates failure by returning a null pointer value. Any other allocation
15188   //   function never returns a null pointer value and indicates failure only by
15189   //   throwing an exception [...]
15190   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15191     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15192 
15193   // C++2a [basic.stc.dynamic.allocation]p2:
15194   //   An allocation function attempts to allocate the requested amount of
15195   //   storage. [...] If the request succeeds, the value returned by a
15196   //   replaceable allocation function is a [...] pointer value p0 different
15197   //   from any previously returned value p1 [...]
15198   //
15199   // However, this particular information is being added in codegen,
15200   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15201 
15202   // C++2a [basic.stc.dynamic.allocation]p2:
15203   //   An allocation function attempts to allocate the requested amount of
15204   //   storage. If it is successful, it returns the address of the start of a
15205   //   block of storage whose length in bytes is at least as large as the
15206   //   requested size.
15207   if (!FD->hasAttr<AllocSizeAttr>()) {
15208     FD->addAttr(AllocSizeAttr::CreateImplicit(
15209         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15210         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15211   }
15212 
15213   // C++2a [basic.stc.dynamic.allocation]p3:
15214   //   For an allocation function [...], the pointer returned on a successful
15215   //   call shall represent the address of storage that is aligned as follows:
15216   //   (3.1) If the allocation function takes an argument of type
15217   //         std​::​align_­val_­t, the storage will have the alignment
15218   //         specified by the value of this argument.
15219   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15220     FD->addAttr(AllocAlignAttr::CreateImplicit(
15221         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15222   }
15223 
15224   // FIXME:
15225   // C++2a [basic.stc.dynamic.allocation]p3:
15226   //   For an allocation function [...], the pointer returned on a successful
15227   //   call shall represent the address of storage that is aligned as follows:
15228   //   (3.2) Otherwise, if the allocation function is named operator new[],
15229   //         the storage is aligned for any object that does not have
15230   //         new-extended alignment ([basic.align]) and is no larger than the
15231   //         requested size.
15232   //   (3.3) Otherwise, the storage is aligned for any object that does not
15233   //         have new-extended alignment and is of the requested size.
15234 }
15235 
15236 /// Adds any function attributes that we know a priori based on
15237 /// the declaration of this function.
15238 ///
15239 /// These attributes can apply both to implicitly-declared builtins
15240 /// (like __builtin___printf_chk) or to library-declared functions
15241 /// like NSLog or printf.
15242 ///
15243 /// We need to check for duplicate attributes both here and where user-written
15244 /// attributes are applied to declarations.
15245 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15246   if (FD->isInvalidDecl())
15247     return;
15248 
15249   // If this is a built-in function, map its builtin attributes to
15250   // actual attributes.
15251   if (unsigned BuiltinID = FD->getBuiltinID()) {
15252     // Handle printf-formatting attributes.
15253     unsigned FormatIdx;
15254     bool HasVAListArg;
15255     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15256       if (!FD->hasAttr<FormatAttr>()) {
15257         const char *fmt = "printf";
15258         unsigned int NumParams = FD->getNumParams();
15259         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15260             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15261           fmt = "NSString";
15262         FD->addAttr(FormatAttr::CreateImplicit(Context,
15263                                                &Context.Idents.get(fmt),
15264                                                FormatIdx+1,
15265                                                HasVAListArg ? 0 : FormatIdx+2,
15266                                                FD->getLocation()));
15267       }
15268     }
15269     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15270                                              HasVAListArg)) {
15271      if (!FD->hasAttr<FormatAttr>())
15272        FD->addAttr(FormatAttr::CreateImplicit(Context,
15273                                               &Context.Idents.get("scanf"),
15274                                               FormatIdx+1,
15275                                               HasVAListArg ? 0 : FormatIdx+2,
15276                                               FD->getLocation()));
15277     }
15278 
15279     // Handle automatically recognized callbacks.
15280     SmallVector<int, 4> Encoding;
15281     if (!FD->hasAttr<CallbackAttr>() &&
15282         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15283       FD->addAttr(CallbackAttr::CreateImplicit(
15284           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15285 
15286     // Mark const if we don't care about errno and that is the only thing
15287     // preventing the function from being const. This allows IRgen to use LLVM
15288     // intrinsics for such functions.
15289     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15290         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15291       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15292 
15293     // We make "fma" on GNU or Windows const because we know it does not set
15294     // errno in those environments even though it could set errno based on the
15295     // C standard.
15296     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15297     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15298         !FD->hasAttr<ConstAttr>()) {
15299       switch (BuiltinID) {
15300       case Builtin::BI__builtin_fma:
15301       case Builtin::BI__builtin_fmaf:
15302       case Builtin::BI__builtin_fmal:
15303       case Builtin::BIfma:
15304       case Builtin::BIfmaf:
15305       case Builtin::BIfmal:
15306         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15307         break;
15308       default:
15309         break;
15310       }
15311     }
15312 
15313     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15314         !FD->hasAttr<ReturnsTwiceAttr>())
15315       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15316                                          FD->getLocation()));
15317     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15318       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15319     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15320       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15321     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15322       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15323     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15324         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15325       // Add the appropriate attribute, depending on the CUDA compilation mode
15326       // and which target the builtin belongs to. For example, during host
15327       // compilation, aux builtins are __device__, while the rest are __host__.
15328       if (getLangOpts().CUDAIsDevice !=
15329           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15330         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15331       else
15332         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15333     }
15334 
15335     // Add known guaranteed alignment for allocation functions.
15336     switch (BuiltinID) {
15337     case Builtin::BImemalign:
15338     case Builtin::BIaligned_alloc:
15339       if (!FD->hasAttr<AllocAlignAttr>())
15340         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15341                                                    FD->getLocation()));
15342       break;
15343     default:
15344       break;
15345     }
15346 
15347     // Add allocsize attribute for allocation functions.
15348     switch (BuiltinID) {
15349     case Builtin::BIcalloc:
15350       FD->addAttr(AllocSizeAttr::CreateImplicit(
15351           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15352       break;
15353     case Builtin::BImemalign:
15354     case Builtin::BIaligned_alloc:
15355     case Builtin::BIrealloc:
15356       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15357                                                 ParamIdx(), FD->getLocation()));
15358       break;
15359     case Builtin::BImalloc:
15360       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15361                                                 ParamIdx(), FD->getLocation()));
15362       break;
15363     default:
15364       break;
15365     }
15366   }
15367 
15368   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15369 
15370   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15371   // throw, add an implicit nothrow attribute to any extern "C" function we come
15372   // across.
15373   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15374       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15375     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15376     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15377       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15378   }
15379 
15380   IdentifierInfo *Name = FD->getIdentifier();
15381   if (!Name)
15382     return;
15383   if ((!getLangOpts().CPlusPlus &&
15384        FD->getDeclContext()->isTranslationUnit()) ||
15385       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15386        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15387        LinkageSpecDecl::lang_c)) {
15388     // Okay: this could be a libc/libm/Objective-C function we know
15389     // about.
15390   } else
15391     return;
15392 
15393   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15394     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15395     // target-specific builtins, perhaps?
15396     if (!FD->hasAttr<FormatAttr>())
15397       FD->addAttr(FormatAttr::CreateImplicit(Context,
15398                                              &Context.Idents.get("printf"), 2,
15399                                              Name->isStr("vasprintf") ? 0 : 3,
15400                                              FD->getLocation()));
15401   }
15402 
15403   if (Name->isStr("__CFStringMakeConstantString")) {
15404     // We already have a __builtin___CFStringMakeConstantString,
15405     // but builds that use -fno-constant-cfstrings don't go through that.
15406     if (!FD->hasAttr<FormatArgAttr>())
15407       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15408                                                 FD->getLocation()));
15409   }
15410 }
15411 
15412 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15413                                     TypeSourceInfo *TInfo) {
15414   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15415   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15416 
15417   if (!TInfo) {
15418     assert(D.isInvalidType() && "no declarator info for valid type");
15419     TInfo = Context.getTrivialTypeSourceInfo(T);
15420   }
15421 
15422   // Scope manipulation handled by caller.
15423   TypedefDecl *NewTD =
15424       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15425                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15426 
15427   // Bail out immediately if we have an invalid declaration.
15428   if (D.isInvalidType()) {
15429     NewTD->setInvalidDecl();
15430     return NewTD;
15431   }
15432 
15433   if (D.getDeclSpec().isModulePrivateSpecified()) {
15434     if (CurContext->isFunctionOrMethod())
15435       Diag(NewTD->getLocation(), diag::err_module_private_local)
15436           << 2 << NewTD
15437           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15438           << FixItHint::CreateRemoval(
15439                  D.getDeclSpec().getModulePrivateSpecLoc());
15440     else
15441       NewTD->setModulePrivate();
15442   }
15443 
15444   // C++ [dcl.typedef]p8:
15445   //   If the typedef declaration defines an unnamed class (or
15446   //   enum), the first typedef-name declared by the declaration
15447   //   to be that class type (or enum type) is used to denote the
15448   //   class type (or enum type) for linkage purposes only.
15449   // We need to check whether the type was declared in the declaration.
15450   switch (D.getDeclSpec().getTypeSpecType()) {
15451   case TST_enum:
15452   case TST_struct:
15453   case TST_interface:
15454   case TST_union:
15455   case TST_class: {
15456     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15457     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15458     break;
15459   }
15460 
15461   default:
15462     break;
15463   }
15464 
15465   return NewTD;
15466 }
15467 
15468 /// Check that this is a valid underlying type for an enum declaration.
15469 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15470   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15471   QualType T = TI->getType();
15472 
15473   if (T->isDependentType())
15474     return false;
15475 
15476   // This doesn't use 'isIntegralType' despite the error message mentioning
15477   // integral type because isIntegralType would also allow enum types in C.
15478   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15479     if (BT->isInteger())
15480       return false;
15481 
15482   if (T->isBitIntType())
15483     return false;
15484 
15485   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15486 }
15487 
15488 /// Check whether this is a valid redeclaration of a previous enumeration.
15489 /// \return true if the redeclaration was invalid.
15490 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15491                                   QualType EnumUnderlyingTy, bool IsFixed,
15492                                   const EnumDecl *Prev) {
15493   if (IsScoped != Prev->isScoped()) {
15494     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15495       << Prev->isScoped();
15496     Diag(Prev->getLocation(), diag::note_previous_declaration);
15497     return true;
15498   }
15499 
15500   if (IsFixed && Prev->isFixed()) {
15501     if (!EnumUnderlyingTy->isDependentType() &&
15502         !Prev->getIntegerType()->isDependentType() &&
15503         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15504                                         Prev->getIntegerType())) {
15505       // TODO: Highlight the underlying type of the redeclaration.
15506       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15507         << EnumUnderlyingTy << Prev->getIntegerType();
15508       Diag(Prev->getLocation(), diag::note_previous_declaration)
15509           << Prev->getIntegerTypeRange();
15510       return true;
15511     }
15512   } else if (IsFixed != Prev->isFixed()) {
15513     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15514       << Prev->isFixed();
15515     Diag(Prev->getLocation(), diag::note_previous_declaration);
15516     return true;
15517   }
15518 
15519   return false;
15520 }
15521 
15522 /// Get diagnostic %select index for tag kind for
15523 /// redeclaration diagnostic message.
15524 /// WARNING: Indexes apply to particular diagnostics only!
15525 ///
15526 /// \returns diagnostic %select index.
15527 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15528   switch (Tag) {
15529   case TTK_Struct: return 0;
15530   case TTK_Interface: return 1;
15531   case TTK_Class:  return 2;
15532   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15533   }
15534 }
15535 
15536 /// Determine if tag kind is a class-key compatible with
15537 /// class for redeclaration (class, struct, or __interface).
15538 ///
15539 /// \returns true iff the tag kind is compatible.
15540 static bool isClassCompatTagKind(TagTypeKind Tag)
15541 {
15542   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15543 }
15544 
15545 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15546                                              TagTypeKind TTK) {
15547   if (isa<TypedefDecl>(PrevDecl))
15548     return NTK_Typedef;
15549   else if (isa<TypeAliasDecl>(PrevDecl))
15550     return NTK_TypeAlias;
15551   else if (isa<ClassTemplateDecl>(PrevDecl))
15552     return NTK_Template;
15553   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15554     return NTK_TypeAliasTemplate;
15555   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15556     return NTK_TemplateTemplateArgument;
15557   switch (TTK) {
15558   case TTK_Struct:
15559   case TTK_Interface:
15560   case TTK_Class:
15561     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15562   case TTK_Union:
15563     return NTK_NonUnion;
15564   case TTK_Enum:
15565     return NTK_NonEnum;
15566   }
15567   llvm_unreachable("invalid TTK");
15568 }
15569 
15570 /// Determine whether a tag with a given kind is acceptable
15571 /// as a redeclaration of the given tag declaration.
15572 ///
15573 /// \returns true if the new tag kind is acceptable, false otherwise.
15574 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15575                                         TagTypeKind NewTag, bool isDefinition,
15576                                         SourceLocation NewTagLoc,
15577                                         const IdentifierInfo *Name) {
15578   // C++ [dcl.type.elab]p3:
15579   //   The class-key or enum keyword present in the
15580   //   elaborated-type-specifier shall agree in kind with the
15581   //   declaration to which the name in the elaborated-type-specifier
15582   //   refers. This rule also applies to the form of
15583   //   elaborated-type-specifier that declares a class-name or
15584   //   friend class since it can be construed as referring to the
15585   //   definition of the class. Thus, in any
15586   //   elaborated-type-specifier, the enum keyword shall be used to
15587   //   refer to an enumeration (7.2), the union class-key shall be
15588   //   used to refer to a union (clause 9), and either the class or
15589   //   struct class-key shall be used to refer to a class (clause 9)
15590   //   declared using the class or struct class-key.
15591   TagTypeKind OldTag = Previous->getTagKind();
15592   if (OldTag != NewTag &&
15593       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15594     return false;
15595 
15596   // Tags are compatible, but we might still want to warn on mismatched tags.
15597   // Non-class tags can't be mismatched at this point.
15598   if (!isClassCompatTagKind(NewTag))
15599     return true;
15600 
15601   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15602   // by our warning analysis. We don't want to warn about mismatches with (eg)
15603   // declarations in system headers that are designed to be specialized, but if
15604   // a user asks us to warn, we should warn if their code contains mismatched
15605   // declarations.
15606   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15607     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15608                                       Loc);
15609   };
15610   if (IsIgnoredLoc(NewTagLoc))
15611     return true;
15612 
15613   auto IsIgnored = [&](const TagDecl *Tag) {
15614     return IsIgnoredLoc(Tag->getLocation());
15615   };
15616   while (IsIgnored(Previous)) {
15617     Previous = Previous->getPreviousDecl();
15618     if (!Previous)
15619       return true;
15620     OldTag = Previous->getTagKind();
15621   }
15622 
15623   bool isTemplate = false;
15624   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15625     isTemplate = Record->getDescribedClassTemplate();
15626 
15627   if (inTemplateInstantiation()) {
15628     if (OldTag != NewTag) {
15629       // In a template instantiation, do not offer fix-its for tag mismatches
15630       // since they usually mess up the template instead of fixing the problem.
15631       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15632         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15633         << getRedeclDiagFromTagKind(OldTag);
15634       // FIXME: Note previous location?
15635     }
15636     return true;
15637   }
15638 
15639   if (isDefinition) {
15640     // On definitions, check all previous tags and issue a fix-it for each
15641     // one that doesn't match the current tag.
15642     if (Previous->getDefinition()) {
15643       // Don't suggest fix-its for redefinitions.
15644       return true;
15645     }
15646 
15647     bool previousMismatch = false;
15648     for (const TagDecl *I : Previous->redecls()) {
15649       if (I->getTagKind() != NewTag) {
15650         // Ignore previous declarations for which the warning was disabled.
15651         if (IsIgnored(I))
15652           continue;
15653 
15654         if (!previousMismatch) {
15655           previousMismatch = true;
15656           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15657             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15658             << getRedeclDiagFromTagKind(I->getTagKind());
15659         }
15660         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15661           << getRedeclDiagFromTagKind(NewTag)
15662           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15663                TypeWithKeyword::getTagTypeKindName(NewTag));
15664       }
15665     }
15666     return true;
15667   }
15668 
15669   // Identify the prevailing tag kind: this is the kind of the definition (if
15670   // there is a non-ignored definition), or otherwise the kind of the prior
15671   // (non-ignored) declaration.
15672   const TagDecl *PrevDef = Previous->getDefinition();
15673   if (PrevDef && IsIgnored(PrevDef))
15674     PrevDef = nullptr;
15675   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15676   if (Redecl->getTagKind() != NewTag) {
15677     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15678       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15679       << getRedeclDiagFromTagKind(OldTag);
15680     Diag(Redecl->getLocation(), diag::note_previous_use);
15681 
15682     // If there is a previous definition, suggest a fix-it.
15683     if (PrevDef) {
15684       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15685         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15686         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15687              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15688     }
15689   }
15690 
15691   return true;
15692 }
15693 
15694 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15695 /// from an outer enclosing namespace or file scope inside a friend declaration.
15696 /// This should provide the commented out code in the following snippet:
15697 ///   namespace N {
15698 ///     struct X;
15699 ///     namespace M {
15700 ///       struct Y { friend struct /*N::*/ X; };
15701 ///     }
15702 ///   }
15703 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15704                                          SourceLocation NameLoc) {
15705   // While the decl is in a namespace, do repeated lookup of that name and see
15706   // if we get the same namespace back.  If we do not, continue until
15707   // translation unit scope, at which point we have a fully qualified NNS.
15708   SmallVector<IdentifierInfo *, 4> Namespaces;
15709   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15710   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15711     // This tag should be declared in a namespace, which can only be enclosed by
15712     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15713     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15714     if (!Namespace || Namespace->isAnonymousNamespace())
15715       return FixItHint();
15716     IdentifierInfo *II = Namespace->getIdentifier();
15717     Namespaces.push_back(II);
15718     NamedDecl *Lookup = SemaRef.LookupSingleName(
15719         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15720     if (Lookup == Namespace)
15721       break;
15722   }
15723 
15724   // Once we have all the namespaces, reverse them to go outermost first, and
15725   // build an NNS.
15726   SmallString<64> Insertion;
15727   llvm::raw_svector_ostream OS(Insertion);
15728   if (DC->isTranslationUnit())
15729     OS << "::";
15730   std::reverse(Namespaces.begin(), Namespaces.end());
15731   for (auto *II : Namespaces)
15732     OS << II->getName() << "::";
15733   return FixItHint::CreateInsertion(NameLoc, Insertion);
15734 }
15735 
15736 /// Determine whether a tag originally declared in context \p OldDC can
15737 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15738 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15739 /// using-declaration).
15740 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15741                                          DeclContext *NewDC) {
15742   OldDC = OldDC->getRedeclContext();
15743   NewDC = NewDC->getRedeclContext();
15744 
15745   if (OldDC->Equals(NewDC))
15746     return true;
15747 
15748   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15749   // encloses the other).
15750   if (S.getLangOpts().MSVCCompat &&
15751       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15752     return true;
15753 
15754   return false;
15755 }
15756 
15757 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15758 /// former case, Name will be non-null.  In the later case, Name will be null.
15759 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15760 /// reference/declaration/definition of a tag.
15761 ///
15762 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15763 /// trailing-type-specifier) other than one in an alias-declaration.
15764 ///
15765 /// \param SkipBody If non-null, will be set to indicate if the caller should
15766 /// skip the definition of this tag and treat it as if it were a declaration.
15767 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15768                      SourceLocation KWLoc, CXXScopeSpec &SS,
15769                      IdentifierInfo *Name, SourceLocation NameLoc,
15770                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15771                      SourceLocation ModulePrivateLoc,
15772                      MultiTemplateParamsArg TemplateParameterLists,
15773                      bool &OwnedDecl, bool &IsDependent,
15774                      SourceLocation ScopedEnumKWLoc,
15775                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15776                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15777                      SkipBodyInfo *SkipBody) {
15778   // If this is not a definition, it must have a name.
15779   IdentifierInfo *OrigName = Name;
15780   assert((Name != nullptr || TUK == TUK_Definition) &&
15781          "Nameless record must be a definition!");
15782   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15783 
15784   OwnedDecl = false;
15785   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15786   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15787 
15788   // FIXME: Check member specializations more carefully.
15789   bool isMemberSpecialization = false;
15790   bool Invalid = false;
15791 
15792   // We only need to do this matching if we have template parameters
15793   // or a scope specifier, which also conveniently avoids this work
15794   // for non-C++ cases.
15795   if (TemplateParameterLists.size() > 0 ||
15796       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15797     if (TemplateParameterList *TemplateParams =
15798             MatchTemplateParametersToScopeSpecifier(
15799                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15800                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15801       if (Kind == TTK_Enum) {
15802         Diag(KWLoc, diag::err_enum_template);
15803         return nullptr;
15804       }
15805 
15806       if (TemplateParams->size() > 0) {
15807         // This is a declaration or definition of a class template (which may
15808         // be a member of another template).
15809 
15810         if (Invalid)
15811           return nullptr;
15812 
15813         OwnedDecl = false;
15814         DeclResult Result = CheckClassTemplate(
15815             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15816             AS, ModulePrivateLoc,
15817             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15818             TemplateParameterLists.data(), SkipBody);
15819         return Result.get();
15820       } else {
15821         // The "template<>" header is extraneous.
15822         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15823           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15824         isMemberSpecialization = true;
15825       }
15826     }
15827 
15828     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15829         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15830       return nullptr;
15831   }
15832 
15833   // Figure out the underlying type if this a enum declaration. We need to do
15834   // this early, because it's needed to detect if this is an incompatible
15835   // redeclaration.
15836   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15837   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15838 
15839   if (Kind == TTK_Enum) {
15840     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15841       // No underlying type explicitly specified, or we failed to parse the
15842       // type, default to int.
15843       EnumUnderlying = Context.IntTy.getTypePtr();
15844     } else if (UnderlyingType.get()) {
15845       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15846       // integral type; any cv-qualification is ignored.
15847       TypeSourceInfo *TI = nullptr;
15848       GetTypeFromParser(UnderlyingType.get(), &TI);
15849       EnumUnderlying = TI;
15850 
15851       if (CheckEnumUnderlyingType(TI))
15852         // Recover by falling back to int.
15853         EnumUnderlying = Context.IntTy.getTypePtr();
15854 
15855       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15856                                           UPPC_FixedUnderlyingType))
15857         EnumUnderlying = Context.IntTy.getTypePtr();
15858 
15859     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15860       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15861       // of 'int'. However, if this is an unfixed forward declaration, don't set
15862       // the underlying type unless the user enables -fms-compatibility. This
15863       // makes unfixed forward declared enums incomplete and is more conforming.
15864       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15865         EnumUnderlying = Context.IntTy.getTypePtr();
15866     }
15867   }
15868 
15869   DeclContext *SearchDC = CurContext;
15870   DeclContext *DC = CurContext;
15871   bool isStdBadAlloc = false;
15872   bool isStdAlignValT = false;
15873 
15874   RedeclarationKind Redecl = forRedeclarationInCurContext();
15875   if (TUK == TUK_Friend || TUK == TUK_Reference)
15876     Redecl = NotForRedeclaration;
15877 
15878   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15879   /// implemented asks for structural equivalence checking, the returned decl
15880   /// here is passed back to the parser, allowing the tag body to be parsed.
15881   auto createTagFromNewDecl = [&]() -> TagDecl * {
15882     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15883     // If there is an identifier, use the location of the identifier as the
15884     // location of the decl, otherwise use the location of the struct/union
15885     // keyword.
15886     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15887     TagDecl *New = nullptr;
15888 
15889     if (Kind == TTK_Enum) {
15890       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15891                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15892       // If this is an undefined enum, bail.
15893       if (TUK != TUK_Definition && !Invalid)
15894         return nullptr;
15895       if (EnumUnderlying) {
15896         EnumDecl *ED = cast<EnumDecl>(New);
15897         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15898           ED->setIntegerTypeSourceInfo(TI);
15899         else
15900           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15901         ED->setPromotionType(ED->getIntegerType());
15902       }
15903     } else { // struct/union
15904       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15905                                nullptr);
15906     }
15907 
15908     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15909       // Add alignment attributes if necessary; these attributes are checked
15910       // when the ASTContext lays out the structure.
15911       //
15912       // It is important for implementing the correct semantics that this
15913       // happen here (in ActOnTag). The #pragma pack stack is
15914       // maintained as a result of parser callbacks which can occur at
15915       // many points during the parsing of a struct declaration (because
15916       // the #pragma tokens are effectively skipped over during the
15917       // parsing of the struct).
15918       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15919         AddAlignmentAttributesForRecord(RD);
15920         AddMsStructLayoutForRecord(RD);
15921       }
15922     }
15923     New->setLexicalDeclContext(CurContext);
15924     return New;
15925   };
15926 
15927   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15928   if (Name && SS.isNotEmpty()) {
15929     // We have a nested-name tag ('struct foo::bar').
15930 
15931     // Check for invalid 'foo::'.
15932     if (SS.isInvalid()) {
15933       Name = nullptr;
15934       goto CreateNewDecl;
15935     }
15936 
15937     // If this is a friend or a reference to a class in a dependent
15938     // context, don't try to make a decl for it.
15939     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15940       DC = computeDeclContext(SS, false);
15941       if (!DC) {
15942         IsDependent = true;
15943         return nullptr;
15944       }
15945     } else {
15946       DC = computeDeclContext(SS, true);
15947       if (!DC) {
15948         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15949           << SS.getRange();
15950         return nullptr;
15951       }
15952     }
15953 
15954     if (RequireCompleteDeclContext(SS, DC))
15955       return nullptr;
15956 
15957     SearchDC = DC;
15958     // Look-up name inside 'foo::'.
15959     LookupQualifiedName(Previous, DC);
15960 
15961     if (Previous.isAmbiguous())
15962       return nullptr;
15963 
15964     if (Previous.empty()) {
15965       // Name lookup did not find anything. However, if the
15966       // nested-name-specifier refers to the current instantiation,
15967       // and that current instantiation has any dependent base
15968       // classes, we might find something at instantiation time: treat
15969       // this as a dependent elaborated-type-specifier.
15970       // But this only makes any sense for reference-like lookups.
15971       if (Previous.wasNotFoundInCurrentInstantiation() &&
15972           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15973         IsDependent = true;
15974         return nullptr;
15975       }
15976 
15977       // A tag 'foo::bar' must already exist.
15978       Diag(NameLoc, diag::err_not_tag_in_scope)
15979         << Kind << Name << DC << SS.getRange();
15980       Name = nullptr;
15981       Invalid = true;
15982       goto CreateNewDecl;
15983     }
15984   } else if (Name) {
15985     // C++14 [class.mem]p14:
15986     //   If T is the name of a class, then each of the following shall have a
15987     //   name different from T:
15988     //    -- every member of class T that is itself a type
15989     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15990         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15991       return nullptr;
15992 
15993     // If this is a named struct, check to see if there was a previous forward
15994     // declaration or definition.
15995     // FIXME: We're looking into outer scopes here, even when we
15996     // shouldn't be. Doing so can result in ambiguities that we
15997     // shouldn't be diagnosing.
15998     LookupName(Previous, S);
15999 
16000     // When declaring or defining a tag, ignore ambiguities introduced
16001     // by types using'ed into this scope.
16002     if (Previous.isAmbiguous() &&
16003         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16004       LookupResult::Filter F = Previous.makeFilter();
16005       while (F.hasNext()) {
16006         NamedDecl *ND = F.next();
16007         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16008                 SearchDC->getRedeclContext()))
16009           F.erase();
16010       }
16011       F.done();
16012     }
16013 
16014     // C++11 [namespace.memdef]p3:
16015     //   If the name in a friend declaration is neither qualified nor
16016     //   a template-id and the declaration is a function or an
16017     //   elaborated-type-specifier, the lookup to determine whether
16018     //   the entity has been previously declared shall not consider
16019     //   any scopes outside the innermost enclosing namespace.
16020     //
16021     // MSVC doesn't implement the above rule for types, so a friend tag
16022     // declaration may be a redeclaration of a type declared in an enclosing
16023     // scope.  They do implement this rule for friend functions.
16024     //
16025     // Does it matter that this should be by scope instead of by
16026     // semantic context?
16027     if (!Previous.empty() && TUK == TUK_Friend) {
16028       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16029       LookupResult::Filter F = Previous.makeFilter();
16030       bool FriendSawTagOutsideEnclosingNamespace = false;
16031       while (F.hasNext()) {
16032         NamedDecl *ND = F.next();
16033         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16034         if (DC->isFileContext() &&
16035             !EnclosingNS->Encloses(ND->getDeclContext())) {
16036           if (getLangOpts().MSVCCompat)
16037             FriendSawTagOutsideEnclosingNamespace = true;
16038           else
16039             F.erase();
16040         }
16041       }
16042       F.done();
16043 
16044       // Diagnose this MSVC extension in the easy case where lookup would have
16045       // unambiguously found something outside the enclosing namespace.
16046       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16047         NamedDecl *ND = Previous.getFoundDecl();
16048         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16049             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16050       }
16051     }
16052 
16053     // Note:  there used to be some attempt at recovery here.
16054     if (Previous.isAmbiguous())
16055       return nullptr;
16056 
16057     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16058       // FIXME: This makes sure that we ignore the contexts associated
16059       // with C structs, unions, and enums when looking for a matching
16060       // tag declaration or definition. See the similar lookup tweak
16061       // in Sema::LookupName; is there a better way to deal with this?
16062       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16063         SearchDC = SearchDC->getParent();
16064     } else if (getLangOpts().CPlusPlus) {
16065       // Inside ObjCContainer want to keep it as a lexical decl context but go
16066       // past it (most often to TranslationUnit) to find the semantic decl
16067       // context.
16068       while (isa<ObjCContainerDecl>(SearchDC))
16069         SearchDC = SearchDC->getParent();
16070     }
16071   } else if (getLangOpts().CPlusPlus) {
16072     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16073     // TagDecl the same way as we skip it for named TagDecl.
16074     while (isa<ObjCContainerDecl>(SearchDC))
16075       SearchDC = SearchDC->getParent();
16076   }
16077 
16078   if (Previous.isSingleResult() &&
16079       Previous.getFoundDecl()->isTemplateParameter()) {
16080     // Maybe we will complain about the shadowed template parameter.
16081     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16082     // Just pretend that we didn't see the previous declaration.
16083     Previous.clear();
16084   }
16085 
16086   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16087       DC->Equals(getStdNamespace())) {
16088     if (Name->isStr("bad_alloc")) {
16089       // This is a declaration of or a reference to "std::bad_alloc".
16090       isStdBadAlloc = true;
16091 
16092       // If std::bad_alloc has been implicitly declared (but made invisible to
16093       // name lookup), fill in this implicit declaration as the previous
16094       // declaration, so that the declarations get chained appropriately.
16095       if (Previous.empty() && StdBadAlloc)
16096         Previous.addDecl(getStdBadAlloc());
16097     } else if (Name->isStr("align_val_t")) {
16098       isStdAlignValT = true;
16099       if (Previous.empty() && StdAlignValT)
16100         Previous.addDecl(getStdAlignValT());
16101     }
16102   }
16103 
16104   // If we didn't find a previous declaration, and this is a reference
16105   // (or friend reference), move to the correct scope.  In C++, we
16106   // also need to do a redeclaration lookup there, just in case
16107   // there's a shadow friend decl.
16108   if (Name && Previous.empty() &&
16109       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16110     if (Invalid) goto CreateNewDecl;
16111     assert(SS.isEmpty());
16112 
16113     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16114       // C++ [basic.scope.pdecl]p5:
16115       //   -- for an elaborated-type-specifier of the form
16116       //
16117       //          class-key identifier
16118       //
16119       //      if the elaborated-type-specifier is used in the
16120       //      decl-specifier-seq or parameter-declaration-clause of a
16121       //      function defined in namespace scope, the identifier is
16122       //      declared as a class-name in the namespace that contains
16123       //      the declaration; otherwise, except as a friend
16124       //      declaration, the identifier is declared in the smallest
16125       //      non-class, non-function-prototype scope that contains the
16126       //      declaration.
16127       //
16128       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16129       // C structs and unions.
16130       //
16131       // It is an error in C++ to declare (rather than define) an enum
16132       // type, including via an elaborated type specifier.  We'll
16133       // diagnose that later; for now, declare the enum in the same
16134       // scope as we would have picked for any other tag type.
16135       //
16136       // GNU C also supports this behavior as part of its incomplete
16137       // enum types extension, while GNU C++ does not.
16138       //
16139       // Find the context where we'll be declaring the tag.
16140       // FIXME: We would like to maintain the current DeclContext as the
16141       // lexical context,
16142       SearchDC = getTagInjectionContext(SearchDC);
16143 
16144       // Find the scope where we'll be declaring the tag.
16145       S = getTagInjectionScope(S, getLangOpts());
16146     } else {
16147       assert(TUK == TUK_Friend);
16148       // C++ [namespace.memdef]p3:
16149       //   If a friend declaration in a non-local class first declares a
16150       //   class or function, the friend class or function is a member of
16151       //   the innermost enclosing namespace.
16152       SearchDC = SearchDC->getEnclosingNamespaceContext();
16153     }
16154 
16155     // In C++, we need to do a redeclaration lookup to properly
16156     // diagnose some problems.
16157     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16158     // hidden declaration so that we don't get ambiguity errors when using a
16159     // type declared by an elaborated-type-specifier.  In C that is not correct
16160     // and we should instead merge compatible types found by lookup.
16161     if (getLangOpts().CPlusPlus) {
16162       // FIXME: This can perform qualified lookups into function contexts,
16163       // which are meaningless.
16164       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16165       LookupQualifiedName(Previous, SearchDC);
16166     } else {
16167       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16168       LookupName(Previous, S);
16169     }
16170   }
16171 
16172   // If we have a known previous declaration to use, then use it.
16173   if (Previous.empty() && SkipBody && SkipBody->Previous)
16174     Previous.addDecl(SkipBody->Previous);
16175 
16176   if (!Previous.empty()) {
16177     NamedDecl *PrevDecl = Previous.getFoundDecl();
16178     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16179 
16180     // It's okay to have a tag decl in the same scope as a typedef
16181     // which hides a tag decl in the same scope.  Finding this
16182     // with a redeclaration lookup can only actually happen in C++.
16183     //
16184     // This is also okay for elaborated-type-specifiers, which is
16185     // technically forbidden by the current standard but which is
16186     // okay according to the likely resolution of an open issue;
16187     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16188     if (getLangOpts().CPlusPlus) {
16189       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16190         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16191           TagDecl *Tag = TT->getDecl();
16192           if (Tag->getDeclName() == Name &&
16193               Tag->getDeclContext()->getRedeclContext()
16194                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16195             PrevDecl = Tag;
16196             Previous.clear();
16197             Previous.addDecl(Tag);
16198             Previous.resolveKind();
16199           }
16200         }
16201       }
16202     }
16203 
16204     // If this is a redeclaration of a using shadow declaration, it must
16205     // declare a tag in the same context. In MSVC mode, we allow a
16206     // redefinition if either context is within the other.
16207     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16208       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16209       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16210           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16211           !(OldTag && isAcceptableTagRedeclContext(
16212                           *this, OldTag->getDeclContext(), SearchDC))) {
16213         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16214         Diag(Shadow->getTargetDecl()->getLocation(),
16215              diag::note_using_decl_target);
16216         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16217             << 0;
16218         // Recover by ignoring the old declaration.
16219         Previous.clear();
16220         goto CreateNewDecl;
16221       }
16222     }
16223 
16224     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16225       // If this is a use of a previous tag, or if the tag is already declared
16226       // in the same scope (so that the definition/declaration completes or
16227       // rementions the tag), reuse the decl.
16228       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16229           isDeclInScope(DirectPrevDecl, SearchDC, S,
16230                         SS.isNotEmpty() || isMemberSpecialization)) {
16231         // Make sure that this wasn't declared as an enum and now used as a
16232         // struct or something similar.
16233         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16234                                           TUK == TUK_Definition, KWLoc,
16235                                           Name)) {
16236           bool SafeToContinue
16237             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16238                Kind != TTK_Enum);
16239           if (SafeToContinue)
16240             Diag(KWLoc, diag::err_use_with_wrong_tag)
16241               << Name
16242               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16243                                               PrevTagDecl->getKindName());
16244           else
16245             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16246           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16247 
16248           if (SafeToContinue)
16249             Kind = PrevTagDecl->getTagKind();
16250           else {
16251             // Recover by making this an anonymous redefinition.
16252             Name = nullptr;
16253             Previous.clear();
16254             Invalid = true;
16255           }
16256         }
16257 
16258         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16259           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16260           if (TUK == TUK_Reference || TUK == TUK_Friend)
16261             return PrevTagDecl;
16262 
16263           QualType EnumUnderlyingTy;
16264           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16265             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16266           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16267             EnumUnderlyingTy = QualType(T, 0);
16268 
16269           // All conflicts with previous declarations are recovered by
16270           // returning the previous declaration, unless this is a definition,
16271           // in which case we want the caller to bail out.
16272           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16273                                      ScopedEnum, EnumUnderlyingTy,
16274                                      IsFixed, PrevEnum))
16275             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16276         }
16277 
16278         // C++11 [class.mem]p1:
16279         //   A member shall not be declared twice in the member-specification,
16280         //   except that a nested class or member class template can be declared
16281         //   and then later defined.
16282         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16283             S->isDeclScope(PrevDecl)) {
16284           Diag(NameLoc, diag::ext_member_redeclared);
16285           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16286         }
16287 
16288         if (!Invalid) {
16289           // If this is a use, just return the declaration we found, unless
16290           // we have attributes.
16291           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16292             if (!Attrs.empty()) {
16293               // FIXME: Diagnose these attributes. For now, we create a new
16294               // declaration to hold them.
16295             } else if (TUK == TUK_Reference &&
16296                        (PrevTagDecl->getFriendObjectKind() ==
16297                             Decl::FOK_Undeclared ||
16298                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16299                        SS.isEmpty()) {
16300               // This declaration is a reference to an existing entity, but
16301               // has different visibility from that entity: it either makes
16302               // a friend visible or it makes a type visible in a new module.
16303               // In either case, create a new declaration. We only do this if
16304               // the declaration would have meant the same thing if no prior
16305               // declaration were found, that is, if it was found in the same
16306               // scope where we would have injected a declaration.
16307               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16308                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16309                 return PrevTagDecl;
16310               // This is in the injected scope, create a new declaration in
16311               // that scope.
16312               S = getTagInjectionScope(S, getLangOpts());
16313             } else {
16314               return PrevTagDecl;
16315             }
16316           }
16317 
16318           // Diagnose attempts to redefine a tag.
16319           if (TUK == TUK_Definition) {
16320             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16321               // If we're defining a specialization and the previous definition
16322               // is from an implicit instantiation, don't emit an error
16323               // here; we'll catch this in the general case below.
16324               bool IsExplicitSpecializationAfterInstantiation = false;
16325               if (isMemberSpecialization) {
16326                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16327                   IsExplicitSpecializationAfterInstantiation =
16328                     RD->getTemplateSpecializationKind() !=
16329                     TSK_ExplicitSpecialization;
16330                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16331                   IsExplicitSpecializationAfterInstantiation =
16332                     ED->getTemplateSpecializationKind() !=
16333                     TSK_ExplicitSpecialization;
16334               }
16335 
16336               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16337               // not keep more that one definition around (merge them). However,
16338               // ensure the decl passes the structural compatibility check in
16339               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16340               NamedDecl *Hidden = nullptr;
16341               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16342                 // There is a definition of this tag, but it is not visible. We
16343                 // explicitly make use of C++'s one definition rule here, and
16344                 // assume that this definition is identical to the hidden one
16345                 // we already have. Make the existing definition visible and
16346                 // use it in place of this one.
16347                 if (!getLangOpts().CPlusPlus) {
16348                   // Postpone making the old definition visible until after we
16349                   // complete parsing the new one and do the structural
16350                   // comparison.
16351                   SkipBody->CheckSameAsPrevious = true;
16352                   SkipBody->New = createTagFromNewDecl();
16353                   SkipBody->Previous = Def;
16354                   return Def;
16355                 } else {
16356                   SkipBody->ShouldSkip = true;
16357                   SkipBody->Previous = Def;
16358                   makeMergedDefinitionVisible(Hidden);
16359                   // Carry on and handle it like a normal definition. We'll
16360                   // skip starting the definitiion later.
16361                 }
16362               } else if (!IsExplicitSpecializationAfterInstantiation) {
16363                 // A redeclaration in function prototype scope in C isn't
16364                 // visible elsewhere, so merely issue a warning.
16365                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16366                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16367                 else
16368                   Diag(NameLoc, diag::err_redefinition) << Name;
16369                 notePreviousDefinition(Def,
16370                                        NameLoc.isValid() ? NameLoc : KWLoc);
16371                 // If this is a redefinition, recover by making this
16372                 // struct be anonymous, which will make any later
16373                 // references get the previous definition.
16374                 Name = nullptr;
16375                 Previous.clear();
16376                 Invalid = true;
16377               }
16378             } else {
16379               // If the type is currently being defined, complain
16380               // about a nested redefinition.
16381               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16382               if (TD->isBeingDefined()) {
16383                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16384                 Diag(PrevTagDecl->getLocation(),
16385                      diag::note_previous_definition);
16386                 Name = nullptr;
16387                 Previous.clear();
16388                 Invalid = true;
16389               }
16390             }
16391 
16392             // Okay, this is definition of a previously declared or referenced
16393             // tag. We're going to create a new Decl for it.
16394           }
16395 
16396           // Okay, we're going to make a redeclaration.  If this is some kind
16397           // of reference, make sure we build the redeclaration in the same DC
16398           // as the original, and ignore the current access specifier.
16399           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16400             SearchDC = PrevTagDecl->getDeclContext();
16401             AS = AS_none;
16402           }
16403         }
16404         // If we get here we have (another) forward declaration or we
16405         // have a definition.  Just create a new decl.
16406 
16407       } else {
16408         // If we get here, this is a definition of a new tag type in a nested
16409         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16410         // new decl/type.  We set PrevDecl to NULL so that the entities
16411         // have distinct types.
16412         Previous.clear();
16413       }
16414       // If we get here, we're going to create a new Decl. If PrevDecl
16415       // is non-NULL, it's a definition of the tag declared by
16416       // PrevDecl. If it's NULL, we have a new definition.
16417 
16418     // Otherwise, PrevDecl is not a tag, but was found with tag
16419     // lookup.  This is only actually possible in C++, where a few
16420     // things like templates still live in the tag namespace.
16421     } else {
16422       // Use a better diagnostic if an elaborated-type-specifier
16423       // found the wrong kind of type on the first
16424       // (non-redeclaration) lookup.
16425       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16426           !Previous.isForRedeclaration()) {
16427         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16428         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16429                                                        << Kind;
16430         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16431         Invalid = true;
16432 
16433       // Otherwise, only diagnose if the declaration is in scope.
16434       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16435                                 SS.isNotEmpty() || isMemberSpecialization)) {
16436         // do nothing
16437 
16438       // Diagnose implicit declarations introduced by elaborated types.
16439       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16440         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16441         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16442         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16443         Invalid = true;
16444 
16445       // Otherwise it's a declaration.  Call out a particularly common
16446       // case here.
16447       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16448         unsigned Kind = 0;
16449         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16450         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16451           << Name << Kind << TND->getUnderlyingType();
16452         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16453         Invalid = true;
16454 
16455       // Otherwise, diagnose.
16456       } else {
16457         // The tag name clashes with something else in the target scope,
16458         // issue an error and recover by making this tag be anonymous.
16459         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16460         notePreviousDefinition(PrevDecl, NameLoc);
16461         Name = nullptr;
16462         Invalid = true;
16463       }
16464 
16465       // The existing declaration isn't relevant to us; we're in a
16466       // new scope, so clear out the previous declaration.
16467       Previous.clear();
16468     }
16469   }
16470 
16471 CreateNewDecl:
16472 
16473   TagDecl *PrevDecl = nullptr;
16474   if (Previous.isSingleResult())
16475     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16476 
16477   // If there is an identifier, use the location of the identifier as the
16478   // location of the decl, otherwise use the location of the struct/union
16479   // keyword.
16480   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16481 
16482   // Otherwise, create a new declaration. If there is a previous
16483   // declaration of the same entity, the two will be linked via
16484   // PrevDecl.
16485   TagDecl *New;
16486 
16487   if (Kind == TTK_Enum) {
16488     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16489     // enum X { A, B, C } D;    D should chain to X.
16490     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16491                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16492                            ScopedEnumUsesClassTag, IsFixed);
16493 
16494     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16495       StdAlignValT = cast<EnumDecl>(New);
16496 
16497     // If this is an undefined enum, warn.
16498     if (TUK != TUK_Definition && !Invalid) {
16499       TagDecl *Def;
16500       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16501         // C++0x: 7.2p2: opaque-enum-declaration.
16502         // Conflicts are diagnosed above. Do nothing.
16503       }
16504       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16505         Diag(Loc, diag::ext_forward_ref_enum_def)
16506           << New;
16507         Diag(Def->getLocation(), diag::note_previous_definition);
16508       } else {
16509         unsigned DiagID = diag::ext_forward_ref_enum;
16510         if (getLangOpts().MSVCCompat)
16511           DiagID = diag::ext_ms_forward_ref_enum;
16512         else if (getLangOpts().CPlusPlus)
16513           DiagID = diag::err_forward_ref_enum;
16514         Diag(Loc, DiagID);
16515       }
16516     }
16517 
16518     if (EnumUnderlying) {
16519       EnumDecl *ED = cast<EnumDecl>(New);
16520       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16521         ED->setIntegerTypeSourceInfo(TI);
16522       else
16523         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16524       ED->setPromotionType(ED->getIntegerType());
16525       assert(ED->isComplete() && "enum with type should be complete");
16526     }
16527   } else {
16528     // struct/union/class
16529 
16530     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16531     // struct X { int A; } D;    D should chain to X.
16532     if (getLangOpts().CPlusPlus) {
16533       // FIXME: Look for a way to use RecordDecl for simple structs.
16534       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16535                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16536 
16537       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16538         StdBadAlloc = cast<CXXRecordDecl>(New);
16539     } else
16540       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16541                                cast_or_null<RecordDecl>(PrevDecl));
16542   }
16543 
16544   // C++11 [dcl.type]p3:
16545   //   A type-specifier-seq shall not define a class or enumeration [...].
16546   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16547       TUK == TUK_Definition) {
16548     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16549       << Context.getTagDeclType(New);
16550     Invalid = true;
16551   }
16552 
16553   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16554       DC->getDeclKind() == Decl::Enum) {
16555     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16556       << Context.getTagDeclType(New);
16557     Invalid = true;
16558   }
16559 
16560   // Maybe add qualifier info.
16561   if (SS.isNotEmpty()) {
16562     if (SS.isSet()) {
16563       // If this is either a declaration or a definition, check the
16564       // nested-name-specifier against the current context.
16565       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16566           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16567                                        isMemberSpecialization))
16568         Invalid = true;
16569 
16570       New->setQualifierInfo(SS.getWithLocInContext(Context));
16571       if (TemplateParameterLists.size() > 0) {
16572         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16573       }
16574     }
16575     else
16576       Invalid = true;
16577   }
16578 
16579   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16580     // Add alignment attributes if necessary; these attributes are checked when
16581     // the ASTContext lays out the structure.
16582     //
16583     // It is important for implementing the correct semantics that this
16584     // happen here (in ActOnTag). The #pragma pack stack is
16585     // maintained as a result of parser callbacks which can occur at
16586     // many points during the parsing of a struct declaration (because
16587     // the #pragma tokens are effectively skipped over during the
16588     // parsing of the struct).
16589     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16590       AddAlignmentAttributesForRecord(RD);
16591       AddMsStructLayoutForRecord(RD);
16592     }
16593   }
16594 
16595   if (ModulePrivateLoc.isValid()) {
16596     if (isMemberSpecialization)
16597       Diag(New->getLocation(), diag::err_module_private_specialization)
16598         << 2
16599         << FixItHint::CreateRemoval(ModulePrivateLoc);
16600     // __module_private__ does not apply to local classes. However, we only
16601     // diagnose this as an error when the declaration specifiers are
16602     // freestanding. Here, we just ignore the __module_private__.
16603     else if (!SearchDC->isFunctionOrMethod())
16604       New->setModulePrivate();
16605   }
16606 
16607   // If this is a specialization of a member class (of a class template),
16608   // check the specialization.
16609   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16610     Invalid = true;
16611 
16612   // If we're declaring or defining a tag in function prototype scope in C,
16613   // note that this type can only be used within the function and add it to
16614   // the list of decls to inject into the function definition scope.
16615   if ((Name || Kind == TTK_Enum) &&
16616       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16617     if (getLangOpts().CPlusPlus) {
16618       // C++ [dcl.fct]p6:
16619       //   Types shall not be defined in return or parameter types.
16620       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16621         Diag(Loc, diag::err_type_defined_in_param_type)
16622             << Name;
16623         Invalid = true;
16624       }
16625     } else if (!PrevDecl) {
16626       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16627     }
16628   }
16629 
16630   if (Invalid)
16631     New->setInvalidDecl();
16632 
16633   // Set the lexical context. If the tag has a C++ scope specifier, the
16634   // lexical context will be different from the semantic context.
16635   New->setLexicalDeclContext(CurContext);
16636 
16637   // Mark this as a friend decl if applicable.
16638   // In Microsoft mode, a friend declaration also acts as a forward
16639   // declaration so we always pass true to setObjectOfFriendDecl to make
16640   // the tag name visible.
16641   if (TUK == TUK_Friend)
16642     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16643 
16644   // Set the access specifier.
16645   if (!Invalid && SearchDC->isRecord())
16646     SetMemberAccessSpecifier(New, PrevDecl, AS);
16647 
16648   if (PrevDecl)
16649     CheckRedeclarationInModule(New, PrevDecl);
16650 
16651   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16652     New->startDefinition();
16653 
16654   ProcessDeclAttributeList(S, New, Attrs);
16655   AddPragmaAttributes(S, New);
16656 
16657   // If this has an identifier, add it to the scope stack.
16658   if (TUK == TUK_Friend) {
16659     // We might be replacing an existing declaration in the lookup tables;
16660     // if so, borrow its access specifier.
16661     if (PrevDecl)
16662       New->setAccess(PrevDecl->getAccess());
16663 
16664     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16665     DC->makeDeclVisibleInContext(New);
16666     if (Name) // can be null along some error paths
16667       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16668         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16669   } else if (Name) {
16670     S = getNonFieldDeclScope(S);
16671     PushOnScopeChains(New, S, true);
16672   } else {
16673     CurContext->addDecl(New);
16674   }
16675 
16676   // If this is the C FILE type, notify the AST context.
16677   if (IdentifierInfo *II = New->getIdentifier())
16678     if (!New->isInvalidDecl() &&
16679         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16680         II->isStr("FILE"))
16681       Context.setFILEDecl(New);
16682 
16683   if (PrevDecl)
16684     mergeDeclAttributes(New, PrevDecl);
16685 
16686   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16687     inferGslOwnerPointerAttribute(CXXRD);
16688 
16689   // If there's a #pragma GCC visibility in scope, set the visibility of this
16690   // record.
16691   AddPushedVisibilityAttribute(New);
16692 
16693   if (isMemberSpecialization && !New->isInvalidDecl())
16694     CompleteMemberSpecialization(New, Previous);
16695 
16696   OwnedDecl = true;
16697   // In C++, don't return an invalid declaration. We can't recover well from
16698   // the cases where we make the type anonymous.
16699   if (Invalid && getLangOpts().CPlusPlus) {
16700     if (New->isBeingDefined())
16701       if (auto RD = dyn_cast<RecordDecl>(New))
16702         RD->completeDefinition();
16703     return nullptr;
16704   } else if (SkipBody && SkipBody->ShouldSkip) {
16705     return SkipBody->Previous;
16706   } else {
16707     return New;
16708   }
16709 }
16710 
16711 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16712   AdjustDeclIfTemplate(TagD);
16713   TagDecl *Tag = cast<TagDecl>(TagD);
16714 
16715   // Enter the tag context.
16716   PushDeclContext(S, Tag);
16717 
16718   ActOnDocumentableDecl(TagD);
16719 
16720   // If there's a #pragma GCC visibility in scope, set the visibility of this
16721   // record.
16722   AddPushedVisibilityAttribute(Tag);
16723 }
16724 
16725 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16726   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16727     return false;
16728 
16729   // Make the previous decl visible.
16730   makeMergedDefinitionVisible(SkipBody.Previous);
16731   return true;
16732 }
16733 
16734 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16735   assert(isa<ObjCContainerDecl>(IDecl) &&
16736          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16737   DeclContext *OCD = cast<DeclContext>(IDecl);
16738   assert(OCD->getLexicalParent() == CurContext &&
16739       "The next DeclContext should be lexically contained in the current one.");
16740   CurContext = OCD;
16741   return IDecl;
16742 }
16743 
16744 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16745                                            SourceLocation FinalLoc,
16746                                            bool IsFinalSpelledSealed,
16747                                            bool IsAbstract,
16748                                            SourceLocation LBraceLoc) {
16749   AdjustDeclIfTemplate(TagD);
16750   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16751 
16752   FieldCollector->StartClass();
16753 
16754   if (!Record->getIdentifier())
16755     return;
16756 
16757   if (IsAbstract)
16758     Record->markAbstract();
16759 
16760   if (FinalLoc.isValid()) {
16761     Record->addAttr(FinalAttr::Create(
16762         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16763         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16764   }
16765   // C++ [class]p2:
16766   //   [...] The class-name is also inserted into the scope of the
16767   //   class itself; this is known as the injected-class-name. For
16768   //   purposes of access checking, the injected-class-name is treated
16769   //   as if it were a public member name.
16770   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16771       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16772       Record->getLocation(), Record->getIdentifier(),
16773       /*PrevDecl=*/nullptr,
16774       /*DelayTypeCreation=*/true);
16775   Context.getTypeDeclType(InjectedClassName, Record);
16776   InjectedClassName->setImplicit();
16777   InjectedClassName->setAccess(AS_public);
16778   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16779       InjectedClassName->setDescribedClassTemplate(Template);
16780   PushOnScopeChains(InjectedClassName, S);
16781   assert(InjectedClassName->isInjectedClassName() &&
16782          "Broken injected-class-name");
16783 }
16784 
16785 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16786                                     SourceRange BraceRange) {
16787   AdjustDeclIfTemplate(TagD);
16788   TagDecl *Tag = cast<TagDecl>(TagD);
16789   Tag->setBraceRange(BraceRange);
16790 
16791   // Make sure we "complete" the definition even it is invalid.
16792   if (Tag->isBeingDefined()) {
16793     assert(Tag->isInvalidDecl() && "We should already have completed it");
16794     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16795       RD->completeDefinition();
16796   }
16797 
16798   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16799     FieldCollector->FinishClass();
16800     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
16801       auto *Def = RD->getDefinition();
16802       assert(Def && "The record is expected to have a completed definition");
16803       unsigned NumInitMethods = 0;
16804       for (auto *Method : Def->methods()) {
16805         if (!Method->getIdentifier())
16806             continue;
16807         if (Method->getName() == "__init")
16808           NumInitMethods++;
16809       }
16810       if (NumInitMethods > 1 || !Def->hasInitMethod())
16811         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16812     }
16813   }
16814 
16815   // Exit this scope of this tag's definition.
16816   PopDeclContext();
16817 
16818   if (getCurLexicalContext()->isObjCContainer() &&
16819       Tag->getDeclContext()->isFileContext())
16820     Tag->setTopLevelDeclInObjCContainer();
16821 
16822   // Notify the consumer that we've defined a tag.
16823   if (!Tag->isInvalidDecl())
16824     Consumer.HandleTagDeclDefinition(Tag);
16825 
16826   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16827   // from XLs and instead matches the XL #pragma pack(1) behavior.
16828   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16829       AlignPackStack.hasValue()) {
16830     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16831     // Only diagnose #pragma align(packed).
16832     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16833       return;
16834     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16835     if (!RD)
16836       return;
16837     // Only warn if there is at least 1 bitfield member.
16838     if (llvm::any_of(RD->fields(),
16839                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16840       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16841   }
16842 }
16843 
16844 void Sema::ActOnObjCContainerFinishDefinition() {
16845   // Exit this scope of this interface definition.
16846   PopDeclContext();
16847 }
16848 
16849 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16850   assert(DC == CurContext && "Mismatch of container contexts");
16851   OriginalLexicalContext = DC;
16852   ActOnObjCContainerFinishDefinition();
16853 }
16854 
16855 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16856   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16857   OriginalLexicalContext = nullptr;
16858 }
16859 
16860 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16861   AdjustDeclIfTemplate(TagD);
16862   TagDecl *Tag = cast<TagDecl>(TagD);
16863   Tag->setInvalidDecl();
16864 
16865   // Make sure we "complete" the definition even it is invalid.
16866   if (Tag->isBeingDefined()) {
16867     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16868       RD->completeDefinition();
16869   }
16870 
16871   // We're undoing ActOnTagStartDefinition here, not
16872   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16873   // the FieldCollector.
16874 
16875   PopDeclContext();
16876 }
16877 
16878 // Note that FieldName may be null for anonymous bitfields.
16879 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16880                                 IdentifierInfo *FieldName,
16881                                 QualType FieldTy, bool IsMsStruct,
16882                                 Expr *BitWidth, bool *ZeroWidth) {
16883   assert(BitWidth);
16884   if (BitWidth->containsErrors())
16885     return ExprError();
16886 
16887   // Default to true; that shouldn't confuse checks for emptiness
16888   if (ZeroWidth)
16889     *ZeroWidth = true;
16890 
16891   // C99 6.7.2.1p4 - verify the field type.
16892   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16893   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16894     // Handle incomplete and sizeless types with a specific error.
16895     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16896                                  diag::err_field_incomplete_or_sizeless))
16897       return ExprError();
16898     if (FieldName)
16899       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16900         << FieldName << FieldTy << BitWidth->getSourceRange();
16901     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16902       << FieldTy << BitWidth->getSourceRange();
16903   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16904                                              UPPC_BitFieldWidth))
16905     return ExprError();
16906 
16907   // If the bit-width is type- or value-dependent, don't try to check
16908   // it now.
16909   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16910     return BitWidth;
16911 
16912   llvm::APSInt Value;
16913   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16914   if (ICE.isInvalid())
16915     return ICE;
16916   BitWidth = ICE.get();
16917 
16918   if (Value != 0 && ZeroWidth)
16919     *ZeroWidth = false;
16920 
16921   // Zero-width bitfield is ok for anonymous field.
16922   if (Value == 0 && FieldName)
16923     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16924 
16925   if (Value.isSigned() && Value.isNegative()) {
16926     if (FieldName)
16927       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16928                << FieldName << toString(Value, 10);
16929     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16930       << toString(Value, 10);
16931   }
16932 
16933   // The size of the bit-field must not exceed our maximum permitted object
16934   // size.
16935   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16936     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16937            << !FieldName << FieldName << toString(Value, 10);
16938   }
16939 
16940   if (!FieldTy->isDependentType()) {
16941     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16942     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16943     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16944 
16945     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16946     // ABI.
16947     bool CStdConstraintViolation =
16948         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16949     bool MSBitfieldViolation =
16950         Value.ugt(TypeStorageSize) &&
16951         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16952     if (CStdConstraintViolation || MSBitfieldViolation) {
16953       unsigned DiagWidth =
16954           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16955       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16956              << (bool)FieldName << FieldName << toString(Value, 10)
16957              << !CStdConstraintViolation << DiagWidth;
16958     }
16959 
16960     // Warn on types where the user might conceivably expect to get all
16961     // specified bits as value bits: that's all integral types other than
16962     // 'bool'.
16963     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16964       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16965           << FieldName << toString(Value, 10)
16966           << (unsigned)TypeWidth;
16967     }
16968   }
16969 
16970   return BitWidth;
16971 }
16972 
16973 /// ActOnField - Each field of a C struct/union is passed into this in order
16974 /// to create a FieldDecl object for it.
16975 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16976                        Declarator &D, Expr *BitfieldWidth) {
16977   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16978                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16979                                /*InitStyle=*/ICIS_NoInit, AS_public);
16980   return Res;
16981 }
16982 
16983 /// HandleField - Analyze a field of a C struct or a C++ data member.
16984 ///
16985 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16986                              SourceLocation DeclStart,
16987                              Declarator &D, Expr *BitWidth,
16988                              InClassInitStyle InitStyle,
16989                              AccessSpecifier AS) {
16990   if (D.isDecompositionDeclarator()) {
16991     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16992     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16993       << Decomp.getSourceRange();
16994     return nullptr;
16995   }
16996 
16997   IdentifierInfo *II = D.getIdentifier();
16998   SourceLocation Loc = DeclStart;
16999   if (II) Loc = D.getIdentifierLoc();
17000 
17001   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17002   QualType T = TInfo->getType();
17003   if (getLangOpts().CPlusPlus) {
17004     CheckExtraCXXDefaultArguments(D);
17005 
17006     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17007                                         UPPC_DataMemberType)) {
17008       D.setInvalidType();
17009       T = Context.IntTy;
17010       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17011     }
17012   }
17013 
17014   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17015 
17016   if (D.getDeclSpec().isInlineSpecified())
17017     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17018         << getLangOpts().CPlusPlus17;
17019   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17020     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17021          diag::err_invalid_thread)
17022       << DeclSpec::getSpecifierName(TSCS);
17023 
17024   // Check to see if this name was declared as a member previously
17025   NamedDecl *PrevDecl = nullptr;
17026   LookupResult Previous(*this, II, Loc, LookupMemberName,
17027                         ForVisibleRedeclaration);
17028   LookupName(Previous, S);
17029   switch (Previous.getResultKind()) {
17030     case LookupResult::Found:
17031     case LookupResult::FoundUnresolvedValue:
17032       PrevDecl = Previous.getAsSingle<NamedDecl>();
17033       break;
17034 
17035     case LookupResult::FoundOverloaded:
17036       PrevDecl = Previous.getRepresentativeDecl();
17037       break;
17038 
17039     case LookupResult::NotFound:
17040     case LookupResult::NotFoundInCurrentInstantiation:
17041     case LookupResult::Ambiguous:
17042       break;
17043   }
17044   Previous.suppressDiagnostics();
17045 
17046   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17047     // Maybe we will complain about the shadowed template parameter.
17048     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17049     // Just pretend that we didn't see the previous declaration.
17050     PrevDecl = nullptr;
17051   }
17052 
17053   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17054     PrevDecl = nullptr;
17055 
17056   bool Mutable
17057     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17058   SourceLocation TSSL = D.getBeginLoc();
17059   FieldDecl *NewFD
17060     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17061                      TSSL, AS, PrevDecl, &D);
17062 
17063   if (NewFD->isInvalidDecl())
17064     Record->setInvalidDecl();
17065 
17066   if (D.getDeclSpec().isModulePrivateSpecified())
17067     NewFD->setModulePrivate();
17068 
17069   if (NewFD->isInvalidDecl() && PrevDecl) {
17070     // Don't introduce NewFD into scope; there's already something
17071     // with the same name in the same scope.
17072   } else if (II) {
17073     PushOnScopeChains(NewFD, S);
17074   } else
17075     Record->addDecl(NewFD);
17076 
17077   return NewFD;
17078 }
17079 
17080 /// Build a new FieldDecl and check its well-formedness.
17081 ///
17082 /// This routine builds a new FieldDecl given the fields name, type,
17083 /// record, etc. \p PrevDecl should refer to any previous declaration
17084 /// with the same name and in the same scope as the field to be
17085 /// created.
17086 ///
17087 /// \returns a new FieldDecl.
17088 ///
17089 /// \todo The Declarator argument is a hack. It will be removed once
17090 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17091                                 TypeSourceInfo *TInfo,
17092                                 RecordDecl *Record, SourceLocation Loc,
17093                                 bool Mutable, Expr *BitWidth,
17094                                 InClassInitStyle InitStyle,
17095                                 SourceLocation TSSL,
17096                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17097                                 Declarator *D) {
17098   IdentifierInfo *II = Name.getAsIdentifierInfo();
17099   bool InvalidDecl = false;
17100   if (D) InvalidDecl = D->isInvalidType();
17101 
17102   // If we receive a broken type, recover by assuming 'int' and
17103   // marking this declaration as invalid.
17104   if (T.isNull() || T->containsErrors()) {
17105     InvalidDecl = true;
17106     T = Context.IntTy;
17107   }
17108 
17109   QualType EltTy = Context.getBaseElementType(T);
17110   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17111     if (RequireCompleteSizedType(Loc, EltTy,
17112                                  diag::err_field_incomplete_or_sizeless)) {
17113       // Fields of incomplete type force their record to be invalid.
17114       Record->setInvalidDecl();
17115       InvalidDecl = true;
17116     } else {
17117       NamedDecl *Def;
17118       EltTy->isIncompleteType(&Def);
17119       if (Def && Def->isInvalidDecl()) {
17120         Record->setInvalidDecl();
17121         InvalidDecl = true;
17122       }
17123     }
17124   }
17125 
17126   // TR 18037 does not allow fields to be declared with address space
17127   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17128       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17129     Diag(Loc, diag::err_field_with_address_space);
17130     Record->setInvalidDecl();
17131     InvalidDecl = true;
17132   }
17133 
17134   if (LangOpts.OpenCL) {
17135     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17136     // used as structure or union field: image, sampler, event or block types.
17137     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17138         T->isBlockPointerType()) {
17139       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17140       Record->setInvalidDecl();
17141       InvalidDecl = true;
17142     }
17143     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17144     // is enabled.
17145     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17146                         "__cl_clang_bitfields", LangOpts)) {
17147       Diag(Loc, diag::err_opencl_bitfields);
17148       InvalidDecl = true;
17149     }
17150   }
17151 
17152   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17153   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17154       T.hasQualifiers()) {
17155     InvalidDecl = true;
17156     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17157   }
17158 
17159   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17160   // than a variably modified type.
17161   if (!InvalidDecl && T->isVariablyModifiedType()) {
17162     if (!tryToFixVariablyModifiedVarType(
17163             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17164       InvalidDecl = true;
17165   }
17166 
17167   // Fields can not have abstract class types
17168   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17169                                              diag::err_abstract_type_in_decl,
17170                                              AbstractFieldType))
17171     InvalidDecl = true;
17172 
17173   bool ZeroWidth = false;
17174   if (InvalidDecl)
17175     BitWidth = nullptr;
17176   // If this is declared as a bit-field, check the bit-field.
17177   if (BitWidth) {
17178     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17179                               &ZeroWidth).get();
17180     if (!BitWidth) {
17181       InvalidDecl = true;
17182       BitWidth = nullptr;
17183       ZeroWidth = false;
17184     }
17185   }
17186 
17187   // Check that 'mutable' is consistent with the type of the declaration.
17188   if (!InvalidDecl && Mutable) {
17189     unsigned DiagID = 0;
17190     if (T->isReferenceType())
17191       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17192                                         : diag::err_mutable_reference;
17193     else if (T.isConstQualified())
17194       DiagID = diag::err_mutable_const;
17195 
17196     if (DiagID) {
17197       SourceLocation ErrLoc = Loc;
17198       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17199         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17200       Diag(ErrLoc, DiagID);
17201       if (DiagID != diag::ext_mutable_reference) {
17202         Mutable = false;
17203         InvalidDecl = true;
17204       }
17205     }
17206   }
17207 
17208   // C++11 [class.union]p8 (DR1460):
17209   //   At most one variant member of a union may have a
17210   //   brace-or-equal-initializer.
17211   if (InitStyle != ICIS_NoInit)
17212     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17213 
17214   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17215                                        BitWidth, Mutable, InitStyle);
17216   if (InvalidDecl)
17217     NewFD->setInvalidDecl();
17218 
17219   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17220     Diag(Loc, diag::err_duplicate_member) << II;
17221     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17222     NewFD->setInvalidDecl();
17223   }
17224 
17225   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17226     if (Record->isUnion()) {
17227       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17228         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17229         if (RDecl->getDefinition()) {
17230           // C++ [class.union]p1: An object of a class with a non-trivial
17231           // constructor, a non-trivial copy constructor, a non-trivial
17232           // destructor, or a non-trivial copy assignment operator
17233           // cannot be a member of a union, nor can an array of such
17234           // objects.
17235           if (CheckNontrivialField(NewFD))
17236             NewFD->setInvalidDecl();
17237         }
17238       }
17239 
17240       // C++ [class.union]p1: If a union contains a member of reference type,
17241       // the program is ill-formed, except when compiling with MSVC extensions
17242       // enabled.
17243       if (EltTy->isReferenceType()) {
17244         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17245                                     diag::ext_union_member_of_reference_type :
17246                                     diag::err_union_member_of_reference_type)
17247           << NewFD->getDeclName() << EltTy;
17248         if (!getLangOpts().MicrosoftExt)
17249           NewFD->setInvalidDecl();
17250       }
17251     }
17252   }
17253 
17254   // FIXME: We need to pass in the attributes given an AST
17255   // representation, not a parser representation.
17256   if (D) {
17257     // FIXME: The current scope is almost... but not entirely... correct here.
17258     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17259 
17260     if (NewFD->hasAttrs())
17261       CheckAlignasUnderalignment(NewFD);
17262   }
17263 
17264   // In auto-retain/release, infer strong retension for fields of
17265   // retainable type.
17266   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17267     NewFD->setInvalidDecl();
17268 
17269   if (T.isObjCGCWeak())
17270     Diag(Loc, diag::warn_attribute_weak_on_field);
17271 
17272   // PPC MMA non-pointer types are not allowed as field types.
17273   if (Context.getTargetInfo().getTriple().isPPC64() &&
17274       CheckPPCMMAType(T, NewFD->getLocation()))
17275     NewFD->setInvalidDecl();
17276 
17277   NewFD->setAccess(AS);
17278   return NewFD;
17279 }
17280 
17281 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17282   assert(FD);
17283   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17284 
17285   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17286     return false;
17287 
17288   QualType EltTy = Context.getBaseElementType(FD->getType());
17289   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17290     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17291     if (RDecl->getDefinition()) {
17292       // We check for copy constructors before constructors
17293       // because otherwise we'll never get complaints about
17294       // copy constructors.
17295 
17296       CXXSpecialMember member = CXXInvalid;
17297       // We're required to check for any non-trivial constructors. Since the
17298       // implicit default constructor is suppressed if there are any
17299       // user-declared constructors, we just need to check that there is a
17300       // trivial default constructor and a trivial copy constructor. (We don't
17301       // worry about move constructors here, since this is a C++98 check.)
17302       if (RDecl->hasNonTrivialCopyConstructor())
17303         member = CXXCopyConstructor;
17304       else if (!RDecl->hasTrivialDefaultConstructor())
17305         member = CXXDefaultConstructor;
17306       else if (RDecl->hasNonTrivialCopyAssignment())
17307         member = CXXCopyAssignment;
17308       else if (RDecl->hasNonTrivialDestructor())
17309         member = CXXDestructor;
17310 
17311       if (member != CXXInvalid) {
17312         if (!getLangOpts().CPlusPlus11 &&
17313             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17314           // Objective-C++ ARC: it is an error to have a non-trivial field of
17315           // a union. However, system headers in Objective-C programs
17316           // occasionally have Objective-C lifetime objects within unions,
17317           // and rather than cause the program to fail, we make those
17318           // members unavailable.
17319           SourceLocation Loc = FD->getLocation();
17320           if (getSourceManager().isInSystemHeader(Loc)) {
17321             if (!FD->hasAttr<UnavailableAttr>())
17322               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17323                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17324             return false;
17325           }
17326         }
17327 
17328         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17329                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17330                diag::err_illegal_union_or_anon_struct_member)
17331           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17332         DiagnoseNontrivial(RDecl, member);
17333         return !getLangOpts().CPlusPlus11;
17334       }
17335     }
17336   }
17337 
17338   return false;
17339 }
17340 
17341 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17342 ///  AST enum value.
17343 static ObjCIvarDecl::AccessControl
17344 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17345   switch (ivarVisibility) {
17346   default: llvm_unreachable("Unknown visitibility kind");
17347   case tok::objc_private: return ObjCIvarDecl::Private;
17348   case tok::objc_public: return ObjCIvarDecl::Public;
17349   case tok::objc_protected: return ObjCIvarDecl::Protected;
17350   case tok::objc_package: return ObjCIvarDecl::Package;
17351   }
17352 }
17353 
17354 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17355 /// in order to create an IvarDecl object for it.
17356 Decl *Sema::ActOnIvar(Scope *S,
17357                                 SourceLocation DeclStart,
17358                                 Declarator &D, Expr *BitfieldWidth,
17359                                 tok::ObjCKeywordKind Visibility) {
17360 
17361   IdentifierInfo *II = D.getIdentifier();
17362   Expr *BitWidth = (Expr*)BitfieldWidth;
17363   SourceLocation Loc = DeclStart;
17364   if (II) Loc = D.getIdentifierLoc();
17365 
17366   // FIXME: Unnamed fields can be handled in various different ways, for
17367   // example, unnamed unions inject all members into the struct namespace!
17368 
17369   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17370   QualType T = TInfo->getType();
17371 
17372   if (BitWidth) {
17373     // 6.7.2.1p3, 6.7.2.1p4
17374     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17375     if (!BitWidth)
17376       D.setInvalidType();
17377   } else {
17378     // Not a bitfield.
17379 
17380     // validate II.
17381 
17382   }
17383   if (T->isReferenceType()) {
17384     Diag(Loc, diag::err_ivar_reference_type);
17385     D.setInvalidType();
17386   }
17387   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17388   // than a variably modified type.
17389   else if (T->isVariablyModifiedType()) {
17390     if (!tryToFixVariablyModifiedVarType(
17391             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17392       D.setInvalidType();
17393   }
17394 
17395   // Get the visibility (access control) for this ivar.
17396   ObjCIvarDecl::AccessControl ac =
17397     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17398                                         : ObjCIvarDecl::None;
17399   // Must set ivar's DeclContext to its enclosing interface.
17400   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17401   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17402     return nullptr;
17403   ObjCContainerDecl *EnclosingContext;
17404   if (ObjCImplementationDecl *IMPDecl =
17405       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17406     if (LangOpts.ObjCRuntime.isFragile()) {
17407     // Case of ivar declared in an implementation. Context is that of its class.
17408       EnclosingContext = IMPDecl->getClassInterface();
17409       assert(EnclosingContext && "Implementation has no class interface!");
17410     }
17411     else
17412       EnclosingContext = EnclosingDecl;
17413   } else {
17414     if (ObjCCategoryDecl *CDecl =
17415         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17416       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17417         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17418         return nullptr;
17419       }
17420     }
17421     EnclosingContext = EnclosingDecl;
17422   }
17423 
17424   // Construct the decl.
17425   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17426                                              DeclStart, Loc, II, T,
17427                                              TInfo, ac, (Expr *)BitfieldWidth);
17428 
17429   if (II) {
17430     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17431                                            ForVisibleRedeclaration);
17432     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17433         && !isa<TagDecl>(PrevDecl)) {
17434       Diag(Loc, diag::err_duplicate_member) << II;
17435       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17436       NewID->setInvalidDecl();
17437     }
17438   }
17439 
17440   // Process attributes attached to the ivar.
17441   ProcessDeclAttributes(S, NewID, D);
17442 
17443   if (D.isInvalidType())
17444     NewID->setInvalidDecl();
17445 
17446   // In ARC, infer 'retaining' for ivars of retainable type.
17447   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17448     NewID->setInvalidDecl();
17449 
17450   if (D.getDeclSpec().isModulePrivateSpecified())
17451     NewID->setModulePrivate();
17452 
17453   if (II) {
17454     // FIXME: When interfaces are DeclContexts, we'll need to add
17455     // these to the interface.
17456     S->AddDecl(NewID);
17457     IdResolver.AddDecl(NewID);
17458   }
17459 
17460   if (LangOpts.ObjCRuntime.isNonFragile() &&
17461       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17462     Diag(Loc, diag::warn_ivars_in_interface);
17463 
17464   return NewID;
17465 }
17466 
17467 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17468 /// class and class extensions. For every class \@interface and class
17469 /// extension \@interface, if the last ivar is a bitfield of any type,
17470 /// then add an implicit `char :0` ivar to the end of that interface.
17471 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17472                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17473   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17474     return;
17475 
17476   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17477   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17478 
17479   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17480     return;
17481   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17482   if (!ID) {
17483     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17484       if (!CD->IsClassExtension())
17485         return;
17486     }
17487     // No need to add this to end of @implementation.
17488     else
17489       return;
17490   }
17491   // All conditions are met. Add a new bitfield to the tail end of ivars.
17492   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17493   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17494 
17495   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17496                               DeclLoc, DeclLoc, nullptr,
17497                               Context.CharTy,
17498                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17499                                                                DeclLoc),
17500                               ObjCIvarDecl::Private, BW,
17501                               true);
17502   AllIvarDecls.push_back(Ivar);
17503 }
17504 
17505 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17506                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17507                        SourceLocation RBrac,
17508                        const ParsedAttributesView &Attrs) {
17509   assert(EnclosingDecl && "missing record or interface decl");
17510 
17511   // If this is an Objective-C @implementation or category and we have
17512   // new fields here we should reset the layout of the interface since
17513   // it will now change.
17514   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17515     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17516     switch (DC->getKind()) {
17517     default: break;
17518     case Decl::ObjCCategory:
17519       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17520       break;
17521     case Decl::ObjCImplementation:
17522       Context.
17523         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17524       break;
17525     }
17526   }
17527 
17528   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17529   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17530 
17531   // Start counting up the number of named members; make sure to include
17532   // members of anonymous structs and unions in the total.
17533   unsigned NumNamedMembers = 0;
17534   if (Record) {
17535     for (const auto *I : Record->decls()) {
17536       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17537         if (IFD->getDeclName())
17538           ++NumNamedMembers;
17539     }
17540   }
17541 
17542   // Verify that all the fields are okay.
17543   SmallVector<FieldDecl*, 32> RecFields;
17544 
17545   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17546        i != end; ++i) {
17547     FieldDecl *FD = cast<FieldDecl>(*i);
17548 
17549     // Get the type for the field.
17550     const Type *FDTy = FD->getType().getTypePtr();
17551 
17552     if (!FD->isAnonymousStructOrUnion()) {
17553       // Remember all fields written by the user.
17554       RecFields.push_back(FD);
17555     }
17556 
17557     // If the field is already invalid for some reason, don't emit more
17558     // diagnostics about it.
17559     if (FD->isInvalidDecl()) {
17560       EnclosingDecl->setInvalidDecl();
17561       continue;
17562     }
17563 
17564     // C99 6.7.2.1p2:
17565     //   A structure or union shall not contain a member with
17566     //   incomplete or function type (hence, a structure shall not
17567     //   contain an instance of itself, but may contain a pointer to
17568     //   an instance of itself), except that the last member of a
17569     //   structure with more than one named member may have incomplete
17570     //   array type; such a structure (and any union containing,
17571     //   possibly recursively, a member that is such a structure)
17572     //   shall not be a member of a structure or an element of an
17573     //   array.
17574     bool IsLastField = (i + 1 == Fields.end());
17575     if (FDTy->isFunctionType()) {
17576       // Field declared as a function.
17577       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17578         << FD->getDeclName();
17579       FD->setInvalidDecl();
17580       EnclosingDecl->setInvalidDecl();
17581       continue;
17582     } else if (FDTy->isIncompleteArrayType() &&
17583                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17584       if (Record) {
17585         // Flexible array member.
17586         // Microsoft and g++ is more permissive regarding flexible array.
17587         // It will accept flexible array in union and also
17588         // as the sole element of a struct/class.
17589         unsigned DiagID = 0;
17590         if (!Record->isUnion() && !IsLastField) {
17591           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17592             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17593           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17594           FD->setInvalidDecl();
17595           EnclosingDecl->setInvalidDecl();
17596           continue;
17597         } else if (Record->isUnion())
17598           DiagID = getLangOpts().MicrosoftExt
17599                        ? diag::ext_flexible_array_union_ms
17600                        : getLangOpts().CPlusPlus
17601                              ? diag::ext_flexible_array_union_gnu
17602                              : diag::err_flexible_array_union;
17603         else if (NumNamedMembers < 1)
17604           DiagID = getLangOpts().MicrosoftExt
17605                        ? diag::ext_flexible_array_empty_aggregate_ms
17606                        : getLangOpts().CPlusPlus
17607                              ? diag::ext_flexible_array_empty_aggregate_gnu
17608                              : diag::err_flexible_array_empty_aggregate;
17609 
17610         if (DiagID)
17611           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17612                                           << Record->getTagKind();
17613         // While the layout of types that contain virtual bases is not specified
17614         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17615         // virtual bases after the derived members.  This would make a flexible
17616         // array member declared at the end of an object not adjacent to the end
17617         // of the type.
17618         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17619           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17620               << FD->getDeclName() << Record->getTagKind();
17621         if (!getLangOpts().C99)
17622           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17623             << FD->getDeclName() << Record->getTagKind();
17624 
17625         // If the element type has a non-trivial destructor, we would not
17626         // implicitly destroy the elements, so disallow it for now.
17627         //
17628         // FIXME: GCC allows this. We should probably either implicitly delete
17629         // the destructor of the containing class, or just allow this.
17630         QualType BaseElem = Context.getBaseElementType(FD->getType());
17631         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17632           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17633             << FD->getDeclName() << FD->getType();
17634           FD->setInvalidDecl();
17635           EnclosingDecl->setInvalidDecl();
17636           continue;
17637         }
17638         // Okay, we have a legal flexible array member at the end of the struct.
17639         Record->setHasFlexibleArrayMember(true);
17640       } else {
17641         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17642         // unless they are followed by another ivar. That check is done
17643         // elsewhere, after synthesized ivars are known.
17644       }
17645     } else if (!FDTy->isDependentType() &&
17646                RequireCompleteSizedType(
17647                    FD->getLocation(), FD->getType(),
17648                    diag::err_field_incomplete_or_sizeless)) {
17649       // Incomplete type
17650       FD->setInvalidDecl();
17651       EnclosingDecl->setInvalidDecl();
17652       continue;
17653     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17654       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17655         // A type which contains a flexible array member is considered to be a
17656         // flexible array member.
17657         Record->setHasFlexibleArrayMember(true);
17658         if (!Record->isUnion()) {
17659           // If this is a struct/class and this is not the last element, reject
17660           // it.  Note that GCC supports variable sized arrays in the middle of
17661           // structures.
17662           if (!IsLastField)
17663             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17664               << FD->getDeclName() << FD->getType();
17665           else {
17666             // We support flexible arrays at the end of structs in
17667             // other structs as an extension.
17668             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17669               << FD->getDeclName();
17670           }
17671         }
17672       }
17673       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17674           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17675                                  diag::err_abstract_type_in_decl,
17676                                  AbstractIvarType)) {
17677         // Ivars can not have abstract class types
17678         FD->setInvalidDecl();
17679       }
17680       if (Record && FDTTy->getDecl()->hasObjectMember())
17681         Record->setHasObjectMember(true);
17682       if (Record && FDTTy->getDecl()->hasVolatileMember())
17683         Record->setHasVolatileMember(true);
17684     } else if (FDTy->isObjCObjectType()) {
17685       /// A field cannot be an Objective-c object
17686       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17687         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17688       QualType T = Context.getObjCObjectPointerType(FD->getType());
17689       FD->setType(T);
17690     } else if (Record && Record->isUnion() &&
17691                FD->getType().hasNonTrivialObjCLifetime() &&
17692                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17693                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17694                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17695                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17696       // For backward compatibility, fields of C unions declared in system
17697       // headers that have non-trivial ObjC ownership qualifications are marked
17698       // as unavailable unless the qualifier is explicit and __strong. This can
17699       // break ABI compatibility between programs compiled with ARC and MRR, but
17700       // is a better option than rejecting programs using those unions under
17701       // ARC.
17702       FD->addAttr(UnavailableAttr::CreateImplicit(
17703           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17704           FD->getLocation()));
17705     } else if (getLangOpts().ObjC &&
17706                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17707                !Record->hasObjectMember()) {
17708       if (FD->getType()->isObjCObjectPointerType() ||
17709           FD->getType().isObjCGCStrong())
17710         Record->setHasObjectMember(true);
17711       else if (Context.getAsArrayType(FD->getType())) {
17712         QualType BaseType = Context.getBaseElementType(FD->getType());
17713         if (BaseType->isRecordType() &&
17714             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17715           Record->setHasObjectMember(true);
17716         else if (BaseType->isObjCObjectPointerType() ||
17717                  BaseType.isObjCGCStrong())
17718                Record->setHasObjectMember(true);
17719       }
17720     }
17721 
17722     if (Record && !getLangOpts().CPlusPlus &&
17723         !shouldIgnoreForRecordTriviality(FD)) {
17724       QualType FT = FD->getType();
17725       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17726         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17727         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17728             Record->isUnion())
17729           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17730       }
17731       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17732       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17733         Record->setNonTrivialToPrimitiveCopy(true);
17734         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17735           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17736       }
17737       if (FT.isDestructedType()) {
17738         Record->setNonTrivialToPrimitiveDestroy(true);
17739         Record->setParamDestroyedInCallee(true);
17740         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17741           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17742       }
17743 
17744       if (const auto *RT = FT->getAs<RecordType>()) {
17745         if (RT->getDecl()->getArgPassingRestrictions() ==
17746             RecordDecl::APK_CanNeverPassInRegs)
17747           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17748       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17749         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17750     }
17751 
17752     if (Record && FD->getType().isVolatileQualified())
17753       Record->setHasVolatileMember(true);
17754     // Keep track of the number of named members.
17755     if (FD->getIdentifier())
17756       ++NumNamedMembers;
17757   }
17758 
17759   // Okay, we successfully defined 'Record'.
17760   if (Record) {
17761     bool Completed = false;
17762     if (CXXRecord) {
17763       if (!CXXRecord->isInvalidDecl()) {
17764         // Set access bits correctly on the directly-declared conversions.
17765         for (CXXRecordDecl::conversion_iterator
17766                I = CXXRecord->conversion_begin(),
17767                E = CXXRecord->conversion_end(); I != E; ++I)
17768           I.setAccess((*I)->getAccess());
17769       }
17770 
17771       // Add any implicitly-declared members to this class.
17772       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17773 
17774       if (!CXXRecord->isDependentType()) {
17775         if (!CXXRecord->isInvalidDecl()) {
17776           // If we have virtual base classes, we may end up finding multiple
17777           // final overriders for a given virtual function. Check for this
17778           // problem now.
17779           if (CXXRecord->getNumVBases()) {
17780             CXXFinalOverriderMap FinalOverriders;
17781             CXXRecord->getFinalOverriders(FinalOverriders);
17782 
17783             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17784                                              MEnd = FinalOverriders.end();
17785                  M != MEnd; ++M) {
17786               for (OverridingMethods::iterator SO = M->second.begin(),
17787                                             SOEnd = M->second.end();
17788                    SO != SOEnd; ++SO) {
17789                 assert(SO->second.size() > 0 &&
17790                        "Virtual function without overriding functions?");
17791                 if (SO->second.size() == 1)
17792                   continue;
17793 
17794                 // C++ [class.virtual]p2:
17795                 //   In a derived class, if a virtual member function of a base
17796                 //   class subobject has more than one final overrider the
17797                 //   program is ill-formed.
17798                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17799                   << (const NamedDecl *)M->first << Record;
17800                 Diag(M->first->getLocation(),
17801                      diag::note_overridden_virtual_function);
17802                 for (OverridingMethods::overriding_iterator
17803                           OM = SO->second.begin(),
17804                        OMEnd = SO->second.end();
17805                      OM != OMEnd; ++OM)
17806                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17807                     << (const NamedDecl *)M->first << OM->Method->getParent();
17808 
17809                 Record->setInvalidDecl();
17810               }
17811             }
17812             CXXRecord->completeDefinition(&FinalOverriders);
17813             Completed = true;
17814           }
17815         }
17816       }
17817     }
17818 
17819     if (!Completed)
17820       Record->completeDefinition();
17821 
17822     // Handle attributes before checking the layout.
17823     ProcessDeclAttributeList(S, Record, Attrs);
17824 
17825     // We may have deferred checking for a deleted destructor. Check now.
17826     if (CXXRecord) {
17827       auto *Dtor = CXXRecord->getDestructor();
17828       if (Dtor && Dtor->isImplicit() &&
17829           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17830         CXXRecord->setImplicitDestructorIsDeleted();
17831         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17832       }
17833     }
17834 
17835     if (Record->hasAttrs()) {
17836       CheckAlignasUnderalignment(Record);
17837 
17838       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17839         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17840                                            IA->getRange(), IA->getBestCase(),
17841                                            IA->getInheritanceModel());
17842     }
17843 
17844     // Check if the structure/union declaration is a type that can have zero
17845     // size in C. For C this is a language extension, for C++ it may cause
17846     // compatibility problems.
17847     bool CheckForZeroSize;
17848     if (!getLangOpts().CPlusPlus) {
17849       CheckForZeroSize = true;
17850     } else {
17851       // For C++ filter out types that cannot be referenced in C code.
17852       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17853       CheckForZeroSize =
17854           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17855           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17856           CXXRecord->isCLike();
17857     }
17858     if (CheckForZeroSize) {
17859       bool ZeroSize = true;
17860       bool IsEmpty = true;
17861       unsigned NonBitFields = 0;
17862       for (RecordDecl::field_iterator I = Record->field_begin(),
17863                                       E = Record->field_end();
17864            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17865         IsEmpty = false;
17866         if (I->isUnnamedBitfield()) {
17867           if (!I->isZeroLengthBitField(Context))
17868             ZeroSize = false;
17869         } else {
17870           ++NonBitFields;
17871           QualType FieldType = I->getType();
17872           if (FieldType->isIncompleteType() ||
17873               !Context.getTypeSizeInChars(FieldType).isZero())
17874             ZeroSize = false;
17875         }
17876       }
17877 
17878       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17879       // allowed in C++, but warn if its declaration is inside
17880       // extern "C" block.
17881       if (ZeroSize) {
17882         Diag(RecLoc, getLangOpts().CPlusPlus ?
17883                          diag::warn_zero_size_struct_union_in_extern_c :
17884                          diag::warn_zero_size_struct_union_compat)
17885           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17886       }
17887 
17888       // Structs without named members are extension in C (C99 6.7.2.1p7),
17889       // but are accepted by GCC.
17890       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17891         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17892                                diag::ext_no_named_members_in_struct_union)
17893           << Record->isUnion();
17894       }
17895     }
17896   } else {
17897     ObjCIvarDecl **ClsFields =
17898       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17899     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17900       ID->setEndOfDefinitionLoc(RBrac);
17901       // Add ivar's to class's DeclContext.
17902       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17903         ClsFields[i]->setLexicalDeclContext(ID);
17904         ID->addDecl(ClsFields[i]);
17905       }
17906       // Must enforce the rule that ivars in the base classes may not be
17907       // duplicates.
17908       if (ID->getSuperClass())
17909         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17910     } else if (ObjCImplementationDecl *IMPDecl =
17911                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17912       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17913       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17914         // Ivar declared in @implementation never belongs to the implementation.
17915         // Only it is in implementation's lexical context.
17916         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17917       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17918       IMPDecl->setIvarLBraceLoc(LBrac);
17919       IMPDecl->setIvarRBraceLoc(RBrac);
17920     } else if (ObjCCategoryDecl *CDecl =
17921                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17922       // case of ivars in class extension; all other cases have been
17923       // reported as errors elsewhere.
17924       // FIXME. Class extension does not have a LocEnd field.
17925       // CDecl->setLocEnd(RBrac);
17926       // Add ivar's to class extension's DeclContext.
17927       // Diagnose redeclaration of private ivars.
17928       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17929       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17930         if (IDecl) {
17931           if (const ObjCIvarDecl *ClsIvar =
17932               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17933             Diag(ClsFields[i]->getLocation(),
17934                  diag::err_duplicate_ivar_declaration);
17935             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17936             continue;
17937           }
17938           for (const auto *Ext : IDecl->known_extensions()) {
17939             if (const ObjCIvarDecl *ClsExtIvar
17940                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17941               Diag(ClsFields[i]->getLocation(),
17942                    diag::err_duplicate_ivar_declaration);
17943               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17944               continue;
17945             }
17946           }
17947         }
17948         ClsFields[i]->setLexicalDeclContext(CDecl);
17949         CDecl->addDecl(ClsFields[i]);
17950       }
17951       CDecl->setIvarLBraceLoc(LBrac);
17952       CDecl->setIvarRBraceLoc(RBrac);
17953     }
17954   }
17955 }
17956 
17957 /// Determine whether the given integral value is representable within
17958 /// the given type T.
17959 static bool isRepresentableIntegerValue(ASTContext &Context,
17960                                         llvm::APSInt &Value,
17961                                         QualType T) {
17962   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17963          "Integral type required!");
17964   unsigned BitWidth = Context.getIntWidth(T);
17965 
17966   if (Value.isUnsigned() || Value.isNonNegative()) {
17967     if (T->isSignedIntegerOrEnumerationType())
17968       --BitWidth;
17969     return Value.getActiveBits() <= BitWidth;
17970   }
17971   return Value.getMinSignedBits() <= BitWidth;
17972 }
17973 
17974 // Given an integral type, return the next larger integral type
17975 // (or a NULL type of no such type exists).
17976 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17977   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17978   // enum checking below.
17979   assert((T->isIntegralType(Context) ||
17980          T->isEnumeralType()) && "Integral type required!");
17981   const unsigned NumTypes = 4;
17982   QualType SignedIntegralTypes[NumTypes] = {
17983     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17984   };
17985   QualType UnsignedIntegralTypes[NumTypes] = {
17986     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17987     Context.UnsignedLongLongTy
17988   };
17989 
17990   unsigned BitWidth = Context.getTypeSize(T);
17991   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17992                                                         : UnsignedIntegralTypes;
17993   for (unsigned I = 0; I != NumTypes; ++I)
17994     if (Context.getTypeSize(Types[I]) > BitWidth)
17995       return Types[I];
17996 
17997   return QualType();
17998 }
17999 
18000 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18001                                           EnumConstantDecl *LastEnumConst,
18002                                           SourceLocation IdLoc,
18003                                           IdentifierInfo *Id,
18004                                           Expr *Val) {
18005   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18006   llvm::APSInt EnumVal(IntWidth);
18007   QualType EltTy;
18008 
18009   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18010     Val = nullptr;
18011 
18012   if (Val)
18013     Val = DefaultLvalueConversion(Val).get();
18014 
18015   if (Val) {
18016     if (Enum->isDependentType() || Val->isTypeDependent() ||
18017         Val->containsErrors())
18018       EltTy = Context.DependentTy;
18019     else {
18020       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18021       // underlying type, but do allow it in all other contexts.
18022       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18023         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18024         // constant-expression in the enumerator-definition shall be a converted
18025         // constant expression of the underlying type.
18026         EltTy = Enum->getIntegerType();
18027         ExprResult Converted =
18028           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18029                                            CCEK_Enumerator);
18030         if (Converted.isInvalid())
18031           Val = nullptr;
18032         else
18033           Val = Converted.get();
18034       } else if (!Val->isValueDependent() &&
18035                  !(Val =
18036                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18037                            .get())) {
18038         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18039       } else {
18040         if (Enum->isComplete()) {
18041           EltTy = Enum->getIntegerType();
18042 
18043           // In Obj-C and Microsoft mode, require the enumeration value to be
18044           // representable in the underlying type of the enumeration. In C++11,
18045           // we perform a non-narrowing conversion as part of converted constant
18046           // expression checking.
18047           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18048             if (Context.getTargetInfo()
18049                     .getTriple()
18050                     .isWindowsMSVCEnvironment()) {
18051               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18052             } else {
18053               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18054             }
18055           }
18056 
18057           // Cast to the underlying type.
18058           Val = ImpCastExprToType(Val, EltTy,
18059                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18060                                                          : CK_IntegralCast)
18061                     .get();
18062         } else if (getLangOpts().CPlusPlus) {
18063           // C++11 [dcl.enum]p5:
18064           //   If the underlying type is not fixed, the type of each enumerator
18065           //   is the type of its initializing value:
18066           //     - If an initializer is specified for an enumerator, the
18067           //       initializing value has the same type as the expression.
18068           EltTy = Val->getType();
18069         } else {
18070           // C99 6.7.2.2p2:
18071           //   The expression that defines the value of an enumeration constant
18072           //   shall be an integer constant expression that has a value
18073           //   representable as an int.
18074 
18075           // Complain if the value is not representable in an int.
18076           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18077             Diag(IdLoc, diag::ext_enum_value_not_int)
18078               << toString(EnumVal, 10) << Val->getSourceRange()
18079               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18080           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18081             // Force the type of the expression to 'int'.
18082             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18083           }
18084           EltTy = Val->getType();
18085         }
18086       }
18087     }
18088   }
18089 
18090   if (!Val) {
18091     if (Enum->isDependentType())
18092       EltTy = Context.DependentTy;
18093     else if (!LastEnumConst) {
18094       // C++0x [dcl.enum]p5:
18095       //   If the underlying type is not fixed, the type of each enumerator
18096       //   is the type of its initializing value:
18097       //     - If no initializer is specified for the first enumerator, the
18098       //       initializing value has an unspecified integral type.
18099       //
18100       // GCC uses 'int' for its unspecified integral type, as does
18101       // C99 6.7.2.2p3.
18102       if (Enum->isFixed()) {
18103         EltTy = Enum->getIntegerType();
18104       }
18105       else {
18106         EltTy = Context.IntTy;
18107       }
18108     } else {
18109       // Assign the last value + 1.
18110       EnumVal = LastEnumConst->getInitVal();
18111       ++EnumVal;
18112       EltTy = LastEnumConst->getType();
18113 
18114       // Check for overflow on increment.
18115       if (EnumVal < LastEnumConst->getInitVal()) {
18116         // C++0x [dcl.enum]p5:
18117         //   If the underlying type is not fixed, the type of each enumerator
18118         //   is the type of its initializing value:
18119         //
18120         //     - Otherwise the type of the initializing value is the same as
18121         //       the type of the initializing value of the preceding enumerator
18122         //       unless the incremented value is not representable in that type,
18123         //       in which case the type is an unspecified integral type
18124         //       sufficient to contain the incremented value. If no such type
18125         //       exists, the program is ill-formed.
18126         QualType T = getNextLargerIntegralType(Context, EltTy);
18127         if (T.isNull() || Enum->isFixed()) {
18128           // There is no integral type larger enough to represent this
18129           // value. Complain, then allow the value to wrap around.
18130           EnumVal = LastEnumConst->getInitVal();
18131           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18132           ++EnumVal;
18133           if (Enum->isFixed())
18134             // When the underlying type is fixed, this is ill-formed.
18135             Diag(IdLoc, diag::err_enumerator_wrapped)
18136               << toString(EnumVal, 10)
18137               << EltTy;
18138           else
18139             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18140               << toString(EnumVal, 10);
18141         } else {
18142           EltTy = T;
18143         }
18144 
18145         // Retrieve the last enumerator's value, extent that type to the
18146         // type that is supposed to be large enough to represent the incremented
18147         // value, then increment.
18148         EnumVal = LastEnumConst->getInitVal();
18149         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18150         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18151         ++EnumVal;
18152 
18153         // If we're not in C++, diagnose the overflow of enumerator values,
18154         // which in C99 means that the enumerator value is not representable in
18155         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18156         // permits enumerator values that are representable in some larger
18157         // integral type.
18158         if (!getLangOpts().CPlusPlus && !T.isNull())
18159           Diag(IdLoc, diag::warn_enum_value_overflow);
18160       } else if (!getLangOpts().CPlusPlus &&
18161                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18162         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18163         Diag(IdLoc, diag::ext_enum_value_not_int)
18164           << toString(EnumVal, 10) << 1;
18165       }
18166     }
18167   }
18168 
18169   if (!EltTy->isDependentType()) {
18170     // Make the enumerator value match the signedness and size of the
18171     // enumerator's type.
18172     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18173     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18174   }
18175 
18176   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18177                                   Val, EnumVal);
18178 }
18179 
18180 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18181                                                 SourceLocation IILoc) {
18182   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18183       !getLangOpts().CPlusPlus)
18184     return SkipBodyInfo();
18185 
18186   // We have an anonymous enum definition. Look up the first enumerator to
18187   // determine if we should merge the definition with an existing one and
18188   // skip the body.
18189   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18190                                          forRedeclarationInCurContext());
18191   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18192   if (!PrevECD)
18193     return SkipBodyInfo();
18194 
18195   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18196   NamedDecl *Hidden;
18197   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18198     SkipBodyInfo Skip;
18199     Skip.Previous = Hidden;
18200     return Skip;
18201   }
18202 
18203   return SkipBodyInfo();
18204 }
18205 
18206 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18207                               SourceLocation IdLoc, IdentifierInfo *Id,
18208                               const ParsedAttributesView &Attrs,
18209                               SourceLocation EqualLoc, Expr *Val) {
18210   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18211   EnumConstantDecl *LastEnumConst =
18212     cast_or_null<EnumConstantDecl>(lastEnumConst);
18213 
18214   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18215   // we find one that is.
18216   S = getNonFieldDeclScope(S);
18217 
18218   // Verify that there isn't already something declared with this name in this
18219   // scope.
18220   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18221   LookupName(R, S);
18222   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18223 
18224   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18225     // Maybe we will complain about the shadowed template parameter.
18226     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18227     // Just pretend that we didn't see the previous declaration.
18228     PrevDecl = nullptr;
18229   }
18230 
18231   // C++ [class.mem]p15:
18232   // If T is the name of a class, then each of the following shall have a name
18233   // different from T:
18234   // - every enumerator of every member of class T that is an unscoped
18235   // enumerated type
18236   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18237     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18238                             DeclarationNameInfo(Id, IdLoc));
18239 
18240   EnumConstantDecl *New =
18241     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18242   if (!New)
18243     return nullptr;
18244 
18245   if (PrevDecl) {
18246     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18247       // Check for other kinds of shadowing not already handled.
18248       CheckShadow(New, PrevDecl, R);
18249     }
18250 
18251     // When in C++, we may get a TagDecl with the same name; in this case the
18252     // enum constant will 'hide' the tag.
18253     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18254            "Received TagDecl when not in C++!");
18255     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18256       if (isa<EnumConstantDecl>(PrevDecl))
18257         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18258       else
18259         Diag(IdLoc, diag::err_redefinition) << Id;
18260       notePreviousDefinition(PrevDecl, IdLoc);
18261       return nullptr;
18262     }
18263   }
18264 
18265   // Process attributes.
18266   ProcessDeclAttributeList(S, New, Attrs);
18267   AddPragmaAttributes(S, New);
18268 
18269   // Register this decl in the current scope stack.
18270   New->setAccess(TheEnumDecl->getAccess());
18271   PushOnScopeChains(New, S);
18272 
18273   ActOnDocumentableDecl(New);
18274 
18275   return New;
18276 }
18277 
18278 // Returns true when the enum initial expression does not trigger the
18279 // duplicate enum warning.  A few common cases are exempted as follows:
18280 // Element2 = Element1
18281 // Element2 = Element1 + 1
18282 // Element2 = Element1 - 1
18283 // Where Element2 and Element1 are from the same enum.
18284 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18285   Expr *InitExpr = ECD->getInitExpr();
18286   if (!InitExpr)
18287     return true;
18288   InitExpr = InitExpr->IgnoreImpCasts();
18289 
18290   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18291     if (!BO->isAdditiveOp())
18292       return true;
18293     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18294     if (!IL)
18295       return true;
18296     if (IL->getValue() != 1)
18297       return true;
18298 
18299     InitExpr = BO->getLHS();
18300   }
18301 
18302   // This checks if the elements are from the same enum.
18303   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18304   if (!DRE)
18305     return true;
18306 
18307   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18308   if (!EnumConstant)
18309     return true;
18310 
18311   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18312       Enum)
18313     return true;
18314 
18315   return false;
18316 }
18317 
18318 // Emits a warning when an element is implicitly set a value that
18319 // a previous element has already been set to.
18320 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18321                                         EnumDecl *Enum, QualType EnumType) {
18322   // Avoid anonymous enums
18323   if (!Enum->getIdentifier())
18324     return;
18325 
18326   // Only check for small enums.
18327   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18328     return;
18329 
18330   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18331     return;
18332 
18333   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18334   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18335 
18336   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18337 
18338   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18339   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18340 
18341   // Use int64_t as a key to avoid needing special handling for map keys.
18342   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18343     llvm::APSInt Val = D->getInitVal();
18344     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18345   };
18346 
18347   DuplicatesVector DupVector;
18348   ValueToVectorMap EnumMap;
18349 
18350   // Populate the EnumMap with all values represented by enum constants without
18351   // an initializer.
18352   for (auto *Element : Elements) {
18353     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18354 
18355     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18356     // this constant.  Skip this enum since it may be ill-formed.
18357     if (!ECD) {
18358       return;
18359     }
18360 
18361     // Constants with initalizers are handled in the next loop.
18362     if (ECD->getInitExpr())
18363       continue;
18364 
18365     // Duplicate values are handled in the next loop.
18366     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18367   }
18368 
18369   if (EnumMap.size() == 0)
18370     return;
18371 
18372   // Create vectors for any values that has duplicates.
18373   for (auto *Element : Elements) {
18374     // The last loop returned if any constant was null.
18375     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18376     if (!ValidDuplicateEnum(ECD, Enum))
18377       continue;
18378 
18379     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18380     if (Iter == EnumMap.end())
18381       continue;
18382 
18383     DeclOrVector& Entry = Iter->second;
18384     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18385       // Ensure constants are different.
18386       if (D == ECD)
18387         continue;
18388 
18389       // Create new vector and push values onto it.
18390       auto Vec = std::make_unique<ECDVector>();
18391       Vec->push_back(D);
18392       Vec->push_back(ECD);
18393 
18394       // Update entry to point to the duplicates vector.
18395       Entry = Vec.get();
18396 
18397       // Store the vector somewhere we can consult later for quick emission of
18398       // diagnostics.
18399       DupVector.emplace_back(std::move(Vec));
18400       continue;
18401     }
18402 
18403     ECDVector *Vec = Entry.get<ECDVector*>();
18404     // Make sure constants are not added more than once.
18405     if (*Vec->begin() == ECD)
18406       continue;
18407 
18408     Vec->push_back(ECD);
18409   }
18410 
18411   // Emit diagnostics.
18412   for (const auto &Vec : DupVector) {
18413     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18414 
18415     // Emit warning for one enum constant.
18416     auto *FirstECD = Vec->front();
18417     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18418       << FirstECD << toString(FirstECD->getInitVal(), 10)
18419       << FirstECD->getSourceRange();
18420 
18421     // Emit one note for each of the remaining enum constants with
18422     // the same value.
18423     for (auto *ECD : llvm::drop_begin(*Vec))
18424       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18425         << ECD << toString(ECD->getInitVal(), 10)
18426         << ECD->getSourceRange();
18427   }
18428 }
18429 
18430 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18431                              bool AllowMask) const {
18432   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18433   assert(ED->isCompleteDefinition() && "expected enum definition");
18434 
18435   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18436   llvm::APInt &FlagBits = R.first->second;
18437 
18438   if (R.second) {
18439     for (auto *E : ED->enumerators()) {
18440       const auto &EVal = E->getInitVal();
18441       // Only single-bit enumerators introduce new flag values.
18442       if (EVal.isPowerOf2())
18443         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18444     }
18445   }
18446 
18447   // A value is in a flag enum if either its bits are a subset of the enum's
18448   // flag bits (the first condition) or we are allowing masks and the same is
18449   // true of its complement (the second condition). When masks are allowed, we
18450   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18451   //
18452   // While it's true that any value could be used as a mask, the assumption is
18453   // that a mask will have all of the insignificant bits set. Anything else is
18454   // likely a logic error.
18455   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18456   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18457 }
18458 
18459 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18460                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18461                          const ParsedAttributesView &Attrs) {
18462   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18463   QualType EnumType = Context.getTypeDeclType(Enum);
18464 
18465   ProcessDeclAttributeList(S, Enum, Attrs);
18466 
18467   if (Enum->isDependentType()) {
18468     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18469       EnumConstantDecl *ECD =
18470         cast_or_null<EnumConstantDecl>(Elements[i]);
18471       if (!ECD) continue;
18472 
18473       ECD->setType(EnumType);
18474     }
18475 
18476     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18477     return;
18478   }
18479 
18480   // TODO: If the result value doesn't fit in an int, it must be a long or long
18481   // long value.  ISO C does not support this, but GCC does as an extension,
18482   // emit a warning.
18483   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18484   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18485   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18486 
18487   // Verify that all the values are okay, compute the size of the values, and
18488   // reverse the list.
18489   unsigned NumNegativeBits = 0;
18490   unsigned NumPositiveBits = 0;
18491 
18492   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18493     EnumConstantDecl *ECD =
18494       cast_or_null<EnumConstantDecl>(Elements[i]);
18495     if (!ECD) continue;  // Already issued a diagnostic.
18496 
18497     const llvm::APSInt &InitVal = ECD->getInitVal();
18498 
18499     // Keep track of the size of positive and negative values.
18500     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18501       NumPositiveBits = std::max(NumPositiveBits,
18502                                  (unsigned)InitVal.getActiveBits());
18503     else
18504       NumNegativeBits = std::max(NumNegativeBits,
18505                                  (unsigned)InitVal.getMinSignedBits());
18506   }
18507 
18508   // Figure out the type that should be used for this enum.
18509   QualType BestType;
18510   unsigned BestWidth;
18511 
18512   // C++0x N3000 [conv.prom]p3:
18513   //   An rvalue of an unscoped enumeration type whose underlying
18514   //   type is not fixed can be converted to an rvalue of the first
18515   //   of the following types that can represent all the values of
18516   //   the enumeration: int, unsigned int, long int, unsigned long
18517   //   int, long long int, or unsigned long long int.
18518   // C99 6.4.4.3p2:
18519   //   An identifier declared as an enumeration constant has type int.
18520   // The C99 rule is modified by a gcc extension
18521   QualType BestPromotionType;
18522 
18523   bool Packed = Enum->hasAttr<PackedAttr>();
18524   // -fshort-enums is the equivalent to specifying the packed attribute on all
18525   // enum definitions.
18526   if (LangOpts.ShortEnums)
18527     Packed = true;
18528 
18529   // If the enum already has a type because it is fixed or dictated by the
18530   // target, promote that type instead of analyzing the enumerators.
18531   if (Enum->isComplete()) {
18532     BestType = Enum->getIntegerType();
18533     if (BestType->isPromotableIntegerType())
18534       BestPromotionType = Context.getPromotedIntegerType(BestType);
18535     else
18536       BestPromotionType = BestType;
18537 
18538     BestWidth = Context.getIntWidth(BestType);
18539   }
18540   else if (NumNegativeBits) {
18541     // If there is a negative value, figure out the smallest integer type (of
18542     // int/long/longlong) that fits.
18543     // If it's packed, check also if it fits a char or a short.
18544     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18545       BestType = Context.SignedCharTy;
18546       BestWidth = CharWidth;
18547     } else if (Packed && NumNegativeBits <= ShortWidth &&
18548                NumPositiveBits < ShortWidth) {
18549       BestType = Context.ShortTy;
18550       BestWidth = ShortWidth;
18551     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18552       BestType = Context.IntTy;
18553       BestWidth = IntWidth;
18554     } else {
18555       BestWidth = Context.getTargetInfo().getLongWidth();
18556 
18557       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18558         BestType = Context.LongTy;
18559       } else {
18560         BestWidth = Context.getTargetInfo().getLongLongWidth();
18561 
18562         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18563           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18564         BestType = Context.LongLongTy;
18565       }
18566     }
18567     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18568   } else {
18569     // If there is no negative value, figure out the smallest type that fits
18570     // all of the enumerator values.
18571     // If it's packed, check also if it fits a char or a short.
18572     if (Packed && NumPositiveBits <= CharWidth) {
18573       BestType = Context.UnsignedCharTy;
18574       BestPromotionType = Context.IntTy;
18575       BestWidth = CharWidth;
18576     } else if (Packed && NumPositiveBits <= ShortWidth) {
18577       BestType = Context.UnsignedShortTy;
18578       BestPromotionType = Context.IntTy;
18579       BestWidth = ShortWidth;
18580     } else if (NumPositiveBits <= IntWidth) {
18581       BestType = Context.UnsignedIntTy;
18582       BestWidth = IntWidth;
18583       BestPromotionType
18584         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18585                            ? Context.UnsignedIntTy : Context.IntTy;
18586     } else if (NumPositiveBits <=
18587                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18588       BestType = Context.UnsignedLongTy;
18589       BestPromotionType
18590         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18591                            ? Context.UnsignedLongTy : Context.LongTy;
18592     } else {
18593       BestWidth = Context.getTargetInfo().getLongLongWidth();
18594       assert(NumPositiveBits <= BestWidth &&
18595              "How could an initializer get larger than ULL?");
18596       BestType = Context.UnsignedLongLongTy;
18597       BestPromotionType
18598         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18599                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18600     }
18601   }
18602 
18603   // Loop over all of the enumerator constants, changing their types to match
18604   // the type of the enum if needed.
18605   for (auto *D : Elements) {
18606     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18607     if (!ECD) continue;  // Already issued a diagnostic.
18608 
18609     // Standard C says the enumerators have int type, but we allow, as an
18610     // extension, the enumerators to be larger than int size.  If each
18611     // enumerator value fits in an int, type it as an int, otherwise type it the
18612     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18613     // that X has type 'int', not 'unsigned'.
18614 
18615     // Determine whether the value fits into an int.
18616     llvm::APSInt InitVal = ECD->getInitVal();
18617 
18618     // If it fits into an integer type, force it.  Otherwise force it to match
18619     // the enum decl type.
18620     QualType NewTy;
18621     unsigned NewWidth;
18622     bool NewSign;
18623     if (!getLangOpts().CPlusPlus &&
18624         !Enum->isFixed() &&
18625         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18626       NewTy = Context.IntTy;
18627       NewWidth = IntWidth;
18628       NewSign = true;
18629     } else if (ECD->getType() == BestType) {
18630       // Already the right type!
18631       if (getLangOpts().CPlusPlus)
18632         // C++ [dcl.enum]p4: Following the closing brace of an
18633         // enum-specifier, each enumerator has the type of its
18634         // enumeration.
18635         ECD->setType(EnumType);
18636       continue;
18637     } else {
18638       NewTy = BestType;
18639       NewWidth = BestWidth;
18640       NewSign = BestType->isSignedIntegerOrEnumerationType();
18641     }
18642 
18643     // Adjust the APSInt value.
18644     InitVal = InitVal.extOrTrunc(NewWidth);
18645     InitVal.setIsSigned(NewSign);
18646     ECD->setInitVal(InitVal);
18647 
18648     // Adjust the Expr initializer and type.
18649     if (ECD->getInitExpr() &&
18650         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18651       ECD->setInitExpr(ImplicitCastExpr::Create(
18652           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18653           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18654     if (getLangOpts().CPlusPlus)
18655       // C++ [dcl.enum]p4: Following the closing brace of an
18656       // enum-specifier, each enumerator has the type of its
18657       // enumeration.
18658       ECD->setType(EnumType);
18659     else
18660       ECD->setType(NewTy);
18661   }
18662 
18663   Enum->completeDefinition(BestType, BestPromotionType,
18664                            NumPositiveBits, NumNegativeBits);
18665 
18666   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18667 
18668   if (Enum->isClosedFlag()) {
18669     for (Decl *D : Elements) {
18670       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18671       if (!ECD) continue;  // Already issued a diagnostic.
18672 
18673       llvm::APSInt InitVal = ECD->getInitVal();
18674       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18675           !IsValueInFlagEnum(Enum, InitVal, true))
18676         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18677           << ECD << Enum;
18678     }
18679   }
18680 
18681   // Now that the enum type is defined, ensure it's not been underaligned.
18682   if (Enum->hasAttrs())
18683     CheckAlignasUnderalignment(Enum);
18684 }
18685 
18686 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18687                                   SourceLocation StartLoc,
18688                                   SourceLocation EndLoc) {
18689   StringLiteral *AsmString = cast<StringLiteral>(expr);
18690 
18691   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18692                                                    AsmString, StartLoc,
18693                                                    EndLoc);
18694   CurContext->addDecl(New);
18695   return New;
18696 }
18697 
18698 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18699                                       IdentifierInfo* AliasName,
18700                                       SourceLocation PragmaLoc,
18701                                       SourceLocation NameLoc,
18702                                       SourceLocation AliasNameLoc) {
18703   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18704                                          LookupOrdinaryName);
18705   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18706                            AttributeCommonInfo::AS_Pragma);
18707   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18708       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18709 
18710   // If a declaration that:
18711   // 1) declares a function or a variable
18712   // 2) has external linkage
18713   // already exists, add a label attribute to it.
18714   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18715     if (isDeclExternC(PrevDecl))
18716       PrevDecl->addAttr(Attr);
18717     else
18718       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18719           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18720   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18721   } else
18722     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18723 }
18724 
18725 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18726                              SourceLocation PragmaLoc,
18727                              SourceLocation NameLoc) {
18728   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18729 
18730   if (PrevDecl) {
18731     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18732   } else {
18733     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
18734   }
18735 }
18736 
18737 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18738                                 IdentifierInfo* AliasName,
18739                                 SourceLocation PragmaLoc,
18740                                 SourceLocation NameLoc,
18741                                 SourceLocation AliasNameLoc) {
18742   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18743                                     LookupOrdinaryName);
18744   WeakInfo W = WeakInfo(Name, NameLoc);
18745 
18746   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18747     if (!PrevDecl->hasAttr<AliasAttr>())
18748       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18749         DeclApplyPragmaWeak(TUScope, ND, W);
18750   } else {
18751     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
18752   }
18753 }
18754 
18755 Decl *Sema::getObjCDeclContext() const {
18756   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18757 }
18758 
18759 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18760                                                      bool Final) {
18761   assert(FD && "Expected non-null FunctionDecl");
18762 
18763   // SYCL functions can be template, so we check if they have appropriate
18764   // attribute prior to checking if it is a template.
18765   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18766     return FunctionEmissionStatus::Emitted;
18767 
18768   // Templates are emitted when they're instantiated.
18769   if (FD->isDependentContext())
18770     return FunctionEmissionStatus::TemplateDiscarded;
18771 
18772   // Check whether this function is an externally visible definition.
18773   auto IsEmittedForExternalSymbol = [this, FD]() {
18774     // We have to check the GVA linkage of the function's *definition* -- if we
18775     // only have a declaration, we don't know whether or not the function will
18776     // be emitted, because (say) the definition could include "inline".
18777     FunctionDecl *Def = FD->getDefinition();
18778 
18779     return Def && !isDiscardableGVALinkage(
18780                       getASTContext().GetGVALinkageForFunction(Def));
18781   };
18782 
18783   if (LangOpts.OpenMPIsDevice) {
18784     // In OpenMP device mode we will not emit host only functions, or functions
18785     // we don't need due to their linkage.
18786     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18787         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18788     // DevTy may be changed later by
18789     //  #pragma omp declare target to(*) device_type(*).
18790     // Therefore DevTy having no value does not imply host. The emission status
18791     // will be checked again at the end of compilation unit with Final = true.
18792     if (DevTy.hasValue())
18793       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18794         return FunctionEmissionStatus::OMPDiscarded;
18795     // If we have an explicit value for the device type, or we are in a target
18796     // declare context, we need to emit all extern and used symbols.
18797     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18798       if (IsEmittedForExternalSymbol())
18799         return FunctionEmissionStatus::Emitted;
18800     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18801     // we'll omit it.
18802     if (Final)
18803       return FunctionEmissionStatus::OMPDiscarded;
18804   } else if (LangOpts.OpenMP > 45) {
18805     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18806     // function. In 5.0, no_host was introduced which might cause a function to
18807     // be ommitted.
18808     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18809         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18810     if (DevTy.hasValue())
18811       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18812         return FunctionEmissionStatus::OMPDiscarded;
18813   }
18814 
18815   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18816     return FunctionEmissionStatus::Emitted;
18817 
18818   if (LangOpts.CUDA) {
18819     // When compiling for device, host functions are never emitted.  Similarly,
18820     // when compiling for host, device and global functions are never emitted.
18821     // (Technically, we do emit a host-side stub for global functions, but this
18822     // doesn't count for our purposes here.)
18823     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18824     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18825       return FunctionEmissionStatus::CUDADiscarded;
18826     if (!LangOpts.CUDAIsDevice &&
18827         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18828       return FunctionEmissionStatus::CUDADiscarded;
18829 
18830     if (IsEmittedForExternalSymbol())
18831       return FunctionEmissionStatus::Emitted;
18832   }
18833 
18834   // Otherwise, the function is known-emitted if it's in our set of
18835   // known-emitted functions.
18836   return FunctionEmissionStatus::Unknown;
18837 }
18838 
18839 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18840   // Host-side references to a __global__ function refer to the stub, so the
18841   // function itself is never emitted and therefore should not be marked.
18842   // If we have host fn calls kernel fn calls host+device, the HD function
18843   // does not get instantiated on the host. We model this by omitting at the
18844   // call to the kernel from the callgraph. This ensures that, when compiling
18845   // for host, only HD functions actually called from the host get marked as
18846   // known-emitted.
18847   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18848          IdentifyCUDATarget(Callee) == CFT_Global;
18849 }
18850