1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw___ibm128:
145   case tok::kw_wchar_t:
146   case tok::kw_bool:
147   case tok::kw___underlying_type:
148   case tok::kw___auto_type:
149     return true;
150 
151   case tok::annot_typename:
152   case tok::kw_char16_t:
153   case tok::kw_char32_t:
154   case tok::kw_typeof:
155   case tok::annot_decltype:
156   case tok::kw_decltype:
157     return getLangOpts().CPlusPlus;
158 
159   case tok::kw_char8_t:
160     return getLangOpts().Char8;
161 
162   default:
163     break;
164   }
165 
166   return false;
167 }
168 
169 namespace {
170 enum class UnqualifiedTypeNameLookupResult {
171   NotFound,
172   FoundNonType,
173   FoundType
174 };
175 } // end anonymous namespace
176 
177 /// Tries to perform unqualified lookup of the type decls in bases for
178 /// dependent class.
179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180 /// type decl, \a FoundType if only type decls are found.
181 static UnqualifiedTypeNameLookupResult
182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
183                                 SourceLocation NameLoc,
184                                 const CXXRecordDecl *RD) {
185   if (!RD->hasDefinition())
186     return UnqualifiedTypeNameLookupResult::NotFound;
187   // Look for type decls in base classes.
188   UnqualifiedTypeNameLookupResult FoundTypeDecl =
189       UnqualifiedTypeNameLookupResult::NotFound;
190   for (const auto &Base : RD->bases()) {
191     const CXXRecordDecl *BaseRD = nullptr;
192     if (auto *BaseTT = Base.getType()->getAs<TagType>())
193       BaseRD = BaseTT->getAsCXXRecordDecl();
194     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195       // Look for type decls in dependent base classes that have known primary
196       // templates.
197       if (!TST || !TST->isDependentType())
198         continue;
199       auto *TD = TST->getTemplateName().getAsTemplateDecl();
200       if (!TD)
201         continue;
202       if (auto *BasePrimaryTemplate =
203           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205           BaseRD = BasePrimaryTemplate;
206         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207           if (const ClassTemplatePartialSpecializationDecl *PS =
208                   CTD->findPartialSpecialization(Base.getType()))
209             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210               BaseRD = PS;
211         }
212       }
213     }
214     if (BaseRD) {
215       for (NamedDecl *ND : BaseRD->lookup(&II)) {
216         if (!isa<TypeDecl>(ND))
217           return UnqualifiedTypeNameLookupResult::FoundNonType;
218         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219       }
220       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222         case UnqualifiedTypeNameLookupResult::FoundNonType:
223           return UnqualifiedTypeNameLookupResult::FoundNonType;
224         case UnqualifiedTypeNameLookupResult::FoundType:
225           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226           break;
227         case UnqualifiedTypeNameLookupResult::NotFound:
228           break;
229         }
230       }
231     }
232   }
233 
234   return FoundTypeDecl;
235 }
236 
237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
238                                                       const IdentifierInfo &II,
239                                                       SourceLocation NameLoc) {
240   // Lookup in the parent class template context, if any.
241   const CXXRecordDecl *RD = nullptr;
242   UnqualifiedTypeNameLookupResult FoundTypeDecl =
243       UnqualifiedTypeNameLookupResult::NotFound;
244   for (DeclContext *DC = S.CurContext;
245        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246        DC = DC->getParent()) {
247     // Look for type decls in dependent base classes that have known primary
248     // templates.
249     RD = dyn_cast<CXXRecordDecl>(DC);
250     if (RD && RD->getDescribedClassTemplate())
251       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252   }
253   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254     return nullptr;
255 
256   // We found some types in dependent base classes.  Recover as if the user
257   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
258   // lookup during template instantiation.
259   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
260 
261   ASTContext &Context = S.Context;
262   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263                                           cast<Type>(Context.getRecordType(RD)));
264   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265 
266   CXXScopeSpec SS;
267   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268 
269   TypeLocBuilder Builder;
270   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271   DepTL.setNameLoc(NameLoc);
272   DepTL.setElaboratedKeywordLoc(SourceLocation());
273   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275 }
276 
277 /// If the identifier refers to a type name within this scope,
278 /// return the declaration of that type.
279 ///
280 /// This routine performs ordinary name lookup of the identifier II
281 /// within the given scope, with optional C++ scope specifier SS, to
282 /// determine whether the name refers to a type. If so, returns an
283 /// opaque pointer (actually a QualType) corresponding to that
284 /// type. Otherwise, returns NULL.
285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
286                              Scope *S, CXXScopeSpec *SS,
287                              bool isClassName, bool HasTrailingDot,
288                              ParsedType ObjectTypePtr,
289                              bool IsCtorOrDtorName,
290                              bool WantNontrivialTypeSourceInfo,
291                              bool IsClassTemplateDeductionContext,
292                              IdentifierInfo **CorrectedII) {
293   // FIXME: Consider allowing this outside C++1z mode as an extension.
294   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296                               !isClassName && !HasTrailingDot;
297 
298   // Determine where we will perform name lookup.
299   DeclContext *LookupCtx = nullptr;
300   if (ObjectTypePtr) {
301     QualType ObjectType = ObjectTypePtr.get();
302     if (ObjectType->isRecordType())
303       LookupCtx = computeDeclContext(ObjectType);
304   } else if (SS && SS->isNotEmpty()) {
305     LookupCtx = computeDeclContext(*SS, false);
306 
307     if (!LookupCtx) {
308       if (isDependentScopeSpecifier(*SS)) {
309         // C++ [temp.res]p3:
310         //   A qualified-id that refers to a type and in which the
311         //   nested-name-specifier depends on a template-parameter (14.6.2)
312         //   shall be prefixed by the keyword typename to indicate that the
313         //   qualified-id denotes a type, forming an
314         //   elaborated-type-specifier (7.1.5.3).
315         //
316         // We therefore do not perform any name lookup if the result would
317         // refer to a member of an unknown specialization.
318         if (!isClassName && !IsCtorOrDtorName)
319           return nullptr;
320 
321         // We know from the grammar that this name refers to a type,
322         // so build a dependent node to describe the type.
323         if (WantNontrivialTypeSourceInfo)
324           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325 
326         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328                                        II, NameLoc);
329         return ParsedType::make(T);
330       }
331 
332       return nullptr;
333     }
334 
335     if (!LookupCtx->isDependentContext() &&
336         RequireCompleteDeclContext(*SS, LookupCtx))
337       return nullptr;
338   }
339 
340   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341   // lookup for class-names.
342   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
343                                       LookupOrdinaryName;
344   LookupResult Result(*this, &II, NameLoc, Kind);
345   if (LookupCtx) {
346     // Perform "qualified" name lookup into the declaration context we
347     // computed, which is either the type of the base of a member access
348     // expression or the declaration context associated with a prior
349     // nested-name-specifier.
350     LookupQualifiedName(Result, LookupCtx);
351 
352     if (ObjectTypePtr && Result.empty()) {
353       // C++ [basic.lookup.classref]p3:
354       //   If the unqualified-id is ~type-name, the type-name is looked up
355       //   in the context of the entire postfix-expression. If the type T of
356       //   the object expression is of a class type C, the type-name is also
357       //   looked up in the scope of class C. At least one of the lookups shall
358       //   find a name that refers to (possibly cv-qualified) T.
359       LookupName(Result, S);
360     }
361   } else {
362     // Perform unqualified name lookup.
363     LookupName(Result, S);
364 
365     // For unqualified lookup in a class template in MSVC mode, look into
366     // dependent base classes where the primary class template is known.
367     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
368       if (ParsedType TypeInBase =
369               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370         return TypeInBase;
371     }
372   }
373 
374   NamedDecl *IIDecl = nullptr;
375   UsingShadowDecl *FoundUsingShadow = nullptr;
376   switch (Result.getResultKind()) {
377   case LookupResult::NotFound:
378   case LookupResult::NotFoundInCurrentInstantiation:
379     if (CorrectedII) {
380       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
381                                AllowDeducedTemplate);
382       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
383                                               S, SS, CCC, CTK_ErrorRecovery);
384       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
385       TemplateTy Template;
386       bool MemberOfUnknownSpecialization;
387       UnqualifiedId TemplateName;
388       TemplateName.setIdentifier(NewII, NameLoc);
389       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
390       CXXScopeSpec NewSS, *NewSSPtr = SS;
391       if (SS && NNS) {
392         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
393         NewSSPtr = &NewSS;
394       }
395       if (Correction && (NNS || NewII != &II) &&
396           // Ignore a correction to a template type as the to-be-corrected
397           // identifier is not a template (typo correction for template names
398           // is handled elsewhere).
399           !(getLangOpts().CPlusPlus && NewSSPtr &&
400             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
401                            Template, MemberOfUnknownSpecialization))) {
402         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
403                                     isClassName, HasTrailingDot, ObjectTypePtr,
404                                     IsCtorOrDtorName,
405                                     WantNontrivialTypeSourceInfo,
406                                     IsClassTemplateDeductionContext);
407         if (Ty) {
408           diagnoseTypo(Correction,
409                        PDiag(diag::err_unknown_type_or_class_name_suggest)
410                          << Result.getLookupName() << isClassName);
411           if (SS && NNS)
412             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
413           *CorrectedII = NewII;
414           return Ty;
415         }
416       }
417     }
418     // If typo correction failed or was not performed, fall through
419     LLVM_FALLTHROUGH;
420   case LookupResult::FoundOverloaded:
421   case LookupResult::FoundUnresolvedValue:
422     Result.suppressDiagnostics();
423     return nullptr;
424 
425   case LookupResult::Ambiguous:
426     // Recover from type-hiding ambiguities by hiding the type.  We'll
427     // do the lookup again when looking for an object, and we can
428     // diagnose the error then.  If we don't do this, then the error
429     // about hiding the type will be immediately followed by an error
430     // that only makes sense if the identifier was treated like a type.
431     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
432       Result.suppressDiagnostics();
433       return nullptr;
434     }
435 
436     // Look to see if we have a type anywhere in the list of results.
437     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
438          Res != ResEnd; ++Res) {
439       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
440       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
441               RealRes) ||
442           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
443         if (!IIDecl ||
444             // Make the selection of the recovery decl deterministic.
445             RealRes->getLocation() < IIDecl->getLocation()) {
446           IIDecl = RealRes;
447           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
448         }
449       }
450     }
451 
452     if (!IIDecl) {
453       // None of the entities we found is a type, so there is no way
454       // to even assume that the result is a type. In this case, don't
455       // complain about the ambiguity. The parser will either try to
456       // perform this lookup again (e.g., as an object name), which
457       // will produce the ambiguity, or will complain that it expected
458       // a type name.
459       Result.suppressDiagnostics();
460       return nullptr;
461     }
462 
463     // We found a type within the ambiguous lookup; diagnose the
464     // ambiguity and then return that type. This might be the right
465     // answer, or it might not be, but it suppresses any attempt to
466     // perform the name lookup again.
467     break;
468 
469   case LookupResult::Found:
470     IIDecl = Result.getFoundDecl();
471     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
472     break;
473   }
474 
475   assert(IIDecl && "Didn't find decl");
476 
477   QualType T;
478   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
479     // C++ [class.qual]p2: A lookup that would find the injected-class-name
480     // instead names the constructors of the class, except when naming a class.
481     // This is ill-formed when we're not actually forming a ctor or dtor name.
482     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
483     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
484     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
485         FoundRD->isInjectedClassName() &&
486         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
487       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
488           << &II << /*Type*/1;
489 
490     DiagnoseUseOfDecl(IIDecl, NameLoc);
491 
492     T = Context.getTypeDeclType(TD);
493     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
494   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
495     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
496     if (!HasTrailingDot)
497       T = Context.getObjCInterfaceType(IDecl);
498     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
499   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
500     (void)DiagnoseUseOfDecl(UD, NameLoc);
501     // Recover with 'int'
502     T = Context.IntTy;
503     FoundUsingShadow = nullptr;
504   } else if (AllowDeducedTemplate) {
505     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
506       // FIXME: TemplateName should include FoundUsingShadow sugar.
507       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
508                                                        QualType(), false);
509       // Don't wrap in a further UsingType.
510       FoundUsingShadow = nullptr;
511     }
512   }
513 
514   if (T.isNull()) {
515     // If it's not plausibly a type, suppress diagnostics.
516     Result.suppressDiagnostics();
517     return nullptr;
518   }
519 
520   if (FoundUsingShadow)
521     T = Context.getUsingType(FoundUsingShadow, T);
522 
523   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
524   // constructor or destructor name (in such a case, the scope specifier
525   // will be attached to the enclosing Expr or Decl node).
526   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
527       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
528     if (WantNontrivialTypeSourceInfo) {
529       // Construct a type with type-source information.
530       TypeLocBuilder Builder;
531       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
532 
533       T = getElaboratedType(ETK_None, *SS, T);
534       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
535       ElabTL.setElaboratedKeywordLoc(SourceLocation());
536       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
537       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
538     } else {
539       T = getElaboratedType(ETK_None, *SS, T);
540     }
541   }
542 
543   return ParsedType::make(T);
544 }
545 
546 // Builds a fake NNS for the given decl context.
547 static NestedNameSpecifier *
548 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
549   for (;; DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     auto *ND = dyn_cast<NamespaceDecl>(DC);
552     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
553       return NestedNameSpecifier::Create(Context, nullptr, ND);
554     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
555       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
556                                          RD->getTypeForDecl());
557     else if (isa<TranslationUnitDecl>(DC))
558       return NestedNameSpecifier::GlobalSpecifier(Context);
559   }
560   llvm_unreachable("something isn't in TU scope?");
561 }
562 
563 /// Find the parent class with dependent bases of the innermost enclosing method
564 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
565 /// up allowing unqualified dependent type names at class-level, which MSVC
566 /// correctly rejects.
567 static const CXXRecordDecl *
568 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
569   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
570     DC = DC->getPrimaryContext();
571     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
572       if (MD->getParent()->hasAnyDependentBases())
573         return MD->getParent();
574   }
575   return nullptr;
576 }
577 
578 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
579                                           SourceLocation NameLoc,
580                                           bool IsTemplateTypeArg) {
581   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
582 
583   NestedNameSpecifier *NNS = nullptr;
584   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
585     // If we weren't able to parse a default template argument, delay lookup
586     // until instantiation time by making a non-dependent DependentTypeName. We
587     // pretend we saw a NestedNameSpecifier referring to the current scope, and
588     // lookup is retried.
589     // FIXME: This hurts our diagnostic quality, since we get errors like "no
590     // type named 'Foo' in 'current_namespace'" when the user didn't write any
591     // name specifiers.
592     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
593     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
594   } else if (const CXXRecordDecl *RD =
595                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
596     // Build a DependentNameType that will perform lookup into RD at
597     // instantiation time.
598     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599                                       RD->getTypeForDecl());
600 
601     // Diagnose that this identifier was undeclared, and retry the lookup during
602     // template instantiation.
603     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
604                                                                       << RD;
605   } else {
606     // This is not a situation that we should recover from.
607     return ParsedType();
608   }
609 
610   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
611 
612   // Build type location information.  We synthesized the qualifier, so we have
613   // to build a fake NestedNameSpecifierLoc.
614   NestedNameSpecifierLocBuilder NNSLocBuilder;
615   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
616   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
617 
618   TypeLocBuilder Builder;
619   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
620   DepTL.setNameLoc(NameLoc);
621   DepTL.setElaboratedKeywordLoc(SourceLocation());
622   DepTL.setQualifierLoc(QualifierLoc);
623   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
624 }
625 
626 /// isTagName() - This method is called *for error recovery purposes only*
627 /// to determine if the specified name is a valid tag name ("struct foo").  If
628 /// so, this returns the TST for the tag corresponding to it (TST_enum,
629 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
630 /// cases in C where the user forgot to specify the tag.
631 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
632   // Do a tag name lookup in this scope.
633   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
634   LookupName(R, S, false);
635   R.suppressDiagnostics();
636   if (R.getResultKind() == LookupResult::Found)
637     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
638       switch (TD->getTagKind()) {
639       case TTK_Struct: return DeclSpec::TST_struct;
640       case TTK_Interface: return DeclSpec::TST_interface;
641       case TTK_Union:  return DeclSpec::TST_union;
642       case TTK_Class:  return DeclSpec::TST_class;
643       case TTK_Enum:   return DeclSpec::TST_enum;
644       }
645     }
646 
647   return DeclSpec::TST_unspecified;
648 }
649 
650 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
651 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
652 /// then downgrade the missing typename error to a warning.
653 /// This is needed for MSVC compatibility; Example:
654 /// @code
655 /// template<class T> class A {
656 /// public:
657 ///   typedef int TYPE;
658 /// };
659 /// template<class T> class B : public A<T> {
660 /// public:
661 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
662 /// };
663 /// @endcode
664 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
665   if (CurContext->isRecord()) {
666     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
667       return true;
668 
669     const Type *Ty = SS->getScopeRep()->getAsType();
670 
671     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672     for (const auto &Base : RD->bases())
673       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674         return true;
675     return S->isFunctionPrototypeScope();
676   }
677   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678 }
679 
680 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
681                                    SourceLocation IILoc,
682                                    Scope *S,
683                                    CXXScopeSpec *SS,
684                                    ParsedType &SuggestedType,
685                                    bool IsTemplateName) {
686   // Don't report typename errors for editor placeholders.
687   if (II->isEditorPlaceholder())
688     return;
689   // We don't have anything to suggest (yet).
690   SuggestedType = nullptr;
691 
692   // There may have been a typo in the name of the type. Look up typo
693   // results, in case we have something that we can suggest.
694   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695                            /*AllowTemplates=*/IsTemplateName,
696                            /*AllowNonTemplates=*/!IsTemplateName);
697   if (TypoCorrection Corrected =
698           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
699                       CCC, CTK_ErrorRecovery)) {
700     // FIXME: Support error recovery for the template-name case.
701     bool CanRecover = !IsTemplateName;
702     if (Corrected.isKeyword()) {
703       // We corrected to a keyword.
704       diagnoseTypo(Corrected,
705                    PDiag(IsTemplateName ? diag::err_no_template_suggest
706                                         : diag::err_unknown_typename_suggest)
707                        << II);
708       II = Corrected.getCorrectionAsIdentifierInfo();
709     } else {
710       // We found a similarly-named type or interface; suggest that.
711       if (!SS || !SS->isSet()) {
712         diagnoseTypo(Corrected,
713                      PDiag(IsTemplateName ? diag::err_no_template_suggest
714                                           : diag::err_unknown_typename_suggest)
715                          << II, CanRecover);
716       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
719                                 II->getName().equals(CorrectedStr);
720         diagnoseTypo(Corrected,
721                      PDiag(IsTemplateName
722                                ? diag::err_no_member_template_suggest
723                                : diag::err_unknown_nested_typename_suggest)
724                          << II << DC << DroppedSpecifier << SS->getRange(),
725                      CanRecover);
726       } else {
727         llvm_unreachable("could not have corrected a typo here");
728       }
729 
730       if (!CanRecover)
731         return;
732 
733       CXXScopeSpec tmpSS;
734       if (Corrected.getCorrectionSpecifier())
735         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736                           SourceRange(IILoc));
737       // FIXME: Support class template argument deduction here.
738       SuggestedType =
739           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741                       /*IsCtorOrDtorName=*/false,
742                       /*WantNontrivialTypeSourceInfo=*/true);
743     }
744     return;
745   }
746 
747   if (getLangOpts().CPlusPlus && !IsTemplateName) {
748     // See if II is a class template that the user forgot to pass arguments to.
749     UnqualifiedId Name;
750     Name.setIdentifier(II, IILoc);
751     CXXScopeSpec EmptySS;
752     TemplateTy TemplateResult;
753     bool MemberOfUnknownSpecialization;
754     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755                        Name, nullptr, true, TemplateResult,
756                        MemberOfUnknownSpecialization) == TNK_Type_template) {
757       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758       return;
759     }
760   }
761 
762   // FIXME: Should we move the logic that tries to recover from a missing tag
763   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764 
765   if (!SS || (!SS->isSet() && !SS->isInvalid()))
766     Diag(IILoc, IsTemplateName ? diag::err_no_template
767                                : diag::err_unknown_typename)
768         << II;
769   else if (DeclContext *DC = computeDeclContext(*SS, false))
770     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771                                : diag::err_typename_nested_not_found)
772         << II << DC << SS->getRange();
773   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774     SuggestedType =
775         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776   } else if (isDependentScopeSpecifier(*SS)) {
777     unsigned DiagID = diag::err_typename_missing;
778     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779       DiagID = diag::ext_typename_missing;
780 
781     Diag(SS->getRange().getBegin(), DiagID)
782       << SS->getScopeRep() << II->getName()
783       << SourceRange(SS->getRange().getBegin(), IILoc)
784       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785     SuggestedType = ActOnTypenameType(S, SourceLocation(),
786                                       *SS, *II, IILoc).get();
787   } else {
788     assert(SS && SS->isInvalid() &&
789            "Invalid scope specifier has already been diagnosed");
790   }
791 }
792 
793 /// Determine whether the given result set contains either a type name
794 /// or
795 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797                        NextToken.is(tok::less);
798 
799   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801       return true;
802 
803     if (CheckTemplate && isa<TemplateDecl>(*I))
804       return true;
805   }
806 
807   return false;
808 }
809 
810 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
811                                     Scope *S, CXXScopeSpec &SS,
812                                     IdentifierInfo *&Name,
813                                     SourceLocation NameLoc) {
814   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815   SemaRef.LookupParsedName(R, S, &SS);
816   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817     StringRef FixItTagName;
818     switch (Tag->getTagKind()) {
819       case TTK_Class:
820         FixItTagName = "class ";
821         break;
822 
823       case TTK_Enum:
824         FixItTagName = "enum ";
825         break;
826 
827       case TTK_Struct:
828         FixItTagName = "struct ";
829         break;
830 
831       case TTK_Interface:
832         FixItTagName = "__interface ";
833         break;
834 
835       case TTK_Union:
836         FixItTagName = "union ";
837         break;
838     }
839 
840     StringRef TagName = FixItTagName.drop_back();
841     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844 
845     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846          I != IEnd; ++I)
847       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848         << Name << TagName;
849 
850     // Replace lookup results with just the tag decl.
851     Result.clear(Sema::LookupTagName);
852     SemaRef.LookupParsedName(Result, S, &SS);
853     return true;
854   }
855 
856   return false;
857 }
858 
859 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
860                                             IdentifierInfo *&Name,
861                                             SourceLocation NameLoc,
862                                             const Token &NextToken,
863                                             CorrectionCandidateCallback *CCC) {
864   DeclarationNameInfo NameInfo(Name, NameLoc);
865   ObjCMethodDecl *CurMethod = getCurMethodDecl();
866 
867   assert(NextToken.isNot(tok::coloncolon) &&
868          "parse nested name specifiers before calling ClassifyName");
869   if (getLangOpts().CPlusPlus && SS.isSet() &&
870       isCurrentClassName(*Name, S, &SS)) {
871     // Per [class.qual]p2, this names the constructors of SS, not the
872     // injected-class-name. We don't have a classification for that.
873     // There's not much point caching this result, since the parser
874     // will reject it later.
875     return NameClassification::Unknown();
876   }
877 
878   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879   LookupParsedName(Result, S, &SS, !CurMethod);
880 
881   if (SS.isInvalid())
882     return NameClassification::Error();
883 
884   // For unqualified lookup in a class template in MSVC mode, look into
885   // dependent base classes where the primary class template is known.
886   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
887     if (ParsedType TypeInBase =
888             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889       return TypeInBase;
890   }
891 
892   // Perform lookup for Objective-C instance variables (including automatically
893   // synthesized instance variables), if we're in an Objective-C method.
894   // FIXME: This lookup really, really needs to be folded in to the normal
895   // unqualified lookup mechanism.
896   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
897     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
898     if (Ivar.isInvalid())
899       return NameClassification::Error();
900     if (Ivar.isUsable())
901       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902 
903     // We defer builtin creation until after ivar lookup inside ObjC methods.
904     if (Result.empty())
905       LookupBuiltin(Result);
906   }
907 
908   bool SecondTry = false;
909   bool IsFilteredTemplateName = false;
910 
911 Corrected:
912   switch (Result.getResultKind()) {
913   case LookupResult::NotFound:
914     // If an unqualified-id is followed by a '(', then we have a function
915     // call.
916     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
917       // In C++, this is an ADL-only call.
918       // FIXME: Reference?
919       if (getLangOpts().CPlusPlus)
920         return NameClassification::UndeclaredNonType();
921 
922       // C90 6.3.2.2:
923       //   If the expression that precedes the parenthesized argument list in a
924       //   function call consists solely of an identifier, and if no
925       //   declaration is visible for this identifier, the identifier is
926       //   implicitly declared exactly as if, in the innermost block containing
927       //   the function call, the declaration
928       //
929       //     extern int identifier ();
930       //
931       //   appeared.
932       //
933       // We also allow this in C99 as an extension.
934       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
935         return NameClassification::NonType(D);
936     }
937 
938     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
939       // In C++20 onwards, this could be an ADL-only call to a function
940       // template, and we're required to assume that this is a template name.
941       //
942       // FIXME: Find a way to still do typo correction in this case.
943       TemplateName Template =
944           Context.getAssumedTemplateName(NameInfo.getName());
945       return NameClassification::UndeclaredTemplate(Template);
946     }
947 
948     // In C, we first see whether there is a tag type by the same name, in
949     // which case it's likely that the user just forgot to write "enum",
950     // "struct", or "union".
951     if (!getLangOpts().CPlusPlus && !SecondTry &&
952         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
953       break;
954     }
955 
956     // Perform typo correction to determine if there is another name that is
957     // close to this name.
958     if (!SecondTry && CCC) {
959       SecondTry = true;
960       if (TypoCorrection Corrected =
961               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
962                           &SS, *CCC, CTK_ErrorRecovery)) {
963         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
964         unsigned QualifiedDiag = diag::err_no_member_suggest;
965 
966         NamedDecl *FirstDecl = Corrected.getFoundDecl();
967         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
968         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
969             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
970           UnqualifiedDiag = diag::err_no_template_suggest;
971           QualifiedDiag = diag::err_no_member_template_suggest;
972         } else if (UnderlyingFirstDecl &&
973                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
974                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
975                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
976           UnqualifiedDiag = diag::err_unknown_typename_suggest;
977           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
978         }
979 
980         if (SS.isEmpty()) {
981           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
982         } else {// FIXME: is this even reachable? Test it.
983           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
984           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
985                                   Name->getName().equals(CorrectedStr);
986           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
987                                     << Name << computeDeclContext(SS, false)
988                                     << DroppedSpecifier << SS.getRange());
989         }
990 
991         // Update the name, so that the caller has the new name.
992         Name = Corrected.getCorrectionAsIdentifierInfo();
993 
994         // Typo correction corrected to a keyword.
995         if (Corrected.isKeyword())
996           return Name;
997 
998         // Also update the LookupResult...
999         // FIXME: This should probably go away at some point
1000         Result.clear();
1001         Result.setLookupName(Corrected.getCorrection());
1002         if (FirstDecl)
1003           Result.addDecl(FirstDecl);
1004 
1005         // If we found an Objective-C instance variable, let
1006         // LookupInObjCMethod build the appropriate expression to
1007         // reference the ivar.
1008         // FIXME: This is a gross hack.
1009         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1010           DeclResult R =
1011               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1012           if (R.isInvalid())
1013             return NameClassification::Error();
1014           if (R.isUsable())
1015             return NameClassification::NonType(Ivar);
1016         }
1017 
1018         goto Corrected;
1019       }
1020     }
1021 
1022     // We failed to correct; just fall through and let the parser deal with it.
1023     Result.suppressDiagnostics();
1024     return NameClassification::Unknown();
1025 
1026   case LookupResult::NotFoundInCurrentInstantiation: {
1027     // We performed name lookup into the current instantiation, and there were
1028     // dependent bases, so we treat this result the same way as any other
1029     // dependent nested-name-specifier.
1030 
1031     // C++ [temp.res]p2:
1032     //   A name used in a template declaration or definition and that is
1033     //   dependent on a template-parameter is assumed not to name a type
1034     //   unless the applicable name lookup finds a type name or the name is
1035     //   qualified by the keyword typename.
1036     //
1037     // FIXME: If the next token is '<', we might want to ask the parser to
1038     // perform some heroics to see if we actually have a
1039     // template-argument-list, which would indicate a missing 'template'
1040     // keyword here.
1041     return NameClassification::DependentNonType();
1042   }
1043 
1044   case LookupResult::Found:
1045   case LookupResult::FoundOverloaded:
1046   case LookupResult::FoundUnresolvedValue:
1047     break;
1048 
1049   case LookupResult::Ambiguous:
1050     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1051         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1052                                       /*AllowDependent=*/false)) {
1053       // C++ [temp.local]p3:
1054       //   A lookup that finds an injected-class-name (10.2) can result in an
1055       //   ambiguity in certain cases (for example, if it is found in more than
1056       //   one base class). If all of the injected-class-names that are found
1057       //   refer to specializations of the same class template, and if the name
1058       //   is followed by a template-argument-list, the reference refers to the
1059       //   class template itself and not a specialization thereof, and is not
1060       //   ambiguous.
1061       //
1062       // This filtering can make an ambiguous result into an unambiguous one,
1063       // so try again after filtering out template names.
1064       FilterAcceptableTemplateNames(Result);
1065       if (!Result.isAmbiguous()) {
1066         IsFilteredTemplateName = true;
1067         break;
1068       }
1069     }
1070 
1071     // Diagnose the ambiguity and return an error.
1072     return NameClassification::Error();
1073   }
1074 
1075   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1076       (IsFilteredTemplateName ||
1077        hasAnyAcceptableTemplateNames(
1078            Result, /*AllowFunctionTemplates=*/true,
1079            /*AllowDependent=*/false,
1080            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1081                getLangOpts().CPlusPlus20))) {
1082     // C++ [temp.names]p3:
1083     //   After name lookup (3.4) finds that a name is a template-name or that
1084     //   an operator-function-id or a literal- operator-id refers to a set of
1085     //   overloaded functions any member of which is a function template if
1086     //   this is followed by a <, the < is always taken as the delimiter of a
1087     //   template-argument-list and never as the less-than operator.
1088     // C++2a [temp.names]p2:
1089     //   A name is also considered to refer to a template if it is an
1090     //   unqualified-id followed by a < and name lookup finds either one
1091     //   or more functions or finds nothing.
1092     if (!IsFilteredTemplateName)
1093       FilterAcceptableTemplateNames(Result);
1094 
1095     bool IsFunctionTemplate;
1096     bool IsVarTemplate;
1097     TemplateName Template;
1098     if (Result.end() - Result.begin() > 1) {
1099       IsFunctionTemplate = true;
1100       Template = Context.getOverloadedTemplateName(Result.begin(),
1101                                                    Result.end());
1102     } else if (!Result.empty()) {
1103       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1104           *Result.begin(), /*AllowFunctionTemplates=*/true,
1105           /*AllowDependent=*/false));
1106       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1107       IsVarTemplate = isa<VarTemplateDecl>(TD);
1108 
1109       if (SS.isNotEmpty())
1110         Template =
1111             Context.getQualifiedTemplateName(SS.getScopeRep(),
1112                                              /*TemplateKeyword=*/false, TD);
1113       else
1114         Template = TemplateName(TD);
1115     } else {
1116       // All results were non-template functions. This is a function template
1117       // name.
1118       IsFunctionTemplate = true;
1119       Template = Context.getAssumedTemplateName(NameInfo.getName());
1120     }
1121 
1122     if (IsFunctionTemplate) {
1123       // Function templates always go through overload resolution, at which
1124       // point we'll perform the various checks (e.g., accessibility) we need
1125       // to based on which function we selected.
1126       Result.suppressDiagnostics();
1127 
1128       return NameClassification::FunctionTemplate(Template);
1129     }
1130 
1131     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1132                          : NameClassification::TypeTemplate(Template);
1133   }
1134 
1135   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1136     QualType T = Context.getTypeDeclType(Type);
1137     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1138       T = Context.getUsingType(USD, T);
1139 
1140     if (SS.isEmpty()) // No elaborated type, trivial location info
1141       return ParsedType::make(T);
1142 
1143     TypeLocBuilder Builder;
1144     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1145     T = getElaboratedType(ETK_None, SS, T);
1146     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1147     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1148     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1149     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1150   };
1151 
1152   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154     DiagnoseUseOfDecl(Type, NameLoc);
1155     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156     return BuildTypeFor(Type, *Result.begin());
1157   }
1158 
1159   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160   if (!Class) {
1161     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162     if (ObjCCompatibleAliasDecl *Alias =
1163             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164       Class = Alias->getClassInterface();
1165   }
1166 
1167   if (Class) {
1168     DiagnoseUseOfDecl(Class, NameLoc);
1169 
1170     if (NextToken.is(tok::period)) {
1171       // Interface. <something> is parsed as a property reference expression.
1172       // Just return "unknown" as a fall-through for now.
1173       Result.suppressDiagnostics();
1174       return NameClassification::Unknown();
1175     }
1176 
1177     QualType T = Context.getObjCInterfaceType(Class);
1178     return ParsedType::make(T);
1179   }
1180 
1181   if (isa<ConceptDecl>(FirstDecl))
1182     return NameClassification::Concept(
1183         TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 
1185   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1187     return NameClassification::Error();
1188   }
1189 
1190   // We can have a type template here if we're classifying a template argument.
1191   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192       !isa<VarTemplateDecl>(FirstDecl))
1193     return NameClassification::TypeTemplate(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   // Check for a tag type hidden by a non-type decl in a few cases where it
1197   // seems likely a type is wanted instead of the non-type that was found.
1198   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199   if ((NextToken.is(tok::identifier) ||
1200        (NextIsOp &&
1201         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1202       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1203     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204     DiagnoseUseOfDecl(Type, NameLoc);
1205     return BuildTypeFor(Type, *Result.begin());
1206   }
1207 
1208   // If we already know which single declaration is referenced, just annotate
1209   // that declaration directly. Defer resolving even non-overloaded class
1210   // member accesses, as we need to defer certain access checks until we know
1211   // the context.
1212   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1214     return NameClassification::NonType(Result.getRepresentativeDecl());
1215 
1216   // Otherwise, this is an overload set that we will need to resolve later.
1217   Result.suppressDiagnostics();
1218   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1219       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1220       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1221       Result.begin(), Result.end()));
1222 }
1223 
1224 ExprResult
1225 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1226                                              SourceLocation NameLoc) {
1227   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1228   CXXScopeSpec SS;
1229   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1230   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1231 }
1232 
1233 ExprResult
1234 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1235                                             IdentifierInfo *Name,
1236                                             SourceLocation NameLoc,
1237                                             bool IsAddressOfOperand) {
1238   DeclarationNameInfo NameInfo(Name, NameLoc);
1239   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1240                                     NameInfo, IsAddressOfOperand,
1241                                     /*TemplateArgs=*/nullptr);
1242 }
1243 
1244 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1245                                               NamedDecl *Found,
1246                                               SourceLocation NameLoc,
1247                                               const Token &NextToken) {
1248   if (getCurMethodDecl() && SS.isEmpty())
1249     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1250       return BuildIvarRefExpr(S, NameLoc, Ivar);
1251 
1252   // Reconstruct the lookup result.
1253   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1254   Result.addDecl(Found);
1255   Result.resolveKind();
1256 
1257   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1258   return BuildDeclarationNameExpr(SS, Result, ADL);
1259 }
1260 
1261 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1262   // For an implicit class member access, transform the result into a member
1263   // access expression if necessary.
1264   auto *ULE = cast<UnresolvedLookupExpr>(E);
1265   if ((*ULE->decls_begin())->isCXXClassMember()) {
1266     CXXScopeSpec SS;
1267     SS.Adopt(ULE->getQualifierLoc());
1268 
1269     // Reconstruct the lookup result.
1270     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1271                         LookupOrdinaryName);
1272     Result.setNamingClass(ULE->getNamingClass());
1273     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1274       Result.addDecl(*I, I.getAccess());
1275     Result.resolveKind();
1276     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1277                                            nullptr, S);
1278   }
1279 
1280   // Otherwise, this is already in the form we needed, and no further checks
1281   // are necessary.
1282   return ULE;
1283 }
1284 
1285 Sema::TemplateNameKindForDiagnostics
1286 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1287   auto *TD = Name.getAsTemplateDecl();
1288   if (!TD)
1289     return TemplateNameKindForDiagnostics::DependentTemplate;
1290   if (isa<ClassTemplateDecl>(TD))
1291     return TemplateNameKindForDiagnostics::ClassTemplate;
1292   if (isa<FunctionTemplateDecl>(TD))
1293     return TemplateNameKindForDiagnostics::FunctionTemplate;
1294   if (isa<VarTemplateDecl>(TD))
1295     return TemplateNameKindForDiagnostics::VarTemplate;
1296   if (isa<TypeAliasTemplateDecl>(TD))
1297     return TemplateNameKindForDiagnostics::AliasTemplate;
1298   if (isa<TemplateTemplateParmDecl>(TD))
1299     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1300   if (isa<ConceptDecl>(TD))
1301     return TemplateNameKindForDiagnostics::Concept;
1302   return TemplateNameKindForDiagnostics::DependentTemplate;
1303 }
1304 
1305 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1306   assert(DC->getLexicalParent() == CurContext &&
1307       "The next DeclContext should be lexically contained in the current one.");
1308   CurContext = DC;
1309   S->setEntity(DC);
1310 }
1311 
1312 void Sema::PopDeclContext() {
1313   assert(CurContext && "DeclContext imbalance!");
1314 
1315   CurContext = CurContext->getLexicalParent();
1316   assert(CurContext && "Popped translation unit!");
1317 }
1318 
1319 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1320                                                                     Decl *D) {
1321   // Unlike PushDeclContext, the context to which we return is not necessarily
1322   // the containing DC of TD, because the new context will be some pre-existing
1323   // TagDecl definition instead of a fresh one.
1324   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1325   CurContext = cast<TagDecl>(D)->getDefinition();
1326   assert(CurContext && "skipping definition of undefined tag");
1327   // Start lookups from the parent of the current context; we don't want to look
1328   // into the pre-existing complete definition.
1329   S->setEntity(CurContext->getLookupParent());
1330   return Result;
1331 }
1332 
1333 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1334   CurContext = static_cast<decltype(CurContext)>(Context);
1335 }
1336 
1337 /// EnterDeclaratorContext - Used when we must lookup names in the context
1338 /// of a declarator's nested name specifier.
1339 ///
1340 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1341   // C++0x [basic.lookup.unqual]p13:
1342   //   A name used in the definition of a static data member of class
1343   //   X (after the qualified-id of the static member) is looked up as
1344   //   if the name was used in a member function of X.
1345   // C++0x [basic.lookup.unqual]p14:
1346   //   If a variable member of a namespace is defined outside of the
1347   //   scope of its namespace then any name used in the definition of
1348   //   the variable member (after the declarator-id) is looked up as
1349   //   if the definition of the variable member occurred in its
1350   //   namespace.
1351   // Both of these imply that we should push a scope whose context
1352   // is the semantic context of the declaration.  We can't use
1353   // PushDeclContext here because that context is not necessarily
1354   // lexically contained in the current context.  Fortunately,
1355   // the containing scope should have the appropriate information.
1356 
1357   assert(!S->getEntity() && "scope already has entity");
1358 
1359 #ifndef NDEBUG
1360   Scope *Ancestor = S->getParent();
1361   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1362   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1363 #endif
1364 
1365   CurContext = DC;
1366   S->setEntity(DC);
1367 
1368   if (S->getParent()->isTemplateParamScope()) {
1369     // Also set the corresponding entities for all immediately-enclosing
1370     // template parameter scopes.
1371     EnterTemplatedContext(S->getParent(), DC);
1372   }
1373 }
1374 
1375 void Sema::ExitDeclaratorContext(Scope *S) {
1376   assert(S->getEntity() == CurContext && "Context imbalance!");
1377 
1378   // Switch back to the lexical context.  The safety of this is
1379   // enforced by an assert in EnterDeclaratorContext.
1380   Scope *Ancestor = S->getParent();
1381   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1382   CurContext = Ancestor->getEntity();
1383 
1384   // We don't need to do anything with the scope, which is going to
1385   // disappear.
1386 }
1387 
1388 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1389   assert(S->isTemplateParamScope() &&
1390          "expected to be initializing a template parameter scope");
1391 
1392   // C++20 [temp.local]p7:
1393   //   In the definition of a member of a class template that appears outside
1394   //   of the class template definition, the name of a member of the class
1395   //   template hides the name of a template-parameter of any enclosing class
1396   //   templates (but not a template-parameter of the member if the member is a
1397   //   class or function template).
1398   // C++20 [temp.local]p9:
1399   //   In the definition of a class template or in the definition of a member
1400   //   of such a template that appears outside of the template definition, for
1401   //   each non-dependent base class (13.8.2.1), if the name of the base class
1402   //   or the name of a member of the base class is the same as the name of a
1403   //   template-parameter, the base class name or member name hides the
1404   //   template-parameter name (6.4.10).
1405   //
1406   // This means that a template parameter scope should be searched immediately
1407   // after searching the DeclContext for which it is a template parameter
1408   // scope. For example, for
1409   //   template<typename T> template<typename U> template<typename V>
1410   //     void N::A<T>::B<U>::f(...)
1411   // we search V then B<U> (and base classes) then U then A<T> (and base
1412   // classes) then T then N then ::.
1413   unsigned ScopeDepth = getTemplateDepth(S);
1414   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1415     DeclContext *SearchDCAfterScope = DC;
1416     for (; DC; DC = DC->getLookupParent()) {
1417       if (const TemplateParameterList *TPL =
1418               cast<Decl>(DC)->getDescribedTemplateParams()) {
1419         unsigned DCDepth = TPL->getDepth() + 1;
1420         if (DCDepth > ScopeDepth)
1421           continue;
1422         if (ScopeDepth == DCDepth)
1423           SearchDCAfterScope = DC = DC->getLookupParent();
1424         break;
1425       }
1426     }
1427     S->setLookupEntity(SearchDCAfterScope);
1428   }
1429 }
1430 
1431 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1432   // We assume that the caller has already called
1433   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1434   FunctionDecl *FD = D->getAsFunction();
1435   if (!FD)
1436     return;
1437 
1438   // Same implementation as PushDeclContext, but enters the context
1439   // from the lexical parent, rather than the top-level class.
1440   assert(CurContext == FD->getLexicalParent() &&
1441     "The next DeclContext should be lexically contained in the current one.");
1442   CurContext = FD;
1443   S->setEntity(CurContext);
1444 
1445   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1446     ParmVarDecl *Param = FD->getParamDecl(P);
1447     // If the parameter has an identifier, then add it to the scope
1448     if (Param->getIdentifier()) {
1449       S->AddDecl(Param);
1450       IdResolver.AddDecl(Param);
1451     }
1452   }
1453 }
1454 
1455 void Sema::ActOnExitFunctionContext() {
1456   // Same implementation as PopDeclContext, but returns to the lexical parent,
1457   // rather than the top-level class.
1458   assert(CurContext && "DeclContext imbalance!");
1459   CurContext = CurContext->getLexicalParent();
1460   assert(CurContext && "Popped translation unit!");
1461 }
1462 
1463 /// Determine whether we allow overloading of the function
1464 /// PrevDecl with another declaration.
1465 ///
1466 /// This routine determines whether overloading is possible, not
1467 /// whether some new function is actually an overload. It will return
1468 /// true in C++ (where we can always provide overloads) or, as an
1469 /// extension, in C when the previous function is already an
1470 /// overloaded function declaration or has the "overloadable"
1471 /// attribute.
1472 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1473                                        ASTContext &Context,
1474                                        const FunctionDecl *New) {
1475   if (Context.getLangOpts().CPlusPlus)
1476     return true;
1477 
1478   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1479     return true;
1480 
1481   return Previous.getResultKind() == LookupResult::Found &&
1482          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1483           New->hasAttr<OverloadableAttr>());
1484 }
1485 
1486 /// Add this decl to the scope shadowed decl chains.
1487 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1488   // Move up the scope chain until we find the nearest enclosing
1489   // non-transparent context. The declaration will be introduced into this
1490   // scope.
1491   while (S->getEntity() && S->getEntity()->isTransparentContext())
1492     S = S->getParent();
1493 
1494   // Add scoped declarations into their context, so that they can be
1495   // found later. Declarations without a context won't be inserted
1496   // into any context.
1497   if (AddToContext)
1498     CurContext->addDecl(D);
1499 
1500   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1501   // are function-local declarations.
1502   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1503     return;
1504 
1505   // Template instantiations should also not be pushed into scope.
1506   if (isa<FunctionDecl>(D) &&
1507       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1508     return;
1509 
1510   // If this replaces anything in the current scope,
1511   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1512                                IEnd = IdResolver.end();
1513   for (; I != IEnd; ++I) {
1514     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1515       S->RemoveDecl(*I);
1516       IdResolver.RemoveDecl(*I);
1517 
1518       // Should only need to replace one decl.
1519       break;
1520     }
1521   }
1522 
1523   S->AddDecl(D);
1524 
1525   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1526     // Implicitly-generated labels may end up getting generated in an order that
1527     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1528     // the label at the appropriate place in the identifier chain.
1529     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1530       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1531       if (IDC == CurContext) {
1532         if (!S->isDeclScope(*I))
1533           continue;
1534       } else if (IDC->Encloses(CurContext))
1535         break;
1536     }
1537 
1538     IdResolver.InsertDeclAfter(I, D);
1539   } else {
1540     IdResolver.AddDecl(D);
1541   }
1542   warnOnReservedIdentifier(D);
1543 }
1544 
1545 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1546                          bool AllowInlineNamespace) {
1547   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1548 }
1549 
1550 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1551   DeclContext *TargetDC = DC->getPrimaryContext();
1552   do {
1553     if (DeclContext *ScopeDC = S->getEntity())
1554       if (ScopeDC->getPrimaryContext() == TargetDC)
1555         return S;
1556   } while ((S = S->getParent()));
1557 
1558   return nullptr;
1559 }
1560 
1561 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1562                                             DeclContext*,
1563                                             ASTContext&);
1564 
1565 /// Filters out lookup results that don't fall within the given scope
1566 /// as determined by isDeclInScope.
1567 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1568                                 bool ConsiderLinkage,
1569                                 bool AllowInlineNamespace) {
1570   LookupResult::Filter F = R.makeFilter();
1571   while (F.hasNext()) {
1572     NamedDecl *D = F.next();
1573 
1574     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1575       continue;
1576 
1577     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1578       continue;
1579 
1580     F.erase();
1581   }
1582 
1583   F.done();
1584 }
1585 
1586 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1587 /// have compatible owning modules.
1588 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1589   // [module.interface]p7:
1590   // A declaration is attached to a module as follows:
1591   // - If the declaration is a non-dependent friend declaration that nominates a
1592   // function with a declarator-id that is a qualified-id or template-id or that
1593   // nominates a class other than with an elaborated-type-specifier with neither
1594   // a nested-name-specifier nor a simple-template-id, it is attached to the
1595   // module to which the friend is attached ([basic.link]).
1596   if (New->getFriendObjectKind() &&
1597       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1598     New->setLocalOwningModule(Old->getOwningModule());
1599     makeMergedDefinitionVisible(New);
1600     return false;
1601   }
1602 
1603   Module *NewM = New->getOwningModule();
1604   Module *OldM = Old->getOwningModule();
1605 
1606   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1607     NewM = NewM->Parent;
1608   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1609     OldM = OldM->Parent;
1610 
1611   // If we have a decl in a module partition, it is part of the containing
1612   // module (which is the only thing that can be importing it).
1613   if (NewM && OldM &&
1614       (OldM->Kind == Module::ModulePartitionInterface ||
1615        OldM->Kind == Module::ModulePartitionImplementation)) {
1616     return false;
1617   }
1618 
1619   if (NewM == OldM)
1620     return false;
1621 
1622   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1623   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1624   if (NewIsModuleInterface || OldIsModuleInterface) {
1625     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1626     //   if a declaration of D [...] appears in the purview of a module, all
1627     //   other such declarations shall appear in the purview of the same module
1628     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1629       << New
1630       << NewIsModuleInterface
1631       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1632       << OldIsModuleInterface
1633       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1634     Diag(Old->getLocation(), diag::note_previous_declaration);
1635     New->setInvalidDecl();
1636     return true;
1637   }
1638 
1639   return false;
1640 }
1641 
1642 // [module.interface]p6:
1643 // A redeclaration of an entity X is implicitly exported if X was introduced by
1644 // an exported declaration; otherwise it shall not be exported.
1645 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1646   // [module.interface]p1:
1647   // An export-declaration shall inhabit a namespace scope.
1648   //
1649   // So it is meaningless to talk about redeclaration which is not at namespace
1650   // scope.
1651   if (!New->getLexicalDeclContext()
1652            ->getNonTransparentContext()
1653            ->isFileContext() ||
1654       !Old->getLexicalDeclContext()
1655            ->getNonTransparentContext()
1656            ->isFileContext())
1657     return false;
1658 
1659   bool IsNewExported = New->isInExportDeclContext();
1660   bool IsOldExported = Old->isInExportDeclContext();
1661 
1662   // It should be irrevelant if both of them are not exported.
1663   if (!IsNewExported && !IsOldExported)
1664     return false;
1665 
1666   if (IsOldExported)
1667     return false;
1668 
1669   assert(IsNewExported);
1670 
1671   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New;
1672   Diag(Old->getLocation(), diag::note_previous_declaration);
1673   return true;
1674 }
1675 
1676 // A wrapper function for checking the semantic restrictions of
1677 // a redeclaration within a module.
1678 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1679   if (CheckRedeclarationModuleOwnership(New, Old))
1680     return true;
1681 
1682   if (CheckRedeclarationExported(New, Old))
1683     return true;
1684 
1685   return false;
1686 }
1687 
1688 static bool isUsingDecl(NamedDecl *D) {
1689   return isa<UsingShadowDecl>(D) ||
1690          isa<UnresolvedUsingTypenameDecl>(D) ||
1691          isa<UnresolvedUsingValueDecl>(D);
1692 }
1693 
1694 /// Removes using shadow declarations from the lookup results.
1695 static void RemoveUsingDecls(LookupResult &R) {
1696   LookupResult::Filter F = R.makeFilter();
1697   while (F.hasNext())
1698     if (isUsingDecl(F.next()))
1699       F.erase();
1700 
1701   F.done();
1702 }
1703 
1704 /// Check for this common pattern:
1705 /// @code
1706 /// class S {
1707 ///   S(const S&); // DO NOT IMPLEMENT
1708 ///   void operator=(const S&); // DO NOT IMPLEMENT
1709 /// };
1710 /// @endcode
1711 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1712   // FIXME: Should check for private access too but access is set after we get
1713   // the decl here.
1714   if (D->doesThisDeclarationHaveABody())
1715     return false;
1716 
1717   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1718     return CD->isCopyConstructor();
1719   return D->isCopyAssignmentOperator();
1720 }
1721 
1722 // We need this to handle
1723 //
1724 // typedef struct {
1725 //   void *foo() { return 0; }
1726 // } A;
1727 //
1728 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1729 // for example. If 'A', foo will have external linkage. If we have '*A',
1730 // foo will have no linkage. Since we can't know until we get to the end
1731 // of the typedef, this function finds out if D might have non-external linkage.
1732 // Callers should verify at the end of the TU if it D has external linkage or
1733 // not.
1734 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1735   const DeclContext *DC = D->getDeclContext();
1736   while (!DC->isTranslationUnit()) {
1737     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1738       if (!RD->hasNameForLinkage())
1739         return true;
1740     }
1741     DC = DC->getParent();
1742   }
1743 
1744   return !D->isExternallyVisible();
1745 }
1746 
1747 // FIXME: This needs to be refactored; some other isInMainFile users want
1748 // these semantics.
1749 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1750   if (S.TUKind != TU_Complete)
1751     return false;
1752   return S.SourceMgr.isInMainFile(Loc);
1753 }
1754 
1755 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1756   assert(D);
1757 
1758   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1759     return false;
1760 
1761   // Ignore all entities declared within templates, and out-of-line definitions
1762   // of members of class templates.
1763   if (D->getDeclContext()->isDependentContext() ||
1764       D->getLexicalDeclContext()->isDependentContext())
1765     return false;
1766 
1767   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1768     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1769       return false;
1770     // A non-out-of-line declaration of a member specialization was implicitly
1771     // instantiated; it's the out-of-line declaration that we're interested in.
1772     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1773         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1774       return false;
1775 
1776     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1777       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1778         return false;
1779     } else {
1780       // 'static inline' functions are defined in headers; don't warn.
1781       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1782         return false;
1783     }
1784 
1785     if (FD->doesThisDeclarationHaveABody() &&
1786         Context.DeclMustBeEmitted(FD))
1787       return false;
1788   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1789     // Constants and utility variables are defined in headers with internal
1790     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1791     // like "inline".)
1792     if (!isMainFileLoc(*this, VD->getLocation()))
1793       return false;
1794 
1795     if (Context.DeclMustBeEmitted(VD))
1796       return false;
1797 
1798     if (VD->isStaticDataMember() &&
1799         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1800       return false;
1801     if (VD->isStaticDataMember() &&
1802         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1803         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1804       return false;
1805 
1806     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1807       return false;
1808   } else {
1809     return false;
1810   }
1811 
1812   // Only warn for unused decls internal to the translation unit.
1813   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1814   // for inline functions defined in the main source file, for instance.
1815   return mightHaveNonExternalLinkage(D);
1816 }
1817 
1818 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1819   if (!D)
1820     return;
1821 
1822   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1823     const FunctionDecl *First = FD->getFirstDecl();
1824     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1825       return; // First should already be in the vector.
1826   }
1827 
1828   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1829     const VarDecl *First = VD->getFirstDecl();
1830     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1831       return; // First should already be in the vector.
1832   }
1833 
1834   if (ShouldWarnIfUnusedFileScopedDecl(D))
1835     UnusedFileScopedDecls.push_back(D);
1836 }
1837 
1838 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1839   if (D->isInvalidDecl())
1840     return false;
1841 
1842   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1843     // For a decomposition declaration, warn if none of the bindings are
1844     // referenced, instead of if the variable itself is referenced (which
1845     // it is, by the bindings' expressions).
1846     for (auto *BD : DD->bindings())
1847       if (BD->isReferenced())
1848         return false;
1849   } else if (!D->getDeclName()) {
1850     return false;
1851   } else if (D->isReferenced() || D->isUsed()) {
1852     return false;
1853   }
1854 
1855   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1856     return false;
1857 
1858   if (isa<LabelDecl>(D))
1859     return true;
1860 
1861   // Except for labels, we only care about unused decls that are local to
1862   // functions.
1863   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1864   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1865     // For dependent types, the diagnostic is deferred.
1866     WithinFunction =
1867         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1868   if (!WithinFunction)
1869     return false;
1870 
1871   if (isa<TypedefNameDecl>(D))
1872     return true;
1873 
1874   // White-list anything that isn't a local variable.
1875   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1876     return false;
1877 
1878   // Types of valid local variables should be complete, so this should succeed.
1879   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1880 
1881     // White-list anything with an __attribute__((unused)) type.
1882     const auto *Ty = VD->getType().getTypePtr();
1883 
1884     // Only look at the outermost level of typedef.
1885     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1886       if (TT->getDecl()->hasAttr<UnusedAttr>())
1887         return false;
1888     }
1889 
1890     // If we failed to complete the type for some reason, or if the type is
1891     // dependent, don't diagnose the variable.
1892     if (Ty->isIncompleteType() || Ty->isDependentType())
1893       return false;
1894 
1895     // Look at the element type to ensure that the warning behaviour is
1896     // consistent for both scalars and arrays.
1897     Ty = Ty->getBaseElementTypeUnsafe();
1898 
1899     if (const TagType *TT = Ty->getAs<TagType>()) {
1900       const TagDecl *Tag = TT->getDecl();
1901       if (Tag->hasAttr<UnusedAttr>())
1902         return false;
1903 
1904       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1905         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1906           return false;
1907 
1908         if (const Expr *Init = VD->getInit()) {
1909           if (const ExprWithCleanups *Cleanups =
1910                   dyn_cast<ExprWithCleanups>(Init))
1911             Init = Cleanups->getSubExpr();
1912           const CXXConstructExpr *Construct =
1913             dyn_cast<CXXConstructExpr>(Init);
1914           if (Construct && !Construct->isElidable()) {
1915             CXXConstructorDecl *CD = Construct->getConstructor();
1916             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1917                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1918               return false;
1919           }
1920 
1921           // Suppress the warning if we don't know how this is constructed, and
1922           // it could possibly be non-trivial constructor.
1923           if (Init->isTypeDependent())
1924             for (const CXXConstructorDecl *Ctor : RD->ctors())
1925               if (!Ctor->isTrivial())
1926                 return false;
1927         }
1928       }
1929     }
1930 
1931     // TODO: __attribute__((unused)) templates?
1932   }
1933 
1934   return true;
1935 }
1936 
1937 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1938                                      FixItHint &Hint) {
1939   if (isa<LabelDecl>(D)) {
1940     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1941         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1942         true);
1943     if (AfterColon.isInvalid())
1944       return;
1945     Hint = FixItHint::CreateRemoval(
1946         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1947   }
1948 }
1949 
1950 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1951   if (D->getTypeForDecl()->isDependentType())
1952     return;
1953 
1954   for (auto *TmpD : D->decls()) {
1955     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1956       DiagnoseUnusedDecl(T);
1957     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1958       DiagnoseUnusedNestedTypedefs(R);
1959   }
1960 }
1961 
1962 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1963 /// unless they are marked attr(unused).
1964 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1965   if (!ShouldDiagnoseUnusedDecl(D))
1966     return;
1967 
1968   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1969     // typedefs can be referenced later on, so the diagnostics are emitted
1970     // at end-of-translation-unit.
1971     UnusedLocalTypedefNameCandidates.insert(TD);
1972     return;
1973   }
1974 
1975   FixItHint Hint;
1976   GenerateFixForUnusedDecl(D, Context, Hint);
1977 
1978   unsigned DiagID;
1979   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1980     DiagID = diag::warn_unused_exception_param;
1981   else if (isa<LabelDecl>(D))
1982     DiagID = diag::warn_unused_label;
1983   else
1984     DiagID = diag::warn_unused_variable;
1985 
1986   Diag(D->getLocation(), DiagID) << D << Hint;
1987 }
1988 
1989 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1990   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
1991   // it's not really unused.
1992   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
1993       VD->hasAttr<CleanupAttr>())
1994     return;
1995 
1996   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1997 
1998   if (Ty->isReferenceType() || Ty->isDependentType())
1999     return;
2000 
2001   if (const TagType *TT = Ty->getAs<TagType>()) {
2002     const TagDecl *Tag = TT->getDecl();
2003     if (Tag->hasAttr<UnusedAttr>())
2004       return;
2005     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2006     // mimic gcc's behavior.
2007     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2008       if (!RD->hasAttr<WarnUnusedAttr>())
2009         return;
2010     }
2011   }
2012 
2013   // Don't warn about __block Objective-C pointer variables, as they might
2014   // be assigned in the block but not used elsewhere for the purpose of lifetime
2015   // extension.
2016   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2017     return;
2018 
2019   // Don't warn about Objective-C pointer variables with precise lifetime
2020   // semantics; they can be used to ensure ARC releases the object at a known
2021   // time, which may mean assignment but no other references.
2022   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2023     return;
2024 
2025   auto iter = RefsMinusAssignments.find(VD);
2026   if (iter == RefsMinusAssignments.end())
2027     return;
2028 
2029   assert(iter->getSecond() >= 0 &&
2030          "Found a negative number of references to a VarDecl");
2031   if (iter->getSecond() != 0)
2032     return;
2033   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2034                                          : diag::warn_unused_but_set_variable;
2035   Diag(VD->getLocation(), DiagID) << VD;
2036 }
2037 
2038 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2039   // Verify that we have no forward references left.  If so, there was a goto
2040   // or address of a label taken, but no definition of it.  Label fwd
2041   // definitions are indicated with a null substmt which is also not a resolved
2042   // MS inline assembly label name.
2043   bool Diagnose = false;
2044   if (L->isMSAsmLabel())
2045     Diagnose = !L->isResolvedMSAsmLabel();
2046   else
2047     Diagnose = L->getStmt() == nullptr;
2048   if (Diagnose)
2049     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2050 }
2051 
2052 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2053   S->mergeNRVOIntoParent();
2054 
2055   if (S->decl_empty()) return;
2056   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2057          "Scope shouldn't contain decls!");
2058 
2059   for (auto *TmpD : S->decls()) {
2060     assert(TmpD && "This decl didn't get pushed??");
2061 
2062     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2063     NamedDecl *D = cast<NamedDecl>(TmpD);
2064 
2065     // Diagnose unused variables in this scope.
2066     if (!S->hasUnrecoverableErrorOccurred()) {
2067       DiagnoseUnusedDecl(D);
2068       if (const auto *RD = dyn_cast<RecordDecl>(D))
2069         DiagnoseUnusedNestedTypedefs(RD);
2070       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2071         DiagnoseUnusedButSetDecl(VD);
2072         RefsMinusAssignments.erase(VD);
2073       }
2074     }
2075 
2076     if (!D->getDeclName()) continue;
2077 
2078     // If this was a forward reference to a label, verify it was defined.
2079     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2080       CheckPoppedLabel(LD, *this);
2081 
2082     // Remove this name from our lexical scope, and warn on it if we haven't
2083     // already.
2084     IdResolver.RemoveDecl(D);
2085     auto ShadowI = ShadowingDecls.find(D);
2086     if (ShadowI != ShadowingDecls.end()) {
2087       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2088         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2089             << D << FD << FD->getParent();
2090         Diag(FD->getLocation(), diag::note_previous_declaration);
2091       }
2092       ShadowingDecls.erase(ShadowI);
2093     }
2094   }
2095 }
2096 
2097 /// Look for an Objective-C class in the translation unit.
2098 ///
2099 /// \param Id The name of the Objective-C class we're looking for. If
2100 /// typo-correction fixes this name, the Id will be updated
2101 /// to the fixed name.
2102 ///
2103 /// \param IdLoc The location of the name in the translation unit.
2104 ///
2105 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2106 /// if there is no class with the given name.
2107 ///
2108 /// \returns The declaration of the named Objective-C class, or NULL if the
2109 /// class could not be found.
2110 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2111                                               SourceLocation IdLoc,
2112                                               bool DoTypoCorrection) {
2113   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2114   // creation from this context.
2115   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2116 
2117   if (!IDecl && DoTypoCorrection) {
2118     // Perform typo correction at the given location, but only if we
2119     // find an Objective-C class name.
2120     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2121     if (TypoCorrection C =
2122             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2123                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2124       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2125       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2126       Id = IDecl->getIdentifier();
2127     }
2128   }
2129   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2130   // This routine must always return a class definition, if any.
2131   if (Def && Def->getDefinition())
2132       Def = Def->getDefinition();
2133   return Def;
2134 }
2135 
2136 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2137 /// from S, where a non-field would be declared. This routine copes
2138 /// with the difference between C and C++ scoping rules in structs and
2139 /// unions. For example, the following code is well-formed in C but
2140 /// ill-formed in C++:
2141 /// @code
2142 /// struct S6 {
2143 ///   enum { BAR } e;
2144 /// };
2145 ///
2146 /// void test_S6() {
2147 ///   struct S6 a;
2148 ///   a.e = BAR;
2149 /// }
2150 /// @endcode
2151 /// For the declaration of BAR, this routine will return a different
2152 /// scope. The scope S will be the scope of the unnamed enumeration
2153 /// within S6. In C++, this routine will return the scope associated
2154 /// with S6, because the enumeration's scope is a transparent
2155 /// context but structures can contain non-field names. In C, this
2156 /// routine will return the translation unit scope, since the
2157 /// enumeration's scope is a transparent context and structures cannot
2158 /// contain non-field names.
2159 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2160   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2161          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2162          (S->isClassScope() && !getLangOpts().CPlusPlus))
2163     S = S->getParent();
2164   return S;
2165 }
2166 
2167 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2168                                ASTContext::GetBuiltinTypeError Error) {
2169   switch (Error) {
2170   case ASTContext::GE_None:
2171     return "";
2172   case ASTContext::GE_Missing_type:
2173     return BuiltinInfo.getHeaderName(ID);
2174   case ASTContext::GE_Missing_stdio:
2175     return "stdio.h";
2176   case ASTContext::GE_Missing_setjmp:
2177     return "setjmp.h";
2178   case ASTContext::GE_Missing_ucontext:
2179     return "ucontext.h";
2180   }
2181   llvm_unreachable("unhandled error kind");
2182 }
2183 
2184 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2185                                   unsigned ID, SourceLocation Loc) {
2186   DeclContext *Parent = Context.getTranslationUnitDecl();
2187 
2188   if (getLangOpts().CPlusPlus) {
2189     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2190         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2191     CLinkageDecl->setImplicit();
2192     Parent->addDecl(CLinkageDecl);
2193     Parent = CLinkageDecl;
2194   }
2195 
2196   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2197                                            /*TInfo=*/nullptr, SC_Extern,
2198                                            getCurFPFeatures().isFPConstrained(),
2199                                            false, Type->isFunctionProtoType());
2200   New->setImplicit();
2201   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2202 
2203   // Create Decl objects for each parameter, adding them to the
2204   // FunctionDecl.
2205   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2206     SmallVector<ParmVarDecl *, 16> Params;
2207     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2208       ParmVarDecl *parm = ParmVarDecl::Create(
2209           Context, New, SourceLocation(), SourceLocation(), nullptr,
2210           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2211       parm->setScopeInfo(0, i);
2212       Params.push_back(parm);
2213     }
2214     New->setParams(Params);
2215   }
2216 
2217   AddKnownFunctionAttributes(New);
2218   return New;
2219 }
2220 
2221 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2222 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2223 /// if we're creating this built-in in anticipation of redeclaring the
2224 /// built-in.
2225 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2226                                      Scope *S, bool ForRedeclaration,
2227                                      SourceLocation Loc) {
2228   LookupNecessaryTypesForBuiltin(S, ID);
2229 
2230   ASTContext::GetBuiltinTypeError Error;
2231   QualType R = Context.GetBuiltinType(ID, Error);
2232   if (Error) {
2233     if (!ForRedeclaration)
2234       return nullptr;
2235 
2236     // If we have a builtin without an associated type we should not emit a
2237     // warning when we were not able to find a type for it.
2238     if (Error == ASTContext::GE_Missing_type ||
2239         Context.BuiltinInfo.allowTypeMismatch(ID))
2240       return nullptr;
2241 
2242     // If we could not find a type for setjmp it is because the jmp_buf type was
2243     // not defined prior to the setjmp declaration.
2244     if (Error == ASTContext::GE_Missing_setjmp) {
2245       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2246           << Context.BuiltinInfo.getName(ID);
2247       return nullptr;
2248     }
2249 
2250     // Generally, we emit a warning that the declaration requires the
2251     // appropriate header.
2252     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2253         << getHeaderName(Context.BuiltinInfo, ID, Error)
2254         << Context.BuiltinInfo.getName(ID);
2255     return nullptr;
2256   }
2257 
2258   if (!ForRedeclaration &&
2259       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2260        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2261     Diag(Loc, diag::ext_implicit_lib_function_decl)
2262         << Context.BuiltinInfo.getName(ID) << R;
2263     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2264       Diag(Loc, diag::note_include_header_or_declare)
2265           << Header << Context.BuiltinInfo.getName(ID);
2266   }
2267 
2268   if (R.isNull())
2269     return nullptr;
2270 
2271   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2272   RegisterLocallyScopedExternCDecl(New, S);
2273 
2274   // TUScope is the translation-unit scope to insert this function into.
2275   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2276   // relate Scopes to DeclContexts, and probably eliminate CurContext
2277   // entirely, but we're not there yet.
2278   DeclContext *SavedContext = CurContext;
2279   CurContext = New->getDeclContext();
2280   PushOnScopeChains(New, TUScope);
2281   CurContext = SavedContext;
2282   return New;
2283 }
2284 
2285 /// Typedef declarations don't have linkage, but they still denote the same
2286 /// entity if their types are the same.
2287 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2288 /// isSameEntity.
2289 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2290                                                      TypedefNameDecl *Decl,
2291                                                      LookupResult &Previous) {
2292   // This is only interesting when modules are enabled.
2293   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2294     return;
2295 
2296   // Empty sets are uninteresting.
2297   if (Previous.empty())
2298     return;
2299 
2300   LookupResult::Filter Filter = Previous.makeFilter();
2301   while (Filter.hasNext()) {
2302     NamedDecl *Old = Filter.next();
2303 
2304     // Non-hidden declarations are never ignored.
2305     if (S.isVisible(Old))
2306       continue;
2307 
2308     // Declarations of the same entity are not ignored, even if they have
2309     // different linkages.
2310     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2311       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2312                                 Decl->getUnderlyingType()))
2313         continue;
2314 
2315       // If both declarations give a tag declaration a typedef name for linkage
2316       // purposes, then they declare the same entity.
2317       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2318           Decl->getAnonDeclWithTypedefName())
2319         continue;
2320     }
2321 
2322     Filter.erase();
2323   }
2324 
2325   Filter.done();
2326 }
2327 
2328 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2329   QualType OldType;
2330   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2331     OldType = OldTypedef->getUnderlyingType();
2332   else
2333     OldType = Context.getTypeDeclType(Old);
2334   QualType NewType = New->getUnderlyingType();
2335 
2336   if (NewType->isVariablyModifiedType()) {
2337     // Must not redefine a typedef with a variably-modified type.
2338     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2339     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2340       << Kind << NewType;
2341     if (Old->getLocation().isValid())
2342       notePreviousDefinition(Old, New->getLocation());
2343     New->setInvalidDecl();
2344     return true;
2345   }
2346 
2347   if (OldType != NewType &&
2348       !OldType->isDependentType() &&
2349       !NewType->isDependentType() &&
2350       !Context.hasSameType(OldType, NewType)) {
2351     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2352     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2353       << Kind << NewType << OldType;
2354     if (Old->getLocation().isValid())
2355       notePreviousDefinition(Old, New->getLocation());
2356     New->setInvalidDecl();
2357     return true;
2358   }
2359   return false;
2360 }
2361 
2362 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2363 /// same name and scope as a previous declaration 'Old'.  Figure out
2364 /// how to resolve this situation, merging decls or emitting
2365 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2366 ///
2367 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2368                                 LookupResult &OldDecls) {
2369   // If the new decl is known invalid already, don't bother doing any
2370   // merging checks.
2371   if (New->isInvalidDecl()) return;
2372 
2373   // Allow multiple definitions for ObjC built-in typedefs.
2374   // FIXME: Verify the underlying types are equivalent!
2375   if (getLangOpts().ObjC) {
2376     const IdentifierInfo *TypeID = New->getIdentifier();
2377     switch (TypeID->getLength()) {
2378     default: break;
2379     case 2:
2380       {
2381         if (!TypeID->isStr("id"))
2382           break;
2383         QualType T = New->getUnderlyingType();
2384         if (!T->isPointerType())
2385           break;
2386         if (!T->isVoidPointerType()) {
2387           QualType PT = T->castAs<PointerType>()->getPointeeType();
2388           if (!PT->isStructureType())
2389             break;
2390         }
2391         Context.setObjCIdRedefinitionType(T);
2392         // Install the built-in type for 'id', ignoring the current definition.
2393         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2394         return;
2395       }
2396     case 5:
2397       if (!TypeID->isStr("Class"))
2398         break;
2399       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2400       // Install the built-in type for 'Class', ignoring the current definition.
2401       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2402       return;
2403     case 3:
2404       if (!TypeID->isStr("SEL"))
2405         break;
2406       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2407       // Install the built-in type for 'SEL', ignoring the current definition.
2408       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2409       return;
2410     }
2411     // Fall through - the typedef name was not a builtin type.
2412   }
2413 
2414   // Verify the old decl was also a type.
2415   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2416   if (!Old) {
2417     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2418       << New->getDeclName();
2419 
2420     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2421     if (OldD->getLocation().isValid())
2422       notePreviousDefinition(OldD, New->getLocation());
2423 
2424     return New->setInvalidDecl();
2425   }
2426 
2427   // If the old declaration is invalid, just give up here.
2428   if (Old->isInvalidDecl())
2429     return New->setInvalidDecl();
2430 
2431   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2432     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2433     auto *NewTag = New->getAnonDeclWithTypedefName();
2434     NamedDecl *Hidden = nullptr;
2435     if (OldTag && NewTag &&
2436         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2437         !hasVisibleDefinition(OldTag, &Hidden)) {
2438       // There is a definition of this tag, but it is not visible. Use it
2439       // instead of our tag.
2440       New->setTypeForDecl(OldTD->getTypeForDecl());
2441       if (OldTD->isModed())
2442         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2443                                     OldTD->getUnderlyingType());
2444       else
2445         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2446 
2447       // Make the old tag definition visible.
2448       makeMergedDefinitionVisible(Hidden);
2449 
2450       // If this was an unscoped enumeration, yank all of its enumerators
2451       // out of the scope.
2452       if (isa<EnumDecl>(NewTag)) {
2453         Scope *EnumScope = getNonFieldDeclScope(S);
2454         for (auto *D : NewTag->decls()) {
2455           auto *ED = cast<EnumConstantDecl>(D);
2456           assert(EnumScope->isDeclScope(ED));
2457           EnumScope->RemoveDecl(ED);
2458           IdResolver.RemoveDecl(ED);
2459           ED->getLexicalDeclContext()->removeDecl(ED);
2460         }
2461       }
2462     }
2463   }
2464 
2465   // If the typedef types are not identical, reject them in all languages and
2466   // with any extensions enabled.
2467   if (isIncompatibleTypedef(Old, New))
2468     return;
2469 
2470   // The types match.  Link up the redeclaration chain and merge attributes if
2471   // the old declaration was a typedef.
2472   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2473     New->setPreviousDecl(Typedef);
2474     mergeDeclAttributes(New, Old);
2475   }
2476 
2477   if (getLangOpts().MicrosoftExt)
2478     return;
2479 
2480   if (getLangOpts().CPlusPlus) {
2481     // C++ [dcl.typedef]p2:
2482     //   In a given non-class scope, a typedef specifier can be used to
2483     //   redefine the name of any type declared in that scope to refer
2484     //   to the type to which it already refers.
2485     if (!isa<CXXRecordDecl>(CurContext))
2486       return;
2487 
2488     // C++0x [dcl.typedef]p4:
2489     //   In a given class scope, a typedef specifier can be used to redefine
2490     //   any class-name declared in that scope that is not also a typedef-name
2491     //   to refer to the type to which it already refers.
2492     //
2493     // This wording came in via DR424, which was a correction to the
2494     // wording in DR56, which accidentally banned code like:
2495     //
2496     //   struct S {
2497     //     typedef struct A { } A;
2498     //   };
2499     //
2500     // in the C++03 standard. We implement the C++0x semantics, which
2501     // allow the above but disallow
2502     //
2503     //   struct S {
2504     //     typedef int I;
2505     //     typedef int I;
2506     //   };
2507     //
2508     // since that was the intent of DR56.
2509     if (!isa<TypedefNameDecl>(Old))
2510       return;
2511 
2512     Diag(New->getLocation(), diag::err_redefinition)
2513       << New->getDeclName();
2514     notePreviousDefinition(Old, New->getLocation());
2515     return New->setInvalidDecl();
2516   }
2517 
2518   // Modules always permit redefinition of typedefs, as does C11.
2519   if (getLangOpts().Modules || getLangOpts().C11)
2520     return;
2521 
2522   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2523   // is normally mapped to an error, but can be controlled with
2524   // -Wtypedef-redefinition.  If either the original or the redefinition is
2525   // in a system header, don't emit this for compatibility with GCC.
2526   if (getDiagnostics().getSuppressSystemWarnings() &&
2527       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2528       (Old->isImplicit() ||
2529        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2530        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2531     return;
2532 
2533   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2534     << New->getDeclName();
2535   notePreviousDefinition(Old, New->getLocation());
2536 }
2537 
2538 /// DeclhasAttr - returns true if decl Declaration already has the target
2539 /// attribute.
2540 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2541   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2542   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2543   for (const auto *i : D->attrs())
2544     if (i->getKind() == A->getKind()) {
2545       if (Ann) {
2546         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2547           return true;
2548         continue;
2549       }
2550       // FIXME: Don't hardcode this check
2551       if (OA && isa<OwnershipAttr>(i))
2552         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2553       return true;
2554     }
2555 
2556   return false;
2557 }
2558 
2559 static bool isAttributeTargetADefinition(Decl *D) {
2560   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2561     return VD->isThisDeclarationADefinition();
2562   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2563     return TD->isCompleteDefinition() || TD->isBeingDefined();
2564   return true;
2565 }
2566 
2567 /// Merge alignment attributes from \p Old to \p New, taking into account the
2568 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2569 ///
2570 /// \return \c true if any attributes were added to \p New.
2571 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2572   // Look for alignas attributes on Old, and pick out whichever attribute
2573   // specifies the strictest alignment requirement.
2574   AlignedAttr *OldAlignasAttr = nullptr;
2575   AlignedAttr *OldStrictestAlignAttr = nullptr;
2576   unsigned OldAlign = 0;
2577   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2578     // FIXME: We have no way of representing inherited dependent alignments
2579     // in a case like:
2580     //   template<int A, int B> struct alignas(A) X;
2581     //   template<int A, int B> struct alignas(B) X {};
2582     // For now, we just ignore any alignas attributes which are not on the
2583     // definition in such a case.
2584     if (I->isAlignmentDependent())
2585       return false;
2586 
2587     if (I->isAlignas())
2588       OldAlignasAttr = I;
2589 
2590     unsigned Align = I->getAlignment(S.Context);
2591     if (Align > OldAlign) {
2592       OldAlign = Align;
2593       OldStrictestAlignAttr = I;
2594     }
2595   }
2596 
2597   // Look for alignas attributes on New.
2598   AlignedAttr *NewAlignasAttr = nullptr;
2599   unsigned NewAlign = 0;
2600   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2601     if (I->isAlignmentDependent())
2602       return false;
2603 
2604     if (I->isAlignas())
2605       NewAlignasAttr = I;
2606 
2607     unsigned Align = I->getAlignment(S.Context);
2608     if (Align > NewAlign)
2609       NewAlign = Align;
2610   }
2611 
2612   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2613     // Both declarations have 'alignas' attributes. We require them to match.
2614     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2615     // fall short. (If two declarations both have alignas, they must both match
2616     // every definition, and so must match each other if there is a definition.)
2617 
2618     // If either declaration only contains 'alignas(0)' specifiers, then it
2619     // specifies the natural alignment for the type.
2620     if (OldAlign == 0 || NewAlign == 0) {
2621       QualType Ty;
2622       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2623         Ty = VD->getType();
2624       else
2625         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2626 
2627       if (OldAlign == 0)
2628         OldAlign = S.Context.getTypeAlign(Ty);
2629       if (NewAlign == 0)
2630         NewAlign = S.Context.getTypeAlign(Ty);
2631     }
2632 
2633     if (OldAlign != NewAlign) {
2634       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2635         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2636         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2637       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2638     }
2639   }
2640 
2641   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2642     // C++11 [dcl.align]p6:
2643     //   if any declaration of an entity has an alignment-specifier,
2644     //   every defining declaration of that entity shall specify an
2645     //   equivalent alignment.
2646     // C11 6.7.5/7:
2647     //   If the definition of an object does not have an alignment
2648     //   specifier, any other declaration of that object shall also
2649     //   have no alignment specifier.
2650     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2651       << OldAlignasAttr;
2652     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2653       << OldAlignasAttr;
2654   }
2655 
2656   bool AnyAdded = false;
2657 
2658   // Ensure we have an attribute representing the strictest alignment.
2659   if (OldAlign > NewAlign) {
2660     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2661     Clone->setInherited(true);
2662     New->addAttr(Clone);
2663     AnyAdded = true;
2664   }
2665 
2666   // Ensure we have an alignas attribute if the old declaration had one.
2667   if (OldAlignasAttr && !NewAlignasAttr &&
2668       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2669     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2670     Clone->setInherited(true);
2671     New->addAttr(Clone);
2672     AnyAdded = true;
2673   }
2674 
2675   return AnyAdded;
2676 }
2677 
2678 #define WANT_DECL_MERGE_LOGIC
2679 #include "clang/Sema/AttrParsedAttrImpl.inc"
2680 #undef WANT_DECL_MERGE_LOGIC
2681 
2682 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2683                                const InheritableAttr *Attr,
2684                                Sema::AvailabilityMergeKind AMK) {
2685   // Diagnose any mutual exclusions between the attribute that we want to add
2686   // and attributes that already exist on the declaration.
2687   if (!DiagnoseMutualExclusions(S, D, Attr))
2688     return false;
2689 
2690   // This function copies an attribute Attr from a previous declaration to the
2691   // new declaration D if the new declaration doesn't itself have that attribute
2692   // yet or if that attribute allows duplicates.
2693   // If you're adding a new attribute that requires logic different from
2694   // "use explicit attribute on decl if present, else use attribute from
2695   // previous decl", for example if the attribute needs to be consistent
2696   // between redeclarations, you need to call a custom merge function here.
2697   InheritableAttr *NewAttr = nullptr;
2698   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2699     NewAttr = S.mergeAvailabilityAttr(
2700         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2701         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2702         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2703         AA->getPriority());
2704   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2705     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2706   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2707     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2708   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2709     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2710   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2711     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2712   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2713     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2714   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2715     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2716                                 FA->getFirstArg());
2717   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2718     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2719   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2720     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2721   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2722     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2723                                        IA->getInheritanceModel());
2724   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2725     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2726                                       &S.Context.Idents.get(AA->getSpelling()));
2727   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2728            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2729             isa<CUDAGlobalAttr>(Attr))) {
2730     // CUDA target attributes are part of function signature for
2731     // overloading purposes and must not be merged.
2732     return false;
2733   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2734     NewAttr = S.mergeMinSizeAttr(D, *MA);
2735   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2736     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2737   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2738     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2739   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2740     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2741   else if (isa<AlignedAttr>(Attr))
2742     // AlignedAttrs are handled separately, because we need to handle all
2743     // such attributes on a declaration at the same time.
2744     NewAttr = nullptr;
2745   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2746            (AMK == Sema::AMK_Override ||
2747             AMK == Sema::AMK_ProtocolImplementation ||
2748             AMK == Sema::AMK_OptionalProtocolImplementation))
2749     NewAttr = nullptr;
2750   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2751     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2752   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2753     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2754   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2755     NewAttr = S.mergeImportNameAttr(D, *INA);
2756   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2757     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2758   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2759     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2760   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2761     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2762   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2763     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2764 
2765   if (NewAttr) {
2766     NewAttr->setInherited(true);
2767     D->addAttr(NewAttr);
2768     if (isa<MSInheritanceAttr>(NewAttr))
2769       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2770     return true;
2771   }
2772 
2773   return false;
2774 }
2775 
2776 static const NamedDecl *getDefinition(const Decl *D) {
2777   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2778     return TD->getDefinition();
2779   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2780     const VarDecl *Def = VD->getDefinition();
2781     if (Def)
2782       return Def;
2783     return VD->getActingDefinition();
2784   }
2785   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2786     const FunctionDecl *Def = nullptr;
2787     if (FD->isDefined(Def, true))
2788       return Def;
2789   }
2790   return nullptr;
2791 }
2792 
2793 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2794   for (const auto *Attribute : D->attrs())
2795     if (Attribute->getKind() == Kind)
2796       return true;
2797   return false;
2798 }
2799 
2800 /// checkNewAttributesAfterDef - If we already have a definition, check that
2801 /// there are no new attributes in this declaration.
2802 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2803   if (!New->hasAttrs())
2804     return;
2805 
2806   const NamedDecl *Def = getDefinition(Old);
2807   if (!Def || Def == New)
2808     return;
2809 
2810   AttrVec &NewAttributes = New->getAttrs();
2811   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2812     const Attr *NewAttribute = NewAttributes[I];
2813 
2814     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2815       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2816         Sema::SkipBodyInfo SkipBody;
2817         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2818 
2819         // If we're skipping this definition, drop the "alias" attribute.
2820         if (SkipBody.ShouldSkip) {
2821           NewAttributes.erase(NewAttributes.begin() + I);
2822           --E;
2823           continue;
2824         }
2825       } else {
2826         VarDecl *VD = cast<VarDecl>(New);
2827         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2828                                 VarDecl::TentativeDefinition
2829                             ? diag::err_alias_after_tentative
2830                             : diag::err_redefinition;
2831         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2832         if (Diag == diag::err_redefinition)
2833           S.notePreviousDefinition(Def, VD->getLocation());
2834         else
2835           S.Diag(Def->getLocation(), diag::note_previous_definition);
2836         VD->setInvalidDecl();
2837       }
2838       ++I;
2839       continue;
2840     }
2841 
2842     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2843       // Tentative definitions are only interesting for the alias check above.
2844       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2845         ++I;
2846         continue;
2847       }
2848     }
2849 
2850     if (hasAttribute(Def, NewAttribute->getKind())) {
2851       ++I;
2852       continue; // regular attr merging will take care of validating this.
2853     }
2854 
2855     if (isa<C11NoReturnAttr>(NewAttribute)) {
2856       // C's _Noreturn is allowed to be added to a function after it is defined.
2857       ++I;
2858       continue;
2859     } else if (isa<UuidAttr>(NewAttribute)) {
2860       // msvc will allow a subsequent definition to add an uuid to a class
2861       ++I;
2862       continue;
2863     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2864       if (AA->isAlignas()) {
2865         // C++11 [dcl.align]p6:
2866         //   if any declaration of an entity has an alignment-specifier,
2867         //   every defining declaration of that entity shall specify an
2868         //   equivalent alignment.
2869         // C11 6.7.5/7:
2870         //   If the definition of an object does not have an alignment
2871         //   specifier, any other declaration of that object shall also
2872         //   have no alignment specifier.
2873         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2874           << AA;
2875         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2876           << AA;
2877         NewAttributes.erase(NewAttributes.begin() + I);
2878         --E;
2879         continue;
2880       }
2881     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2882       // If there is a C definition followed by a redeclaration with this
2883       // attribute then there are two different definitions. In C++, prefer the
2884       // standard diagnostics.
2885       if (!S.getLangOpts().CPlusPlus) {
2886         S.Diag(NewAttribute->getLocation(),
2887                diag::err_loader_uninitialized_redeclaration);
2888         S.Diag(Def->getLocation(), diag::note_previous_definition);
2889         NewAttributes.erase(NewAttributes.begin() + I);
2890         --E;
2891         continue;
2892       }
2893     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2894                cast<VarDecl>(New)->isInline() &&
2895                !cast<VarDecl>(New)->isInlineSpecified()) {
2896       // Don't warn about applying selectany to implicitly inline variables.
2897       // Older compilers and language modes would require the use of selectany
2898       // to make such variables inline, and it would have no effect if we
2899       // honored it.
2900       ++I;
2901       continue;
2902     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2903       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2904       // declarations after defintions.
2905       ++I;
2906       continue;
2907     }
2908 
2909     S.Diag(NewAttribute->getLocation(),
2910            diag::warn_attribute_precede_definition);
2911     S.Diag(Def->getLocation(), diag::note_previous_definition);
2912     NewAttributes.erase(NewAttributes.begin() + I);
2913     --E;
2914   }
2915 }
2916 
2917 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2918                                      const ConstInitAttr *CIAttr,
2919                                      bool AttrBeforeInit) {
2920   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2921 
2922   // Figure out a good way to write this specifier on the old declaration.
2923   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2924   // enough of the attribute list spelling information to extract that without
2925   // heroics.
2926   std::string SuitableSpelling;
2927   if (S.getLangOpts().CPlusPlus20)
2928     SuitableSpelling = std::string(
2929         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2930   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2931     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2932         InsertLoc, {tok::l_square, tok::l_square,
2933                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2934                     S.PP.getIdentifierInfo("require_constant_initialization"),
2935                     tok::r_square, tok::r_square}));
2936   if (SuitableSpelling.empty())
2937     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2938         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2939                     S.PP.getIdentifierInfo("require_constant_initialization"),
2940                     tok::r_paren, tok::r_paren}));
2941   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2942     SuitableSpelling = "constinit";
2943   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2944     SuitableSpelling = "[[clang::require_constant_initialization]]";
2945   if (SuitableSpelling.empty())
2946     SuitableSpelling = "__attribute__((require_constant_initialization))";
2947   SuitableSpelling += " ";
2948 
2949   if (AttrBeforeInit) {
2950     // extern constinit int a;
2951     // int a = 0; // error (missing 'constinit'), accepted as extension
2952     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2953     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2954         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2955     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2956   } else {
2957     // int a = 0;
2958     // constinit extern int a; // error (missing 'constinit')
2959     S.Diag(CIAttr->getLocation(),
2960            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2961                                  : diag::warn_require_const_init_added_too_late)
2962         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2963     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2964         << CIAttr->isConstinit()
2965         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2966   }
2967 }
2968 
2969 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2970 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2971                                AvailabilityMergeKind AMK) {
2972   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2973     UsedAttr *NewAttr = OldAttr->clone(Context);
2974     NewAttr->setInherited(true);
2975     New->addAttr(NewAttr);
2976   }
2977   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2978     RetainAttr *NewAttr = OldAttr->clone(Context);
2979     NewAttr->setInherited(true);
2980     New->addAttr(NewAttr);
2981   }
2982 
2983   if (!Old->hasAttrs() && !New->hasAttrs())
2984     return;
2985 
2986   // [dcl.constinit]p1:
2987   //   If the [constinit] specifier is applied to any declaration of a
2988   //   variable, it shall be applied to the initializing declaration.
2989   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2990   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2991   if (bool(OldConstInit) != bool(NewConstInit)) {
2992     const auto *OldVD = cast<VarDecl>(Old);
2993     auto *NewVD = cast<VarDecl>(New);
2994 
2995     // Find the initializing declaration. Note that we might not have linked
2996     // the new declaration into the redeclaration chain yet.
2997     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2998     if (!InitDecl &&
2999         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3000       InitDecl = NewVD;
3001 
3002     if (InitDecl == NewVD) {
3003       // This is the initializing declaration. If it would inherit 'constinit',
3004       // that's ill-formed. (Note that we do not apply this to the attribute
3005       // form).
3006       if (OldConstInit && OldConstInit->isConstinit())
3007         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3008                                  /*AttrBeforeInit=*/true);
3009     } else if (NewConstInit) {
3010       // This is the first time we've been told that this declaration should
3011       // have a constant initializer. If we already saw the initializing
3012       // declaration, this is too late.
3013       if (InitDecl && InitDecl != NewVD) {
3014         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3015                                  /*AttrBeforeInit=*/false);
3016         NewVD->dropAttr<ConstInitAttr>();
3017       }
3018     }
3019   }
3020 
3021   // Attributes declared post-definition are currently ignored.
3022   checkNewAttributesAfterDef(*this, New, Old);
3023 
3024   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3025     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3026       if (!OldA->isEquivalent(NewA)) {
3027         // This redeclaration changes __asm__ label.
3028         Diag(New->getLocation(), diag::err_different_asm_label);
3029         Diag(OldA->getLocation(), diag::note_previous_declaration);
3030       }
3031     } else if (Old->isUsed()) {
3032       // This redeclaration adds an __asm__ label to a declaration that has
3033       // already been ODR-used.
3034       Diag(New->getLocation(), diag::err_late_asm_label_name)
3035         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3036     }
3037   }
3038 
3039   // Re-declaration cannot add abi_tag's.
3040   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3041     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3042       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3043         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3044           Diag(NewAbiTagAttr->getLocation(),
3045                diag::err_new_abi_tag_on_redeclaration)
3046               << NewTag;
3047           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3048         }
3049       }
3050     } else {
3051       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3052       Diag(Old->getLocation(), diag::note_previous_declaration);
3053     }
3054   }
3055 
3056   // This redeclaration adds a section attribute.
3057   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3058     if (auto *VD = dyn_cast<VarDecl>(New)) {
3059       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3060         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3061         Diag(Old->getLocation(), diag::note_previous_declaration);
3062       }
3063     }
3064   }
3065 
3066   // Redeclaration adds code-seg attribute.
3067   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3068   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3069       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3070     Diag(New->getLocation(), diag::warn_mismatched_section)
3071          << 0 /*codeseg*/;
3072     Diag(Old->getLocation(), diag::note_previous_declaration);
3073   }
3074 
3075   if (!Old->hasAttrs())
3076     return;
3077 
3078   bool foundAny = New->hasAttrs();
3079 
3080   // Ensure that any moving of objects within the allocated map is done before
3081   // we process them.
3082   if (!foundAny) New->setAttrs(AttrVec());
3083 
3084   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3085     // Ignore deprecated/unavailable/availability attributes if requested.
3086     AvailabilityMergeKind LocalAMK = AMK_None;
3087     if (isa<DeprecatedAttr>(I) ||
3088         isa<UnavailableAttr>(I) ||
3089         isa<AvailabilityAttr>(I)) {
3090       switch (AMK) {
3091       case AMK_None:
3092         continue;
3093 
3094       case AMK_Redeclaration:
3095       case AMK_Override:
3096       case AMK_ProtocolImplementation:
3097       case AMK_OptionalProtocolImplementation:
3098         LocalAMK = AMK;
3099         break;
3100       }
3101     }
3102 
3103     // Already handled.
3104     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3105       continue;
3106 
3107     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3108       foundAny = true;
3109   }
3110 
3111   if (mergeAlignedAttrs(*this, New, Old))
3112     foundAny = true;
3113 
3114   if (!foundAny) New->dropAttrs();
3115 }
3116 
3117 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3118 /// to the new one.
3119 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3120                                      const ParmVarDecl *oldDecl,
3121                                      Sema &S) {
3122   // C++11 [dcl.attr.depend]p2:
3123   //   The first declaration of a function shall specify the
3124   //   carries_dependency attribute for its declarator-id if any declaration
3125   //   of the function specifies the carries_dependency attribute.
3126   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3127   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3128     S.Diag(CDA->getLocation(),
3129            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3130     // Find the first declaration of the parameter.
3131     // FIXME: Should we build redeclaration chains for function parameters?
3132     const FunctionDecl *FirstFD =
3133       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3134     const ParmVarDecl *FirstVD =
3135       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3136     S.Diag(FirstVD->getLocation(),
3137            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3138   }
3139 
3140   if (!oldDecl->hasAttrs())
3141     return;
3142 
3143   bool foundAny = newDecl->hasAttrs();
3144 
3145   // Ensure that any moving of objects within the allocated map is
3146   // done before we process them.
3147   if (!foundAny) newDecl->setAttrs(AttrVec());
3148 
3149   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3150     if (!DeclHasAttr(newDecl, I)) {
3151       InheritableAttr *newAttr =
3152         cast<InheritableParamAttr>(I->clone(S.Context));
3153       newAttr->setInherited(true);
3154       newDecl->addAttr(newAttr);
3155       foundAny = true;
3156     }
3157   }
3158 
3159   if (!foundAny) newDecl->dropAttrs();
3160 }
3161 
3162 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3163                                 const ParmVarDecl *OldParam,
3164                                 Sema &S) {
3165   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3166     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3167       if (*Oldnullability != *Newnullability) {
3168         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3169           << DiagNullabilityKind(
3170                *Newnullability,
3171                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3172                 != 0))
3173           << DiagNullabilityKind(
3174                *Oldnullability,
3175                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3176                 != 0));
3177         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3178       }
3179     } else {
3180       QualType NewT = NewParam->getType();
3181       NewT = S.Context.getAttributedType(
3182                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3183                          NewT, NewT);
3184       NewParam->setType(NewT);
3185     }
3186   }
3187 }
3188 
3189 namespace {
3190 
3191 /// Used in MergeFunctionDecl to keep track of function parameters in
3192 /// C.
3193 struct GNUCompatibleParamWarning {
3194   ParmVarDecl *OldParm;
3195   ParmVarDecl *NewParm;
3196   QualType PromotedType;
3197 };
3198 
3199 } // end anonymous namespace
3200 
3201 // Determine whether the previous declaration was a definition, implicit
3202 // declaration, or a declaration.
3203 template <typename T>
3204 static std::pair<diag::kind, SourceLocation>
3205 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3206   diag::kind PrevDiag;
3207   SourceLocation OldLocation = Old->getLocation();
3208   if (Old->isThisDeclarationADefinition())
3209     PrevDiag = diag::note_previous_definition;
3210   else if (Old->isImplicit()) {
3211     PrevDiag = diag::note_previous_implicit_declaration;
3212     if (OldLocation.isInvalid())
3213       OldLocation = New->getLocation();
3214   } else
3215     PrevDiag = diag::note_previous_declaration;
3216   return std::make_pair(PrevDiag, OldLocation);
3217 }
3218 
3219 /// canRedefineFunction - checks if a function can be redefined. Currently,
3220 /// only extern inline functions can be redefined, and even then only in
3221 /// GNU89 mode.
3222 static bool canRedefineFunction(const FunctionDecl *FD,
3223                                 const LangOptions& LangOpts) {
3224   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3225           !LangOpts.CPlusPlus &&
3226           FD->isInlineSpecified() &&
3227           FD->getStorageClass() == SC_Extern);
3228 }
3229 
3230 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3231   const AttributedType *AT = T->getAs<AttributedType>();
3232   while (AT && !AT->isCallingConv())
3233     AT = AT->getModifiedType()->getAs<AttributedType>();
3234   return AT;
3235 }
3236 
3237 template <typename T>
3238 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3239   const DeclContext *DC = Old->getDeclContext();
3240   if (DC->isRecord())
3241     return false;
3242 
3243   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3244   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3245     return true;
3246   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3247     return true;
3248   return false;
3249 }
3250 
3251 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3252 static bool isExternC(VarTemplateDecl *) { return false; }
3253 static bool isExternC(FunctionTemplateDecl *) { return false; }
3254 
3255 /// Check whether a redeclaration of an entity introduced by a
3256 /// using-declaration is valid, given that we know it's not an overload
3257 /// (nor a hidden tag declaration).
3258 template<typename ExpectedDecl>
3259 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3260                                    ExpectedDecl *New) {
3261   // C++11 [basic.scope.declarative]p4:
3262   //   Given a set of declarations in a single declarative region, each of
3263   //   which specifies the same unqualified name,
3264   //   -- they shall all refer to the same entity, or all refer to functions
3265   //      and function templates; or
3266   //   -- exactly one declaration shall declare a class name or enumeration
3267   //      name that is not a typedef name and the other declarations shall all
3268   //      refer to the same variable or enumerator, or all refer to functions
3269   //      and function templates; in this case the class name or enumeration
3270   //      name is hidden (3.3.10).
3271 
3272   // C++11 [namespace.udecl]p14:
3273   //   If a function declaration in namespace scope or block scope has the
3274   //   same name and the same parameter-type-list as a function introduced
3275   //   by a using-declaration, and the declarations do not declare the same
3276   //   function, the program is ill-formed.
3277 
3278   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3279   if (Old &&
3280       !Old->getDeclContext()->getRedeclContext()->Equals(
3281           New->getDeclContext()->getRedeclContext()) &&
3282       !(isExternC(Old) && isExternC(New)))
3283     Old = nullptr;
3284 
3285   if (!Old) {
3286     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3287     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3288     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3289     return true;
3290   }
3291   return false;
3292 }
3293 
3294 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3295                                             const FunctionDecl *B) {
3296   assert(A->getNumParams() == B->getNumParams());
3297 
3298   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3299     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3300     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3301     if (AttrA == AttrB)
3302       return true;
3303     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3304            AttrA->isDynamic() == AttrB->isDynamic();
3305   };
3306 
3307   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3308 }
3309 
3310 /// If necessary, adjust the semantic declaration context for a qualified
3311 /// declaration to name the correct inline namespace within the qualifier.
3312 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3313                                                DeclaratorDecl *OldD) {
3314   // The only case where we need to update the DeclContext is when
3315   // redeclaration lookup for a qualified name finds a declaration
3316   // in an inline namespace within the context named by the qualifier:
3317   //
3318   //   inline namespace N { int f(); }
3319   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3320   //
3321   // For unqualified declarations, the semantic context *can* change
3322   // along the redeclaration chain (for local extern declarations,
3323   // extern "C" declarations, and friend declarations in particular).
3324   if (!NewD->getQualifier())
3325     return;
3326 
3327   // NewD is probably already in the right context.
3328   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3329   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3330   if (NamedDC->Equals(SemaDC))
3331     return;
3332 
3333   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3334           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3335          "unexpected context for redeclaration");
3336 
3337   auto *LexDC = NewD->getLexicalDeclContext();
3338   auto FixSemaDC = [=](NamedDecl *D) {
3339     if (!D)
3340       return;
3341     D->setDeclContext(SemaDC);
3342     D->setLexicalDeclContext(LexDC);
3343   };
3344 
3345   FixSemaDC(NewD);
3346   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3347     FixSemaDC(FD->getDescribedFunctionTemplate());
3348   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3349     FixSemaDC(VD->getDescribedVarTemplate());
3350 }
3351 
3352 /// MergeFunctionDecl - We just parsed a function 'New' from
3353 /// declarator D which has the same name and scope as a previous
3354 /// declaration 'Old'.  Figure out how to resolve this situation,
3355 /// merging decls or emitting diagnostics as appropriate.
3356 ///
3357 /// In C++, New and Old must be declarations that are not
3358 /// overloaded. Use IsOverload to determine whether New and Old are
3359 /// overloaded, and to select the Old declaration that New should be
3360 /// merged with.
3361 ///
3362 /// Returns true if there was an error, false otherwise.
3363 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3364                              Scope *S, bool MergeTypeWithOld) {
3365   // Verify the old decl was also a function.
3366   FunctionDecl *Old = OldD->getAsFunction();
3367   if (!Old) {
3368     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3369       if (New->getFriendObjectKind()) {
3370         Diag(New->getLocation(), diag::err_using_decl_friend);
3371         Diag(Shadow->getTargetDecl()->getLocation(),
3372              diag::note_using_decl_target);
3373         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3374             << 0;
3375         return true;
3376       }
3377 
3378       // Check whether the two declarations might declare the same function or
3379       // function template.
3380       if (FunctionTemplateDecl *NewTemplate =
3381               New->getDescribedFunctionTemplate()) {
3382         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3383                                                          NewTemplate))
3384           return true;
3385         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3386                          ->getAsFunction();
3387       } else {
3388         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3389           return true;
3390         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3391       }
3392     } else {
3393       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3394         << New->getDeclName();
3395       notePreviousDefinition(OldD, New->getLocation());
3396       return true;
3397     }
3398   }
3399 
3400   // If the old declaration was found in an inline namespace and the new
3401   // declaration was qualified, update the DeclContext to match.
3402   adjustDeclContextForDeclaratorDecl(New, Old);
3403 
3404   // If the old declaration is invalid, just give up here.
3405   if (Old->isInvalidDecl())
3406     return true;
3407 
3408   // Disallow redeclaration of some builtins.
3409   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3410     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3411     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3412         << Old << Old->getType();
3413     return true;
3414   }
3415 
3416   diag::kind PrevDiag;
3417   SourceLocation OldLocation;
3418   std::tie(PrevDiag, OldLocation) =
3419       getNoteDiagForInvalidRedeclaration(Old, New);
3420 
3421   // Don't complain about this if we're in GNU89 mode and the old function
3422   // is an extern inline function.
3423   // Don't complain about specializations. They are not supposed to have
3424   // storage classes.
3425   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3426       New->getStorageClass() == SC_Static &&
3427       Old->hasExternalFormalLinkage() &&
3428       !New->getTemplateSpecializationInfo() &&
3429       !canRedefineFunction(Old, getLangOpts())) {
3430     if (getLangOpts().MicrosoftExt) {
3431       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3432       Diag(OldLocation, PrevDiag);
3433     } else {
3434       Diag(New->getLocation(), diag::err_static_non_static) << New;
3435       Diag(OldLocation, PrevDiag);
3436       return true;
3437     }
3438   }
3439 
3440   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3441     if (!Old->hasAttr<InternalLinkageAttr>()) {
3442       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3443           << ILA;
3444       Diag(Old->getLocation(), diag::note_previous_declaration);
3445       New->dropAttr<InternalLinkageAttr>();
3446     }
3447 
3448   if (auto *EA = New->getAttr<ErrorAttr>()) {
3449     if (!Old->hasAttr<ErrorAttr>()) {
3450       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3451       Diag(Old->getLocation(), diag::note_previous_declaration);
3452       New->dropAttr<ErrorAttr>();
3453     }
3454   }
3455 
3456   if (CheckRedeclarationInModule(New, Old))
3457     return true;
3458 
3459   if (!getLangOpts().CPlusPlus) {
3460     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3461     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3462       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3463         << New << OldOvl;
3464 
3465       // Try our best to find a decl that actually has the overloadable
3466       // attribute for the note. In most cases (e.g. programs with only one
3467       // broken declaration/definition), this won't matter.
3468       //
3469       // FIXME: We could do this if we juggled some extra state in
3470       // OverloadableAttr, rather than just removing it.
3471       const Decl *DiagOld = Old;
3472       if (OldOvl) {
3473         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3474           const auto *A = D->getAttr<OverloadableAttr>();
3475           return A && !A->isImplicit();
3476         });
3477         // If we've implicitly added *all* of the overloadable attrs to this
3478         // chain, emitting a "previous redecl" note is pointless.
3479         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3480       }
3481 
3482       if (DiagOld)
3483         Diag(DiagOld->getLocation(),
3484              diag::note_attribute_overloadable_prev_overload)
3485           << OldOvl;
3486 
3487       if (OldOvl)
3488         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3489       else
3490         New->dropAttr<OverloadableAttr>();
3491     }
3492   }
3493 
3494   // If a function is first declared with a calling convention, but is later
3495   // declared or defined without one, all following decls assume the calling
3496   // convention of the first.
3497   //
3498   // It's OK if a function is first declared without a calling convention,
3499   // but is later declared or defined with the default calling convention.
3500   //
3501   // To test if either decl has an explicit calling convention, we look for
3502   // AttributedType sugar nodes on the type as written.  If they are missing or
3503   // were canonicalized away, we assume the calling convention was implicit.
3504   //
3505   // Note also that we DO NOT return at this point, because we still have
3506   // other tests to run.
3507   QualType OldQType = Context.getCanonicalType(Old->getType());
3508   QualType NewQType = Context.getCanonicalType(New->getType());
3509   const FunctionType *OldType = cast<FunctionType>(OldQType);
3510   const FunctionType *NewType = cast<FunctionType>(NewQType);
3511   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3512   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3513   bool RequiresAdjustment = false;
3514 
3515   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3516     FunctionDecl *First = Old->getFirstDecl();
3517     const FunctionType *FT =
3518         First->getType().getCanonicalType()->castAs<FunctionType>();
3519     FunctionType::ExtInfo FI = FT->getExtInfo();
3520     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3521     if (!NewCCExplicit) {
3522       // Inherit the CC from the previous declaration if it was specified
3523       // there but not here.
3524       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3525       RequiresAdjustment = true;
3526     } else if (Old->getBuiltinID()) {
3527       // Builtin attribute isn't propagated to the new one yet at this point,
3528       // so we check if the old one is a builtin.
3529 
3530       // Calling Conventions on a Builtin aren't really useful and setting a
3531       // default calling convention and cdecl'ing some builtin redeclarations is
3532       // common, so warn and ignore the calling convention on the redeclaration.
3533       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3534           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3535           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3536       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3537       RequiresAdjustment = true;
3538     } else {
3539       // Calling conventions aren't compatible, so complain.
3540       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3541       Diag(New->getLocation(), diag::err_cconv_change)
3542         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3543         << !FirstCCExplicit
3544         << (!FirstCCExplicit ? "" :
3545             FunctionType::getNameForCallConv(FI.getCC()));
3546 
3547       // Put the note on the first decl, since it is the one that matters.
3548       Diag(First->getLocation(), diag::note_previous_declaration);
3549       return true;
3550     }
3551   }
3552 
3553   // FIXME: diagnose the other way around?
3554   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3555     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3556     RequiresAdjustment = true;
3557   }
3558 
3559   // Merge regparm attribute.
3560   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3561       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3562     if (NewTypeInfo.getHasRegParm()) {
3563       Diag(New->getLocation(), diag::err_regparm_mismatch)
3564         << NewType->getRegParmType()
3565         << OldType->getRegParmType();
3566       Diag(OldLocation, diag::note_previous_declaration);
3567       return true;
3568     }
3569 
3570     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3571     RequiresAdjustment = true;
3572   }
3573 
3574   // Merge ns_returns_retained attribute.
3575   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3576     if (NewTypeInfo.getProducesResult()) {
3577       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3578           << "'ns_returns_retained'";
3579       Diag(OldLocation, diag::note_previous_declaration);
3580       return true;
3581     }
3582 
3583     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3584     RequiresAdjustment = true;
3585   }
3586 
3587   if (OldTypeInfo.getNoCallerSavedRegs() !=
3588       NewTypeInfo.getNoCallerSavedRegs()) {
3589     if (NewTypeInfo.getNoCallerSavedRegs()) {
3590       AnyX86NoCallerSavedRegistersAttr *Attr =
3591         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3592       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3593       Diag(OldLocation, diag::note_previous_declaration);
3594       return true;
3595     }
3596 
3597     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3598     RequiresAdjustment = true;
3599   }
3600 
3601   if (RequiresAdjustment) {
3602     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3603     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3604     New->setType(QualType(AdjustedType, 0));
3605     NewQType = Context.getCanonicalType(New->getType());
3606   }
3607 
3608   // If this redeclaration makes the function inline, we may need to add it to
3609   // UndefinedButUsed.
3610   if (!Old->isInlined() && New->isInlined() &&
3611       !New->hasAttr<GNUInlineAttr>() &&
3612       !getLangOpts().GNUInline &&
3613       Old->isUsed(false) &&
3614       !Old->isDefined() && !New->isThisDeclarationADefinition())
3615     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3616                                            SourceLocation()));
3617 
3618   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3619   // about it.
3620   if (New->hasAttr<GNUInlineAttr>() &&
3621       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3622     UndefinedButUsed.erase(Old->getCanonicalDecl());
3623   }
3624 
3625   // If pass_object_size params don't match up perfectly, this isn't a valid
3626   // redeclaration.
3627   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3628       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3629     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3630         << New->getDeclName();
3631     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3632     return true;
3633   }
3634 
3635   if (getLangOpts().CPlusPlus) {
3636     // C++1z [over.load]p2
3637     //   Certain function declarations cannot be overloaded:
3638     //     -- Function declarations that differ only in the return type,
3639     //        the exception specification, or both cannot be overloaded.
3640 
3641     // Check the exception specifications match. This may recompute the type of
3642     // both Old and New if it resolved exception specifications, so grab the
3643     // types again after this. Because this updates the type, we do this before
3644     // any of the other checks below, which may update the "de facto" NewQType
3645     // but do not necessarily update the type of New.
3646     if (CheckEquivalentExceptionSpec(Old, New))
3647       return true;
3648     OldQType = Context.getCanonicalType(Old->getType());
3649     NewQType = Context.getCanonicalType(New->getType());
3650 
3651     // Go back to the type source info to compare the declared return types,
3652     // per C++1y [dcl.type.auto]p13:
3653     //   Redeclarations or specializations of a function or function template
3654     //   with a declared return type that uses a placeholder type shall also
3655     //   use that placeholder, not a deduced type.
3656     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3657     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3658     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3659         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3660                                        OldDeclaredReturnType)) {
3661       QualType ResQT;
3662       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3663           OldDeclaredReturnType->isObjCObjectPointerType())
3664         // FIXME: This does the wrong thing for a deduced return type.
3665         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3666       if (ResQT.isNull()) {
3667         if (New->isCXXClassMember() && New->isOutOfLine())
3668           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3669               << New << New->getReturnTypeSourceRange();
3670         else
3671           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3672               << New->getReturnTypeSourceRange();
3673         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3674                                     << Old->getReturnTypeSourceRange();
3675         return true;
3676       }
3677       else
3678         NewQType = ResQT;
3679     }
3680 
3681     QualType OldReturnType = OldType->getReturnType();
3682     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3683     if (OldReturnType != NewReturnType) {
3684       // If this function has a deduced return type and has already been
3685       // defined, copy the deduced value from the old declaration.
3686       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3687       if (OldAT && OldAT->isDeduced()) {
3688         QualType DT = OldAT->getDeducedType();
3689         if (DT.isNull()) {
3690           New->setType(SubstAutoTypeDependent(New->getType()));
3691           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3692         } else {
3693           New->setType(SubstAutoType(New->getType(), DT));
3694           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3695         }
3696       }
3697     }
3698 
3699     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3700     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3701     if (OldMethod && NewMethod) {
3702       // Preserve triviality.
3703       NewMethod->setTrivial(OldMethod->isTrivial());
3704 
3705       // MSVC allows explicit template specialization at class scope:
3706       // 2 CXXMethodDecls referring to the same function will be injected.
3707       // We don't want a redeclaration error.
3708       bool IsClassScopeExplicitSpecialization =
3709                               OldMethod->isFunctionTemplateSpecialization() &&
3710                               NewMethod->isFunctionTemplateSpecialization();
3711       bool isFriend = NewMethod->getFriendObjectKind();
3712 
3713       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3714           !IsClassScopeExplicitSpecialization) {
3715         //    -- Member function declarations with the same name and the
3716         //       same parameter types cannot be overloaded if any of them
3717         //       is a static member function declaration.
3718         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3719           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3720           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3721           return true;
3722         }
3723 
3724         // C++ [class.mem]p1:
3725         //   [...] A member shall not be declared twice in the
3726         //   member-specification, except that a nested class or member
3727         //   class template can be declared and then later defined.
3728         if (!inTemplateInstantiation()) {
3729           unsigned NewDiag;
3730           if (isa<CXXConstructorDecl>(OldMethod))
3731             NewDiag = diag::err_constructor_redeclared;
3732           else if (isa<CXXDestructorDecl>(NewMethod))
3733             NewDiag = diag::err_destructor_redeclared;
3734           else if (isa<CXXConversionDecl>(NewMethod))
3735             NewDiag = diag::err_conv_function_redeclared;
3736           else
3737             NewDiag = diag::err_member_redeclared;
3738 
3739           Diag(New->getLocation(), NewDiag);
3740         } else {
3741           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3742             << New << New->getType();
3743         }
3744         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3745         return true;
3746 
3747       // Complain if this is an explicit declaration of a special
3748       // member that was initially declared implicitly.
3749       //
3750       // As an exception, it's okay to befriend such methods in order
3751       // to permit the implicit constructor/destructor/operator calls.
3752       } else if (OldMethod->isImplicit()) {
3753         if (isFriend) {
3754           NewMethod->setImplicit();
3755         } else {
3756           Diag(NewMethod->getLocation(),
3757                diag::err_definition_of_implicitly_declared_member)
3758             << New << getSpecialMember(OldMethod);
3759           return true;
3760         }
3761       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3762         Diag(NewMethod->getLocation(),
3763              diag::err_definition_of_explicitly_defaulted_member)
3764           << getSpecialMember(OldMethod);
3765         return true;
3766       }
3767     }
3768 
3769     // C++11 [dcl.attr.noreturn]p1:
3770     //   The first declaration of a function shall specify the noreturn
3771     //   attribute if any declaration of that function specifies the noreturn
3772     //   attribute.
3773     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3774       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3775         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3776             << NRA;
3777         Diag(Old->getLocation(), diag::note_previous_declaration);
3778       }
3779 
3780     // C++11 [dcl.attr.depend]p2:
3781     //   The first declaration of a function shall specify the
3782     //   carries_dependency attribute for its declarator-id if any declaration
3783     //   of the function specifies the carries_dependency attribute.
3784     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3785     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3786       Diag(CDA->getLocation(),
3787            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3788       Diag(Old->getFirstDecl()->getLocation(),
3789            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3790     }
3791 
3792     // (C++98 8.3.5p3):
3793     //   All declarations for a function shall agree exactly in both the
3794     //   return type and the parameter-type-list.
3795     // We also want to respect all the extended bits except noreturn.
3796 
3797     // noreturn should now match unless the old type info didn't have it.
3798     QualType OldQTypeForComparison = OldQType;
3799     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3800       auto *OldType = OldQType->castAs<FunctionProtoType>();
3801       const FunctionType *OldTypeForComparison
3802         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3803       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3804       assert(OldQTypeForComparison.isCanonical());
3805     }
3806 
3807     if (haveIncompatibleLanguageLinkages(Old, New)) {
3808       // As a special case, retain the language linkage from previous
3809       // declarations of a friend function as an extension.
3810       //
3811       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3812       // and is useful because there's otherwise no way to specify language
3813       // linkage within class scope.
3814       //
3815       // Check cautiously as the friend object kind isn't yet complete.
3816       if (New->getFriendObjectKind() != Decl::FOK_None) {
3817         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3818         Diag(OldLocation, PrevDiag);
3819       } else {
3820         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3821         Diag(OldLocation, PrevDiag);
3822         return true;
3823       }
3824     }
3825 
3826     // If the function types are compatible, merge the declarations. Ignore the
3827     // exception specifier because it was already checked above in
3828     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3829     // about incompatible types under -fms-compatibility.
3830     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3831                                                          NewQType))
3832       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3833 
3834     // If the types are imprecise (due to dependent constructs in friends or
3835     // local extern declarations), it's OK if they differ. We'll check again
3836     // during instantiation.
3837     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3838       return false;
3839 
3840     // Fall through for conflicting redeclarations and redefinitions.
3841   }
3842 
3843   // C: Function types need to be compatible, not identical. This handles
3844   // duplicate function decls like "void f(int); void f(enum X);" properly.
3845   if (!getLangOpts().CPlusPlus &&
3846       Context.typesAreCompatible(OldQType, NewQType)) {
3847     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3848     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3849     const FunctionProtoType *OldProto = nullptr;
3850     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3851         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3852       // The old declaration provided a function prototype, but the
3853       // new declaration does not. Merge in the prototype.
3854       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3855       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3856       NewQType =
3857           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3858                                   OldProto->getExtProtoInfo());
3859       New->setType(NewQType);
3860       New->setHasInheritedPrototype();
3861 
3862       // Synthesize parameters with the same types.
3863       SmallVector<ParmVarDecl*, 16> Params;
3864       for (const auto &ParamType : OldProto->param_types()) {
3865         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3866                                                  SourceLocation(), nullptr,
3867                                                  ParamType, /*TInfo=*/nullptr,
3868                                                  SC_None, nullptr);
3869         Param->setScopeInfo(0, Params.size());
3870         Param->setImplicit();
3871         Params.push_back(Param);
3872       }
3873 
3874       New->setParams(Params);
3875     }
3876 
3877     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3878   }
3879 
3880   // Check if the function types are compatible when pointer size address
3881   // spaces are ignored.
3882   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3883     return false;
3884 
3885   // GNU C permits a K&R definition to follow a prototype declaration
3886   // if the declared types of the parameters in the K&R definition
3887   // match the types in the prototype declaration, even when the
3888   // promoted types of the parameters from the K&R definition differ
3889   // from the types in the prototype. GCC then keeps the types from
3890   // the prototype.
3891   //
3892   // If a variadic prototype is followed by a non-variadic K&R definition,
3893   // the K&R definition becomes variadic.  This is sort of an edge case, but
3894   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3895   // C99 6.9.1p8.
3896   if (!getLangOpts().CPlusPlus &&
3897       Old->hasPrototype() && !New->hasPrototype() &&
3898       New->getType()->getAs<FunctionProtoType>() &&
3899       Old->getNumParams() == New->getNumParams()) {
3900     SmallVector<QualType, 16> ArgTypes;
3901     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3902     const FunctionProtoType *OldProto
3903       = Old->getType()->getAs<FunctionProtoType>();
3904     const FunctionProtoType *NewProto
3905       = New->getType()->getAs<FunctionProtoType>();
3906 
3907     // Determine whether this is the GNU C extension.
3908     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3909                                                NewProto->getReturnType());
3910     bool LooseCompatible = !MergedReturn.isNull();
3911     for (unsigned Idx = 0, End = Old->getNumParams();
3912          LooseCompatible && Idx != End; ++Idx) {
3913       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3914       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3915       if (Context.typesAreCompatible(OldParm->getType(),
3916                                      NewProto->getParamType(Idx))) {
3917         ArgTypes.push_back(NewParm->getType());
3918       } else if (Context.typesAreCompatible(OldParm->getType(),
3919                                             NewParm->getType(),
3920                                             /*CompareUnqualified=*/true)) {
3921         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3922                                            NewProto->getParamType(Idx) };
3923         Warnings.push_back(Warn);
3924         ArgTypes.push_back(NewParm->getType());
3925       } else
3926         LooseCompatible = false;
3927     }
3928 
3929     if (LooseCompatible) {
3930       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3931         Diag(Warnings[Warn].NewParm->getLocation(),
3932              diag::ext_param_promoted_not_compatible_with_prototype)
3933           << Warnings[Warn].PromotedType
3934           << Warnings[Warn].OldParm->getType();
3935         if (Warnings[Warn].OldParm->getLocation().isValid())
3936           Diag(Warnings[Warn].OldParm->getLocation(),
3937                diag::note_previous_declaration);
3938       }
3939 
3940       if (MergeTypeWithOld)
3941         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3942                                              OldProto->getExtProtoInfo()));
3943       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3944     }
3945 
3946     // Fall through to diagnose conflicting types.
3947   }
3948 
3949   // A function that has already been declared has been redeclared or
3950   // defined with a different type; show an appropriate diagnostic.
3951 
3952   // If the previous declaration was an implicitly-generated builtin
3953   // declaration, then at the very least we should use a specialized note.
3954   unsigned BuiltinID;
3955   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3956     // If it's actually a library-defined builtin function like 'malloc'
3957     // or 'printf', just warn about the incompatible redeclaration.
3958     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3959       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3960       Diag(OldLocation, diag::note_previous_builtin_declaration)
3961         << Old << Old->getType();
3962       return false;
3963     }
3964 
3965     PrevDiag = diag::note_previous_builtin_declaration;
3966   }
3967 
3968   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3969   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3970   return true;
3971 }
3972 
3973 /// Completes the merge of two function declarations that are
3974 /// known to be compatible.
3975 ///
3976 /// This routine handles the merging of attributes and other
3977 /// properties of function declarations from the old declaration to
3978 /// the new declaration, once we know that New is in fact a
3979 /// redeclaration of Old.
3980 ///
3981 /// \returns false
3982 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3983                                         Scope *S, bool MergeTypeWithOld) {
3984   // Merge the attributes
3985   mergeDeclAttributes(New, Old);
3986 
3987   // Merge "pure" flag.
3988   if (Old->isPure())
3989     New->setPure();
3990 
3991   // Merge "used" flag.
3992   if (Old->getMostRecentDecl()->isUsed(false))
3993     New->setIsUsed();
3994 
3995   // Merge attributes from the parameters.  These can mismatch with K&R
3996   // declarations.
3997   if (New->getNumParams() == Old->getNumParams())
3998       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3999         ParmVarDecl *NewParam = New->getParamDecl(i);
4000         ParmVarDecl *OldParam = Old->getParamDecl(i);
4001         mergeParamDeclAttributes(NewParam, OldParam, *this);
4002         mergeParamDeclTypes(NewParam, OldParam, *this);
4003       }
4004 
4005   if (getLangOpts().CPlusPlus)
4006     return MergeCXXFunctionDecl(New, Old, S);
4007 
4008   // Merge the function types so the we get the composite types for the return
4009   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4010   // was visible.
4011   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4012   if (!Merged.isNull() && MergeTypeWithOld)
4013     New->setType(Merged);
4014 
4015   return false;
4016 }
4017 
4018 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4019                                 ObjCMethodDecl *oldMethod) {
4020   // Merge the attributes, including deprecated/unavailable
4021   AvailabilityMergeKind MergeKind =
4022       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4023           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4024                                      : AMK_ProtocolImplementation)
4025           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4026                                                            : AMK_Override;
4027 
4028   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4029 
4030   // Merge attributes from the parameters.
4031   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4032                                        oe = oldMethod->param_end();
4033   for (ObjCMethodDecl::param_iterator
4034          ni = newMethod->param_begin(), ne = newMethod->param_end();
4035        ni != ne && oi != oe; ++ni, ++oi)
4036     mergeParamDeclAttributes(*ni, *oi, *this);
4037 
4038   CheckObjCMethodOverride(newMethod, oldMethod);
4039 }
4040 
4041 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4042   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4043 
4044   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4045          ? diag::err_redefinition_different_type
4046          : diag::err_redeclaration_different_type)
4047     << New->getDeclName() << New->getType() << Old->getType();
4048 
4049   diag::kind PrevDiag;
4050   SourceLocation OldLocation;
4051   std::tie(PrevDiag, OldLocation)
4052     = getNoteDiagForInvalidRedeclaration(Old, New);
4053   S.Diag(OldLocation, PrevDiag);
4054   New->setInvalidDecl();
4055 }
4056 
4057 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4058 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4059 /// emitting diagnostics as appropriate.
4060 ///
4061 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4062 /// to here in AddInitializerToDecl. We can't check them before the initializer
4063 /// is attached.
4064 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4065                              bool MergeTypeWithOld) {
4066   if (New->isInvalidDecl() || Old->isInvalidDecl())
4067     return;
4068 
4069   QualType MergedT;
4070   if (getLangOpts().CPlusPlus) {
4071     if (New->getType()->isUndeducedType()) {
4072       // We don't know what the new type is until the initializer is attached.
4073       return;
4074     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4075       // These could still be something that needs exception specs checked.
4076       return MergeVarDeclExceptionSpecs(New, Old);
4077     }
4078     // C++ [basic.link]p10:
4079     //   [...] the types specified by all declarations referring to a given
4080     //   object or function shall be identical, except that declarations for an
4081     //   array object can specify array types that differ by the presence or
4082     //   absence of a major array bound (8.3.4).
4083     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4084       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4085       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4086 
4087       // We are merging a variable declaration New into Old. If it has an array
4088       // bound, and that bound differs from Old's bound, we should diagnose the
4089       // mismatch.
4090       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4091         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4092              PrevVD = PrevVD->getPreviousDecl()) {
4093           QualType PrevVDTy = PrevVD->getType();
4094           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4095             continue;
4096 
4097           if (!Context.hasSameType(New->getType(), PrevVDTy))
4098             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4099         }
4100       }
4101 
4102       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4103         if (Context.hasSameType(OldArray->getElementType(),
4104                                 NewArray->getElementType()))
4105           MergedT = New->getType();
4106       }
4107       // FIXME: Check visibility. New is hidden but has a complete type. If New
4108       // has no array bound, it should not inherit one from Old, if Old is not
4109       // visible.
4110       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4111         if (Context.hasSameType(OldArray->getElementType(),
4112                                 NewArray->getElementType()))
4113           MergedT = Old->getType();
4114       }
4115     }
4116     else if (New->getType()->isObjCObjectPointerType() &&
4117                Old->getType()->isObjCObjectPointerType()) {
4118       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4119                                               Old->getType());
4120     }
4121   } else {
4122     // C 6.2.7p2:
4123     //   All declarations that refer to the same object or function shall have
4124     //   compatible type.
4125     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4126   }
4127   if (MergedT.isNull()) {
4128     // It's OK if we couldn't merge types if either type is dependent, for a
4129     // block-scope variable. In other cases (static data members of class
4130     // templates, variable templates, ...), we require the types to be
4131     // equivalent.
4132     // FIXME: The C++ standard doesn't say anything about this.
4133     if ((New->getType()->isDependentType() ||
4134          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4135       // If the old type was dependent, we can't merge with it, so the new type
4136       // becomes dependent for now. We'll reproduce the original type when we
4137       // instantiate the TypeSourceInfo for the variable.
4138       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4139         New->setType(Context.DependentTy);
4140       return;
4141     }
4142     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4143   }
4144 
4145   // Don't actually update the type on the new declaration if the old
4146   // declaration was an extern declaration in a different scope.
4147   if (MergeTypeWithOld)
4148     New->setType(MergedT);
4149 }
4150 
4151 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4152                                   LookupResult &Previous) {
4153   // C11 6.2.7p4:
4154   //   For an identifier with internal or external linkage declared
4155   //   in a scope in which a prior declaration of that identifier is
4156   //   visible, if the prior declaration specifies internal or
4157   //   external linkage, the type of the identifier at the later
4158   //   declaration becomes the composite type.
4159   //
4160   // If the variable isn't visible, we do not merge with its type.
4161   if (Previous.isShadowed())
4162     return false;
4163 
4164   if (S.getLangOpts().CPlusPlus) {
4165     // C++11 [dcl.array]p3:
4166     //   If there is a preceding declaration of the entity in the same
4167     //   scope in which the bound was specified, an omitted array bound
4168     //   is taken to be the same as in that earlier declaration.
4169     return NewVD->isPreviousDeclInSameBlockScope() ||
4170            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4171             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4172   } else {
4173     // If the old declaration was function-local, don't merge with its
4174     // type unless we're in the same function.
4175     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4176            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4177   }
4178 }
4179 
4180 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4181 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4182 /// situation, merging decls or emitting diagnostics as appropriate.
4183 ///
4184 /// Tentative definition rules (C99 6.9.2p2) are checked by
4185 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4186 /// definitions here, since the initializer hasn't been attached.
4187 ///
4188 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4189   // If the new decl is already invalid, don't do any other checking.
4190   if (New->isInvalidDecl())
4191     return;
4192 
4193   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4194     return;
4195 
4196   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4197 
4198   // Verify the old decl was also a variable or variable template.
4199   VarDecl *Old = nullptr;
4200   VarTemplateDecl *OldTemplate = nullptr;
4201   if (Previous.isSingleResult()) {
4202     if (NewTemplate) {
4203       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4204       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4205 
4206       if (auto *Shadow =
4207               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4208         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4209           return New->setInvalidDecl();
4210     } else {
4211       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4212 
4213       if (auto *Shadow =
4214               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4215         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4216           return New->setInvalidDecl();
4217     }
4218   }
4219   if (!Old) {
4220     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4221         << New->getDeclName();
4222     notePreviousDefinition(Previous.getRepresentativeDecl(),
4223                            New->getLocation());
4224     return New->setInvalidDecl();
4225   }
4226 
4227   // If the old declaration was found in an inline namespace and the new
4228   // declaration was qualified, update the DeclContext to match.
4229   adjustDeclContextForDeclaratorDecl(New, Old);
4230 
4231   // Ensure the template parameters are compatible.
4232   if (NewTemplate &&
4233       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4234                                       OldTemplate->getTemplateParameters(),
4235                                       /*Complain=*/true, TPL_TemplateMatch))
4236     return New->setInvalidDecl();
4237 
4238   // C++ [class.mem]p1:
4239   //   A member shall not be declared twice in the member-specification [...]
4240   //
4241   // Here, we need only consider static data members.
4242   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4243     Diag(New->getLocation(), diag::err_duplicate_member)
4244       << New->getIdentifier();
4245     Diag(Old->getLocation(), diag::note_previous_declaration);
4246     New->setInvalidDecl();
4247   }
4248 
4249   mergeDeclAttributes(New, Old);
4250   // Warn if an already-declared variable is made a weak_import in a subsequent
4251   // declaration
4252   if (New->hasAttr<WeakImportAttr>() &&
4253       Old->getStorageClass() == SC_None &&
4254       !Old->hasAttr<WeakImportAttr>()) {
4255     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4256     Diag(Old->getLocation(), diag::note_previous_declaration);
4257     // Remove weak_import attribute on new declaration.
4258     New->dropAttr<WeakImportAttr>();
4259   }
4260 
4261   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4262     if (!Old->hasAttr<InternalLinkageAttr>()) {
4263       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4264           << ILA;
4265       Diag(Old->getLocation(), diag::note_previous_declaration);
4266       New->dropAttr<InternalLinkageAttr>();
4267     }
4268 
4269   // Merge the types.
4270   VarDecl *MostRecent = Old->getMostRecentDecl();
4271   if (MostRecent != Old) {
4272     MergeVarDeclTypes(New, MostRecent,
4273                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4274     if (New->isInvalidDecl())
4275       return;
4276   }
4277 
4278   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4279   if (New->isInvalidDecl())
4280     return;
4281 
4282   diag::kind PrevDiag;
4283   SourceLocation OldLocation;
4284   std::tie(PrevDiag, OldLocation) =
4285       getNoteDiagForInvalidRedeclaration(Old, New);
4286 
4287   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4288   if (New->getStorageClass() == SC_Static &&
4289       !New->isStaticDataMember() &&
4290       Old->hasExternalFormalLinkage()) {
4291     if (getLangOpts().MicrosoftExt) {
4292       Diag(New->getLocation(), diag::ext_static_non_static)
4293           << New->getDeclName();
4294       Diag(OldLocation, PrevDiag);
4295     } else {
4296       Diag(New->getLocation(), diag::err_static_non_static)
4297           << New->getDeclName();
4298       Diag(OldLocation, PrevDiag);
4299       return New->setInvalidDecl();
4300     }
4301   }
4302   // C99 6.2.2p4:
4303   //   For an identifier declared with the storage-class specifier
4304   //   extern in a scope in which a prior declaration of that
4305   //   identifier is visible,23) if the prior declaration specifies
4306   //   internal or external linkage, the linkage of the identifier at
4307   //   the later declaration is the same as the linkage specified at
4308   //   the prior declaration. If no prior declaration is visible, or
4309   //   if the prior declaration specifies no linkage, then the
4310   //   identifier has external linkage.
4311   if (New->hasExternalStorage() && Old->hasLinkage())
4312     /* Okay */;
4313   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4314            !New->isStaticDataMember() &&
4315            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4316     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4317     Diag(OldLocation, PrevDiag);
4318     return New->setInvalidDecl();
4319   }
4320 
4321   // Check if extern is followed by non-extern and vice-versa.
4322   if (New->hasExternalStorage() &&
4323       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4324     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4325     Diag(OldLocation, PrevDiag);
4326     return New->setInvalidDecl();
4327   }
4328   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4329       !New->hasExternalStorage()) {
4330     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4331     Diag(OldLocation, PrevDiag);
4332     return New->setInvalidDecl();
4333   }
4334 
4335   if (CheckRedeclarationInModule(New, Old))
4336     return;
4337 
4338   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4339 
4340   // FIXME: The test for external storage here seems wrong? We still
4341   // need to check for mismatches.
4342   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4343       // Don't complain about out-of-line definitions of static members.
4344       !(Old->getLexicalDeclContext()->isRecord() &&
4345         !New->getLexicalDeclContext()->isRecord())) {
4346     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4347     Diag(OldLocation, PrevDiag);
4348     return New->setInvalidDecl();
4349   }
4350 
4351   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4352     if (VarDecl *Def = Old->getDefinition()) {
4353       // C++1z [dcl.fcn.spec]p4:
4354       //   If the definition of a variable appears in a translation unit before
4355       //   its first declaration as inline, the program is ill-formed.
4356       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4357       Diag(Def->getLocation(), diag::note_previous_definition);
4358     }
4359   }
4360 
4361   // If this redeclaration makes the variable inline, we may need to add it to
4362   // UndefinedButUsed.
4363   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4364       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4365     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4366                                            SourceLocation()));
4367 
4368   if (New->getTLSKind() != Old->getTLSKind()) {
4369     if (!Old->getTLSKind()) {
4370       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4371       Diag(OldLocation, PrevDiag);
4372     } else if (!New->getTLSKind()) {
4373       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4374       Diag(OldLocation, PrevDiag);
4375     } else {
4376       // Do not allow redeclaration to change the variable between requiring
4377       // static and dynamic initialization.
4378       // FIXME: GCC allows this, but uses the TLS keyword on the first
4379       // declaration to determine the kind. Do we need to be compatible here?
4380       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4381         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4382       Diag(OldLocation, PrevDiag);
4383     }
4384   }
4385 
4386   // C++ doesn't have tentative definitions, so go right ahead and check here.
4387   if (getLangOpts().CPlusPlus &&
4388       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4389     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4390         Old->getCanonicalDecl()->isConstexpr()) {
4391       // This definition won't be a definition any more once it's been merged.
4392       Diag(New->getLocation(),
4393            diag::warn_deprecated_redundant_constexpr_static_def);
4394     } else if (VarDecl *Def = Old->getDefinition()) {
4395       if (checkVarDeclRedefinition(Def, New))
4396         return;
4397     }
4398   }
4399 
4400   if (haveIncompatibleLanguageLinkages(Old, New)) {
4401     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4402     Diag(OldLocation, PrevDiag);
4403     New->setInvalidDecl();
4404     return;
4405   }
4406 
4407   // Merge "used" flag.
4408   if (Old->getMostRecentDecl()->isUsed(false))
4409     New->setIsUsed();
4410 
4411   // Keep a chain of previous declarations.
4412   New->setPreviousDecl(Old);
4413   if (NewTemplate)
4414     NewTemplate->setPreviousDecl(OldTemplate);
4415 
4416   // Inherit access appropriately.
4417   New->setAccess(Old->getAccess());
4418   if (NewTemplate)
4419     NewTemplate->setAccess(New->getAccess());
4420 
4421   if (Old->isInline())
4422     New->setImplicitlyInline();
4423 }
4424 
4425 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4426   SourceManager &SrcMgr = getSourceManager();
4427   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4428   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4429   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4430   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4431   auto &HSI = PP.getHeaderSearchInfo();
4432   StringRef HdrFilename =
4433       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4434 
4435   auto noteFromModuleOrInclude = [&](Module *Mod,
4436                                      SourceLocation IncLoc) -> bool {
4437     // Redefinition errors with modules are common with non modular mapped
4438     // headers, example: a non-modular header H in module A that also gets
4439     // included directly in a TU. Pointing twice to the same header/definition
4440     // is confusing, try to get better diagnostics when modules is on.
4441     if (IncLoc.isValid()) {
4442       if (Mod) {
4443         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4444             << HdrFilename.str() << Mod->getFullModuleName();
4445         if (!Mod->DefinitionLoc.isInvalid())
4446           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4447               << Mod->getFullModuleName();
4448       } else {
4449         Diag(IncLoc, diag::note_redefinition_include_same_file)
4450             << HdrFilename.str();
4451       }
4452       return true;
4453     }
4454 
4455     return false;
4456   };
4457 
4458   // Is it the same file and same offset? Provide more information on why
4459   // this leads to a redefinition error.
4460   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4461     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4462     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4463     bool EmittedDiag =
4464         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4465     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4466 
4467     // If the header has no guards, emit a note suggesting one.
4468     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4469       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4470 
4471     if (EmittedDiag)
4472       return;
4473   }
4474 
4475   // Redefinition coming from different files or couldn't do better above.
4476   if (Old->getLocation().isValid())
4477     Diag(Old->getLocation(), diag::note_previous_definition);
4478 }
4479 
4480 /// We've just determined that \p Old and \p New both appear to be definitions
4481 /// of the same variable. Either diagnose or fix the problem.
4482 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4483   if (!hasVisibleDefinition(Old) &&
4484       (New->getFormalLinkage() == InternalLinkage ||
4485        New->isInline() ||
4486        New->getDescribedVarTemplate() ||
4487        New->getNumTemplateParameterLists() ||
4488        New->getDeclContext()->isDependentContext())) {
4489     // The previous definition is hidden, and multiple definitions are
4490     // permitted (in separate TUs). Demote this to a declaration.
4491     New->demoteThisDefinitionToDeclaration();
4492 
4493     // Make the canonical definition visible.
4494     if (auto *OldTD = Old->getDescribedVarTemplate())
4495       makeMergedDefinitionVisible(OldTD);
4496     makeMergedDefinitionVisible(Old);
4497     return false;
4498   } else {
4499     Diag(New->getLocation(), diag::err_redefinition) << New;
4500     notePreviousDefinition(Old, New->getLocation());
4501     New->setInvalidDecl();
4502     return true;
4503   }
4504 }
4505 
4506 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4507 /// no declarator (e.g. "struct foo;") is parsed.
4508 Decl *
4509 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4510                                  RecordDecl *&AnonRecord) {
4511   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4512                                     AnonRecord);
4513 }
4514 
4515 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4516 // disambiguate entities defined in different scopes.
4517 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4518 // compatibility.
4519 // We will pick our mangling number depending on which version of MSVC is being
4520 // targeted.
4521 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4522   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4523              ? S->getMSCurManglingNumber()
4524              : S->getMSLastManglingNumber();
4525 }
4526 
4527 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4528   if (!Context.getLangOpts().CPlusPlus)
4529     return;
4530 
4531   if (isa<CXXRecordDecl>(Tag->getParent())) {
4532     // If this tag is the direct child of a class, number it if
4533     // it is anonymous.
4534     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4535       return;
4536     MangleNumberingContext &MCtx =
4537         Context.getManglingNumberContext(Tag->getParent());
4538     Context.setManglingNumber(
4539         Tag, MCtx.getManglingNumber(
4540                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4541     return;
4542   }
4543 
4544   // If this tag isn't a direct child of a class, number it if it is local.
4545   MangleNumberingContext *MCtx;
4546   Decl *ManglingContextDecl;
4547   std::tie(MCtx, ManglingContextDecl) =
4548       getCurrentMangleNumberContext(Tag->getDeclContext());
4549   if (MCtx) {
4550     Context.setManglingNumber(
4551         Tag, MCtx->getManglingNumber(
4552                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4553   }
4554 }
4555 
4556 namespace {
4557 struct NonCLikeKind {
4558   enum {
4559     None,
4560     BaseClass,
4561     DefaultMemberInit,
4562     Lambda,
4563     Friend,
4564     OtherMember,
4565     Invalid,
4566   } Kind = None;
4567   SourceRange Range;
4568 
4569   explicit operator bool() { return Kind != None; }
4570 };
4571 }
4572 
4573 /// Determine whether a class is C-like, according to the rules of C++
4574 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4575 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4576   if (RD->isInvalidDecl())
4577     return {NonCLikeKind::Invalid, {}};
4578 
4579   // C++ [dcl.typedef]p9: [P1766R1]
4580   //   An unnamed class with a typedef name for linkage purposes shall not
4581   //
4582   //    -- have any base classes
4583   if (RD->getNumBases())
4584     return {NonCLikeKind::BaseClass,
4585             SourceRange(RD->bases_begin()->getBeginLoc(),
4586                         RD->bases_end()[-1].getEndLoc())};
4587   bool Invalid = false;
4588   for (Decl *D : RD->decls()) {
4589     // Don't complain about things we already diagnosed.
4590     if (D->isInvalidDecl()) {
4591       Invalid = true;
4592       continue;
4593     }
4594 
4595     //  -- have any [...] default member initializers
4596     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4597       if (FD->hasInClassInitializer()) {
4598         auto *Init = FD->getInClassInitializer();
4599         return {NonCLikeKind::DefaultMemberInit,
4600                 Init ? Init->getSourceRange() : D->getSourceRange()};
4601       }
4602       continue;
4603     }
4604 
4605     // FIXME: We don't allow friend declarations. This violates the wording of
4606     // P1766, but not the intent.
4607     if (isa<FriendDecl>(D))
4608       return {NonCLikeKind::Friend, D->getSourceRange()};
4609 
4610     //  -- declare any members other than non-static data members, member
4611     //     enumerations, or member classes,
4612     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4613         isa<EnumDecl>(D))
4614       continue;
4615     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4616     if (!MemberRD) {
4617       if (D->isImplicit())
4618         continue;
4619       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4620     }
4621 
4622     //  -- contain a lambda-expression,
4623     if (MemberRD->isLambda())
4624       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4625 
4626     //  and all member classes shall also satisfy these requirements
4627     //  (recursively).
4628     if (MemberRD->isThisDeclarationADefinition()) {
4629       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4630         return Kind;
4631     }
4632   }
4633 
4634   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4635 }
4636 
4637 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4638                                         TypedefNameDecl *NewTD) {
4639   if (TagFromDeclSpec->isInvalidDecl())
4640     return;
4641 
4642   // Do nothing if the tag already has a name for linkage purposes.
4643   if (TagFromDeclSpec->hasNameForLinkage())
4644     return;
4645 
4646   // A well-formed anonymous tag must always be a TUK_Definition.
4647   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4648 
4649   // The type must match the tag exactly;  no qualifiers allowed.
4650   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4651                            Context.getTagDeclType(TagFromDeclSpec))) {
4652     if (getLangOpts().CPlusPlus)
4653       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4654     return;
4655   }
4656 
4657   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4658   //   An unnamed class with a typedef name for linkage purposes shall [be
4659   //   C-like].
4660   //
4661   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4662   // shouldn't happen, but there are constructs that the language rule doesn't
4663   // disallow for which we can't reasonably avoid computing linkage early.
4664   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4665   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4666                              : NonCLikeKind();
4667   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4668   if (NonCLike || ChangesLinkage) {
4669     if (NonCLike.Kind == NonCLikeKind::Invalid)
4670       return;
4671 
4672     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4673     if (ChangesLinkage) {
4674       // If the linkage changes, we can't accept this as an extension.
4675       if (NonCLike.Kind == NonCLikeKind::None)
4676         DiagID = diag::err_typedef_changes_linkage;
4677       else
4678         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4679     }
4680 
4681     SourceLocation FixitLoc =
4682         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4683     llvm::SmallString<40> TextToInsert;
4684     TextToInsert += ' ';
4685     TextToInsert += NewTD->getIdentifier()->getName();
4686 
4687     Diag(FixitLoc, DiagID)
4688       << isa<TypeAliasDecl>(NewTD)
4689       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4690     if (NonCLike.Kind != NonCLikeKind::None) {
4691       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4692         << NonCLike.Kind - 1 << NonCLike.Range;
4693     }
4694     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4695       << NewTD << isa<TypeAliasDecl>(NewTD);
4696 
4697     if (ChangesLinkage)
4698       return;
4699   }
4700 
4701   // Otherwise, set this as the anon-decl typedef for the tag.
4702   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4703 }
4704 
4705 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4706   switch (T) {
4707   case DeclSpec::TST_class:
4708     return 0;
4709   case DeclSpec::TST_struct:
4710     return 1;
4711   case DeclSpec::TST_interface:
4712     return 2;
4713   case DeclSpec::TST_union:
4714     return 3;
4715   case DeclSpec::TST_enum:
4716     return 4;
4717   default:
4718     llvm_unreachable("unexpected type specifier");
4719   }
4720 }
4721 
4722 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4723 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4724 /// parameters to cope with template friend declarations.
4725 Decl *
4726 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4727                                  MultiTemplateParamsArg TemplateParams,
4728                                  bool IsExplicitInstantiation,
4729                                  RecordDecl *&AnonRecord) {
4730   Decl *TagD = nullptr;
4731   TagDecl *Tag = nullptr;
4732   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4733       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4734       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4735       DS.getTypeSpecType() == DeclSpec::TST_union ||
4736       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4737     TagD = DS.getRepAsDecl();
4738 
4739     if (!TagD) // We probably had an error
4740       return nullptr;
4741 
4742     // Note that the above type specs guarantee that the
4743     // type rep is a Decl, whereas in many of the others
4744     // it's a Type.
4745     if (isa<TagDecl>(TagD))
4746       Tag = cast<TagDecl>(TagD);
4747     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4748       Tag = CTD->getTemplatedDecl();
4749   }
4750 
4751   if (Tag) {
4752     handleTagNumbering(Tag, S);
4753     Tag->setFreeStanding();
4754     if (Tag->isInvalidDecl())
4755       return Tag;
4756   }
4757 
4758   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4759     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4760     // or incomplete types shall not be restrict-qualified."
4761     if (TypeQuals & DeclSpec::TQ_restrict)
4762       Diag(DS.getRestrictSpecLoc(),
4763            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4764            << DS.getSourceRange();
4765   }
4766 
4767   if (DS.isInlineSpecified())
4768     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4769         << getLangOpts().CPlusPlus17;
4770 
4771   if (DS.hasConstexprSpecifier()) {
4772     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4773     // and definitions of functions and variables.
4774     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4775     // the declaration of a function or function template
4776     if (Tag)
4777       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4778           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4779           << static_cast<int>(DS.getConstexprSpecifier());
4780     else
4781       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4782           << static_cast<int>(DS.getConstexprSpecifier());
4783     // Don't emit warnings after this error.
4784     return TagD;
4785   }
4786 
4787   DiagnoseFunctionSpecifiers(DS);
4788 
4789   if (DS.isFriendSpecified()) {
4790     // If we're dealing with a decl but not a TagDecl, assume that
4791     // whatever routines created it handled the friendship aspect.
4792     if (TagD && !Tag)
4793       return nullptr;
4794     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4795   }
4796 
4797   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4798   bool IsExplicitSpecialization =
4799     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4800   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4801       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4802       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4803     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4804     // nested-name-specifier unless it is an explicit instantiation
4805     // or an explicit specialization.
4806     //
4807     // FIXME: We allow class template partial specializations here too, per the
4808     // obvious intent of DR1819.
4809     //
4810     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4811     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4812         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4813     return nullptr;
4814   }
4815 
4816   // Track whether this decl-specifier declares anything.
4817   bool DeclaresAnything = true;
4818 
4819   // Handle anonymous struct definitions.
4820   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4821     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4822         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4823       if (getLangOpts().CPlusPlus ||
4824           Record->getDeclContext()->isRecord()) {
4825         // If CurContext is a DeclContext that can contain statements,
4826         // RecursiveASTVisitor won't visit the decls that
4827         // BuildAnonymousStructOrUnion() will put into CurContext.
4828         // Also store them here so that they can be part of the
4829         // DeclStmt that gets created in this case.
4830         // FIXME: Also return the IndirectFieldDecls created by
4831         // BuildAnonymousStructOr union, for the same reason?
4832         if (CurContext->isFunctionOrMethod())
4833           AnonRecord = Record;
4834         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4835                                            Context.getPrintingPolicy());
4836       }
4837 
4838       DeclaresAnything = false;
4839     }
4840   }
4841 
4842   // C11 6.7.2.1p2:
4843   //   A struct-declaration that does not declare an anonymous structure or
4844   //   anonymous union shall contain a struct-declarator-list.
4845   //
4846   // This rule also existed in C89 and C99; the grammar for struct-declaration
4847   // did not permit a struct-declaration without a struct-declarator-list.
4848   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4849       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4850     // Check for Microsoft C extension: anonymous struct/union member.
4851     // Handle 2 kinds of anonymous struct/union:
4852     //   struct STRUCT;
4853     //   union UNION;
4854     // and
4855     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4856     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4857     if ((Tag && Tag->getDeclName()) ||
4858         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4859       RecordDecl *Record = nullptr;
4860       if (Tag)
4861         Record = dyn_cast<RecordDecl>(Tag);
4862       else if (const RecordType *RT =
4863                    DS.getRepAsType().get()->getAsStructureType())
4864         Record = RT->getDecl();
4865       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4866         Record = UT->getDecl();
4867 
4868       if (Record && getLangOpts().MicrosoftExt) {
4869         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4870             << Record->isUnion() << DS.getSourceRange();
4871         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4872       }
4873 
4874       DeclaresAnything = false;
4875     }
4876   }
4877 
4878   // Skip all the checks below if we have a type error.
4879   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4880       (TagD && TagD->isInvalidDecl()))
4881     return TagD;
4882 
4883   if (getLangOpts().CPlusPlus &&
4884       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4885     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4886       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4887           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4888         DeclaresAnything = false;
4889 
4890   if (!DS.isMissingDeclaratorOk()) {
4891     // Customize diagnostic for a typedef missing a name.
4892     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4893       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4894           << DS.getSourceRange();
4895     else
4896       DeclaresAnything = false;
4897   }
4898 
4899   if (DS.isModulePrivateSpecified() &&
4900       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4901     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4902       << Tag->getTagKind()
4903       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4904 
4905   ActOnDocumentableDecl(TagD);
4906 
4907   // C 6.7/2:
4908   //   A declaration [...] shall declare at least a declarator [...], a tag,
4909   //   or the members of an enumeration.
4910   // C++ [dcl.dcl]p3:
4911   //   [If there are no declarators], and except for the declaration of an
4912   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4913   //   names into the program, or shall redeclare a name introduced by a
4914   //   previous declaration.
4915   if (!DeclaresAnything) {
4916     // In C, we allow this as a (popular) extension / bug. Don't bother
4917     // producing further diagnostics for redundant qualifiers after this.
4918     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4919                                ? diag::err_no_declarators
4920                                : diag::ext_no_declarators)
4921         << DS.getSourceRange();
4922     return TagD;
4923   }
4924 
4925   // C++ [dcl.stc]p1:
4926   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4927   //   init-declarator-list of the declaration shall not be empty.
4928   // C++ [dcl.fct.spec]p1:
4929   //   If a cv-qualifier appears in a decl-specifier-seq, the
4930   //   init-declarator-list of the declaration shall not be empty.
4931   //
4932   // Spurious qualifiers here appear to be valid in C.
4933   unsigned DiagID = diag::warn_standalone_specifier;
4934   if (getLangOpts().CPlusPlus)
4935     DiagID = diag::ext_standalone_specifier;
4936 
4937   // Note that a linkage-specification sets a storage class, but
4938   // 'extern "C" struct foo;' is actually valid and not theoretically
4939   // useless.
4940   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4941     if (SCS == DeclSpec::SCS_mutable)
4942       // Since mutable is not a viable storage class specifier in C, there is
4943       // no reason to treat it as an extension. Instead, diagnose as an error.
4944       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4945     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4946       Diag(DS.getStorageClassSpecLoc(), DiagID)
4947         << DeclSpec::getSpecifierName(SCS);
4948   }
4949 
4950   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4951     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4952       << DeclSpec::getSpecifierName(TSCS);
4953   if (DS.getTypeQualifiers()) {
4954     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4955       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4956     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4957       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4958     // Restrict is covered above.
4959     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4960       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4961     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4962       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4963   }
4964 
4965   // Warn about ignored type attributes, for example:
4966   // __attribute__((aligned)) struct A;
4967   // Attributes should be placed after tag to apply to type declaration.
4968   if (!DS.getAttributes().empty()) {
4969     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4970     if (TypeSpecType == DeclSpec::TST_class ||
4971         TypeSpecType == DeclSpec::TST_struct ||
4972         TypeSpecType == DeclSpec::TST_interface ||
4973         TypeSpecType == DeclSpec::TST_union ||
4974         TypeSpecType == DeclSpec::TST_enum) {
4975       for (const ParsedAttr &AL : DS.getAttributes())
4976         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4977             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4978     }
4979   }
4980 
4981   return TagD;
4982 }
4983 
4984 /// We are trying to inject an anonymous member into the given scope;
4985 /// check if there's an existing declaration that can't be overloaded.
4986 ///
4987 /// \return true if this is a forbidden redeclaration
4988 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4989                                          Scope *S,
4990                                          DeclContext *Owner,
4991                                          DeclarationName Name,
4992                                          SourceLocation NameLoc,
4993                                          bool IsUnion) {
4994   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4995                  Sema::ForVisibleRedeclaration);
4996   if (!SemaRef.LookupName(R, S)) return false;
4997 
4998   // Pick a representative declaration.
4999   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5000   assert(PrevDecl && "Expected a non-null Decl");
5001 
5002   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5003     return false;
5004 
5005   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5006     << IsUnion << Name;
5007   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5008 
5009   return true;
5010 }
5011 
5012 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5013 /// anonymous struct or union AnonRecord into the owning context Owner
5014 /// and scope S. This routine will be invoked just after we realize
5015 /// that an unnamed union or struct is actually an anonymous union or
5016 /// struct, e.g.,
5017 ///
5018 /// @code
5019 /// union {
5020 ///   int i;
5021 ///   float f;
5022 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5023 ///    // f into the surrounding scope.x
5024 /// @endcode
5025 ///
5026 /// This routine is recursive, injecting the names of nested anonymous
5027 /// structs/unions into the owning context and scope as well.
5028 static bool
5029 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5030                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5031                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5032   bool Invalid = false;
5033 
5034   // Look every FieldDecl and IndirectFieldDecl with a name.
5035   for (auto *D : AnonRecord->decls()) {
5036     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5037         cast<NamedDecl>(D)->getDeclName()) {
5038       ValueDecl *VD = cast<ValueDecl>(D);
5039       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5040                                        VD->getLocation(),
5041                                        AnonRecord->isUnion())) {
5042         // C++ [class.union]p2:
5043         //   The names of the members of an anonymous union shall be
5044         //   distinct from the names of any other entity in the
5045         //   scope in which the anonymous union is declared.
5046         Invalid = true;
5047       } else {
5048         // C++ [class.union]p2:
5049         //   For the purpose of name lookup, after the anonymous union
5050         //   definition, the members of the anonymous union are
5051         //   considered to have been defined in the scope in which the
5052         //   anonymous union is declared.
5053         unsigned OldChainingSize = Chaining.size();
5054         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5055           Chaining.append(IF->chain_begin(), IF->chain_end());
5056         else
5057           Chaining.push_back(VD);
5058 
5059         assert(Chaining.size() >= 2);
5060         NamedDecl **NamedChain =
5061           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5062         for (unsigned i = 0; i < Chaining.size(); i++)
5063           NamedChain[i] = Chaining[i];
5064 
5065         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5066             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5067             VD->getType(), {NamedChain, Chaining.size()});
5068 
5069         for (const auto *Attr : VD->attrs())
5070           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5071 
5072         IndirectField->setAccess(AS);
5073         IndirectField->setImplicit();
5074         SemaRef.PushOnScopeChains(IndirectField, S);
5075 
5076         // That includes picking up the appropriate access specifier.
5077         if (AS != AS_none) IndirectField->setAccess(AS);
5078 
5079         Chaining.resize(OldChainingSize);
5080       }
5081     }
5082   }
5083 
5084   return Invalid;
5085 }
5086 
5087 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5088 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5089 /// illegal input values are mapped to SC_None.
5090 static StorageClass
5091 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5092   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5093   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5094          "Parser allowed 'typedef' as storage class VarDecl.");
5095   switch (StorageClassSpec) {
5096   case DeclSpec::SCS_unspecified:    return SC_None;
5097   case DeclSpec::SCS_extern:
5098     if (DS.isExternInLinkageSpec())
5099       return SC_None;
5100     return SC_Extern;
5101   case DeclSpec::SCS_static:         return SC_Static;
5102   case DeclSpec::SCS_auto:           return SC_Auto;
5103   case DeclSpec::SCS_register:       return SC_Register;
5104   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5105     // Illegal SCSs map to None: error reporting is up to the caller.
5106   case DeclSpec::SCS_mutable:        // Fall through.
5107   case DeclSpec::SCS_typedef:        return SC_None;
5108   }
5109   llvm_unreachable("unknown storage class specifier");
5110 }
5111 
5112 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5113   assert(Record->hasInClassInitializer());
5114 
5115   for (const auto *I : Record->decls()) {
5116     const auto *FD = dyn_cast<FieldDecl>(I);
5117     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5118       FD = IFD->getAnonField();
5119     if (FD && FD->hasInClassInitializer())
5120       return FD->getLocation();
5121   }
5122 
5123   llvm_unreachable("couldn't find in-class initializer");
5124 }
5125 
5126 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5127                                       SourceLocation DefaultInitLoc) {
5128   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5129     return;
5130 
5131   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5132   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5133 }
5134 
5135 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5136                                       CXXRecordDecl *AnonUnion) {
5137   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5138     return;
5139 
5140   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5141 }
5142 
5143 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5144 /// anonymous structure or union. Anonymous unions are a C++ feature
5145 /// (C++ [class.union]) and a C11 feature; anonymous structures
5146 /// are a C11 feature and GNU C++ extension.
5147 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5148                                         AccessSpecifier AS,
5149                                         RecordDecl *Record,
5150                                         const PrintingPolicy &Policy) {
5151   DeclContext *Owner = Record->getDeclContext();
5152 
5153   // Diagnose whether this anonymous struct/union is an extension.
5154   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5155     Diag(Record->getLocation(), diag::ext_anonymous_union);
5156   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5157     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5158   else if (!Record->isUnion() && !getLangOpts().C11)
5159     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5160 
5161   // C and C++ require different kinds of checks for anonymous
5162   // structs/unions.
5163   bool Invalid = false;
5164   if (getLangOpts().CPlusPlus) {
5165     const char *PrevSpec = nullptr;
5166     if (Record->isUnion()) {
5167       // C++ [class.union]p6:
5168       // C++17 [class.union.anon]p2:
5169       //   Anonymous unions declared in a named namespace or in the
5170       //   global namespace shall be declared static.
5171       unsigned DiagID;
5172       DeclContext *OwnerScope = Owner->getRedeclContext();
5173       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5174           (OwnerScope->isTranslationUnit() ||
5175            (OwnerScope->isNamespace() &&
5176             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5177         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5178           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5179 
5180         // Recover by adding 'static'.
5181         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5182                                PrevSpec, DiagID, Policy);
5183       }
5184       // C++ [class.union]p6:
5185       //   A storage class is not allowed in a declaration of an
5186       //   anonymous union in a class scope.
5187       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5188                isa<RecordDecl>(Owner)) {
5189         Diag(DS.getStorageClassSpecLoc(),
5190              diag::err_anonymous_union_with_storage_spec)
5191           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5192 
5193         // Recover by removing the storage specifier.
5194         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5195                                SourceLocation(),
5196                                PrevSpec, DiagID, Context.getPrintingPolicy());
5197       }
5198     }
5199 
5200     // Ignore const/volatile/restrict qualifiers.
5201     if (DS.getTypeQualifiers()) {
5202       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5203         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5204           << Record->isUnion() << "const"
5205           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5206       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5207         Diag(DS.getVolatileSpecLoc(),
5208              diag::ext_anonymous_struct_union_qualified)
5209           << Record->isUnion() << "volatile"
5210           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5211       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5212         Diag(DS.getRestrictSpecLoc(),
5213              diag::ext_anonymous_struct_union_qualified)
5214           << Record->isUnion() << "restrict"
5215           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5216       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5217         Diag(DS.getAtomicSpecLoc(),
5218              diag::ext_anonymous_struct_union_qualified)
5219           << Record->isUnion() << "_Atomic"
5220           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5221       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5222         Diag(DS.getUnalignedSpecLoc(),
5223              diag::ext_anonymous_struct_union_qualified)
5224           << Record->isUnion() << "__unaligned"
5225           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5226 
5227       DS.ClearTypeQualifiers();
5228     }
5229 
5230     // C++ [class.union]p2:
5231     //   The member-specification of an anonymous union shall only
5232     //   define non-static data members. [Note: nested types and
5233     //   functions cannot be declared within an anonymous union. ]
5234     for (auto *Mem : Record->decls()) {
5235       // Ignore invalid declarations; we already diagnosed them.
5236       if (Mem->isInvalidDecl())
5237         continue;
5238 
5239       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5240         // C++ [class.union]p3:
5241         //   An anonymous union shall not have private or protected
5242         //   members (clause 11).
5243         assert(FD->getAccess() != AS_none);
5244         if (FD->getAccess() != AS_public) {
5245           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5246             << Record->isUnion() << (FD->getAccess() == AS_protected);
5247           Invalid = true;
5248         }
5249 
5250         // C++ [class.union]p1
5251         //   An object of a class with a non-trivial constructor, a non-trivial
5252         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5253         //   assignment operator cannot be a member of a union, nor can an
5254         //   array of such objects.
5255         if (CheckNontrivialField(FD))
5256           Invalid = true;
5257       } else if (Mem->isImplicit()) {
5258         // Any implicit members are fine.
5259       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5260         // This is a type that showed up in an
5261         // elaborated-type-specifier inside the anonymous struct or
5262         // union, but which actually declares a type outside of the
5263         // anonymous struct or union. It's okay.
5264       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5265         if (!MemRecord->isAnonymousStructOrUnion() &&
5266             MemRecord->getDeclName()) {
5267           // Visual C++ allows type definition in anonymous struct or union.
5268           if (getLangOpts().MicrosoftExt)
5269             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5270               << Record->isUnion();
5271           else {
5272             // This is a nested type declaration.
5273             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5274               << Record->isUnion();
5275             Invalid = true;
5276           }
5277         } else {
5278           // This is an anonymous type definition within another anonymous type.
5279           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5280           // not part of standard C++.
5281           Diag(MemRecord->getLocation(),
5282                diag::ext_anonymous_record_with_anonymous_type)
5283             << Record->isUnion();
5284         }
5285       } else if (isa<AccessSpecDecl>(Mem)) {
5286         // Any access specifier is fine.
5287       } else if (isa<StaticAssertDecl>(Mem)) {
5288         // In C++1z, static_assert declarations are also fine.
5289       } else {
5290         // We have something that isn't a non-static data
5291         // member. Complain about it.
5292         unsigned DK = diag::err_anonymous_record_bad_member;
5293         if (isa<TypeDecl>(Mem))
5294           DK = diag::err_anonymous_record_with_type;
5295         else if (isa<FunctionDecl>(Mem))
5296           DK = diag::err_anonymous_record_with_function;
5297         else if (isa<VarDecl>(Mem))
5298           DK = diag::err_anonymous_record_with_static;
5299 
5300         // Visual C++ allows type definition in anonymous struct or union.
5301         if (getLangOpts().MicrosoftExt &&
5302             DK == diag::err_anonymous_record_with_type)
5303           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5304             << Record->isUnion();
5305         else {
5306           Diag(Mem->getLocation(), DK) << Record->isUnion();
5307           Invalid = true;
5308         }
5309       }
5310     }
5311 
5312     // C++11 [class.union]p8 (DR1460):
5313     //   At most one variant member of a union may have a
5314     //   brace-or-equal-initializer.
5315     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5316         Owner->isRecord())
5317       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5318                                 cast<CXXRecordDecl>(Record));
5319   }
5320 
5321   if (!Record->isUnion() && !Owner->isRecord()) {
5322     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5323       << getLangOpts().CPlusPlus;
5324     Invalid = true;
5325   }
5326 
5327   // C++ [dcl.dcl]p3:
5328   //   [If there are no declarators], and except for the declaration of an
5329   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5330   //   names into the program
5331   // C++ [class.mem]p2:
5332   //   each such member-declaration shall either declare at least one member
5333   //   name of the class or declare at least one unnamed bit-field
5334   //
5335   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5336   if (getLangOpts().CPlusPlus && Record->field_empty())
5337     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5338 
5339   // Mock up a declarator.
5340   Declarator Dc(DS, DeclaratorContext::Member);
5341   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5342   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5343 
5344   // Create a declaration for this anonymous struct/union.
5345   NamedDecl *Anon = nullptr;
5346   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5347     Anon = FieldDecl::Create(
5348         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5349         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5350         /*BitWidth=*/nullptr, /*Mutable=*/false,
5351         /*InitStyle=*/ICIS_NoInit);
5352     Anon->setAccess(AS);
5353     ProcessDeclAttributes(S, Anon, Dc);
5354 
5355     if (getLangOpts().CPlusPlus)
5356       FieldCollector->Add(cast<FieldDecl>(Anon));
5357   } else {
5358     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5359     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5360     if (SCSpec == DeclSpec::SCS_mutable) {
5361       // mutable can only appear on non-static class members, so it's always
5362       // an error here
5363       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5364       Invalid = true;
5365       SC = SC_None;
5366     }
5367 
5368     assert(DS.getAttributes().empty() && "No attribute expected");
5369     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5370                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5371                            Context.getTypeDeclType(Record), TInfo, SC);
5372 
5373     // Default-initialize the implicit variable. This initialization will be
5374     // trivial in almost all cases, except if a union member has an in-class
5375     // initializer:
5376     //   union { int n = 0; };
5377     ActOnUninitializedDecl(Anon);
5378   }
5379   Anon->setImplicit();
5380 
5381   // Mark this as an anonymous struct/union type.
5382   Record->setAnonymousStructOrUnion(true);
5383 
5384   // Add the anonymous struct/union object to the current
5385   // context. We'll be referencing this object when we refer to one of
5386   // its members.
5387   Owner->addDecl(Anon);
5388 
5389   // Inject the members of the anonymous struct/union into the owning
5390   // context and into the identifier resolver chain for name lookup
5391   // purposes.
5392   SmallVector<NamedDecl*, 2> Chain;
5393   Chain.push_back(Anon);
5394 
5395   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5396     Invalid = true;
5397 
5398   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5399     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5400       MangleNumberingContext *MCtx;
5401       Decl *ManglingContextDecl;
5402       std::tie(MCtx, ManglingContextDecl) =
5403           getCurrentMangleNumberContext(NewVD->getDeclContext());
5404       if (MCtx) {
5405         Context.setManglingNumber(
5406             NewVD, MCtx->getManglingNumber(
5407                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5408         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5409       }
5410     }
5411   }
5412 
5413   if (Invalid)
5414     Anon->setInvalidDecl();
5415 
5416   return Anon;
5417 }
5418 
5419 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5420 /// Microsoft C anonymous structure.
5421 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5422 /// Example:
5423 ///
5424 /// struct A { int a; };
5425 /// struct B { struct A; int b; };
5426 ///
5427 /// void foo() {
5428 ///   B var;
5429 ///   var.a = 3;
5430 /// }
5431 ///
5432 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5433                                            RecordDecl *Record) {
5434   assert(Record && "expected a record!");
5435 
5436   // Mock up a declarator.
5437   Declarator Dc(DS, DeclaratorContext::TypeName);
5438   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5439   assert(TInfo && "couldn't build declarator info for anonymous struct");
5440 
5441   auto *ParentDecl = cast<RecordDecl>(CurContext);
5442   QualType RecTy = Context.getTypeDeclType(Record);
5443 
5444   // Create a declaration for this anonymous struct.
5445   NamedDecl *Anon =
5446       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5447                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5448                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5449                         /*InitStyle=*/ICIS_NoInit);
5450   Anon->setImplicit();
5451 
5452   // Add the anonymous struct object to the current context.
5453   CurContext->addDecl(Anon);
5454 
5455   // Inject the members of the anonymous struct into the current
5456   // context and into the identifier resolver chain for name lookup
5457   // purposes.
5458   SmallVector<NamedDecl*, 2> Chain;
5459   Chain.push_back(Anon);
5460 
5461   RecordDecl *RecordDef = Record->getDefinition();
5462   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5463                                diag::err_field_incomplete_or_sizeless) ||
5464       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5465                                           AS_none, Chain)) {
5466     Anon->setInvalidDecl();
5467     ParentDecl->setInvalidDecl();
5468   }
5469 
5470   return Anon;
5471 }
5472 
5473 /// GetNameForDeclarator - Determine the full declaration name for the
5474 /// given Declarator.
5475 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5476   return GetNameFromUnqualifiedId(D.getName());
5477 }
5478 
5479 /// Retrieves the declaration name from a parsed unqualified-id.
5480 DeclarationNameInfo
5481 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5482   DeclarationNameInfo NameInfo;
5483   NameInfo.setLoc(Name.StartLocation);
5484 
5485   switch (Name.getKind()) {
5486 
5487   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5488   case UnqualifiedIdKind::IK_Identifier:
5489     NameInfo.setName(Name.Identifier);
5490     return NameInfo;
5491 
5492   case UnqualifiedIdKind::IK_DeductionGuideName: {
5493     // C++ [temp.deduct.guide]p3:
5494     //   The simple-template-id shall name a class template specialization.
5495     //   The template-name shall be the same identifier as the template-name
5496     //   of the simple-template-id.
5497     // These together intend to imply that the template-name shall name a
5498     // class template.
5499     // FIXME: template<typename T> struct X {};
5500     //        template<typename T> using Y = X<T>;
5501     //        Y(int) -> Y<int>;
5502     //   satisfies these rules but does not name a class template.
5503     TemplateName TN = Name.TemplateName.get().get();
5504     auto *Template = TN.getAsTemplateDecl();
5505     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5506       Diag(Name.StartLocation,
5507            diag::err_deduction_guide_name_not_class_template)
5508         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5509       if (Template)
5510         Diag(Template->getLocation(), diag::note_template_decl_here);
5511       return DeclarationNameInfo();
5512     }
5513 
5514     NameInfo.setName(
5515         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5516     return NameInfo;
5517   }
5518 
5519   case UnqualifiedIdKind::IK_OperatorFunctionId:
5520     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5521                                            Name.OperatorFunctionId.Operator));
5522     NameInfo.setCXXOperatorNameRange(SourceRange(
5523         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5524     return NameInfo;
5525 
5526   case UnqualifiedIdKind::IK_LiteralOperatorId:
5527     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5528                                                            Name.Identifier));
5529     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5530     return NameInfo;
5531 
5532   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5533     TypeSourceInfo *TInfo;
5534     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5535     if (Ty.isNull())
5536       return DeclarationNameInfo();
5537     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5538                                                Context.getCanonicalType(Ty)));
5539     NameInfo.setNamedTypeInfo(TInfo);
5540     return NameInfo;
5541   }
5542 
5543   case UnqualifiedIdKind::IK_ConstructorName: {
5544     TypeSourceInfo *TInfo;
5545     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5546     if (Ty.isNull())
5547       return DeclarationNameInfo();
5548     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5549                                               Context.getCanonicalType(Ty)));
5550     NameInfo.setNamedTypeInfo(TInfo);
5551     return NameInfo;
5552   }
5553 
5554   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5555     // In well-formed code, we can only have a constructor
5556     // template-id that refers to the current context, so go there
5557     // to find the actual type being constructed.
5558     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5559     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5560       return DeclarationNameInfo();
5561 
5562     // Determine the type of the class being constructed.
5563     QualType CurClassType = Context.getTypeDeclType(CurClass);
5564 
5565     // FIXME: Check two things: that the template-id names the same type as
5566     // CurClassType, and that the template-id does not occur when the name
5567     // was qualified.
5568 
5569     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5570                                     Context.getCanonicalType(CurClassType)));
5571     // FIXME: should we retrieve TypeSourceInfo?
5572     NameInfo.setNamedTypeInfo(nullptr);
5573     return NameInfo;
5574   }
5575 
5576   case UnqualifiedIdKind::IK_DestructorName: {
5577     TypeSourceInfo *TInfo;
5578     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5579     if (Ty.isNull())
5580       return DeclarationNameInfo();
5581     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5582                                               Context.getCanonicalType(Ty)));
5583     NameInfo.setNamedTypeInfo(TInfo);
5584     return NameInfo;
5585   }
5586 
5587   case UnqualifiedIdKind::IK_TemplateId: {
5588     TemplateName TName = Name.TemplateId->Template.get();
5589     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5590     return Context.getNameForTemplate(TName, TNameLoc);
5591   }
5592 
5593   } // switch (Name.getKind())
5594 
5595   llvm_unreachable("Unknown name kind");
5596 }
5597 
5598 static QualType getCoreType(QualType Ty) {
5599   do {
5600     if (Ty->isPointerType() || Ty->isReferenceType())
5601       Ty = Ty->getPointeeType();
5602     else if (Ty->isArrayType())
5603       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5604     else
5605       return Ty.withoutLocalFastQualifiers();
5606   } while (true);
5607 }
5608 
5609 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5610 /// and Definition have "nearly" matching parameters. This heuristic is
5611 /// used to improve diagnostics in the case where an out-of-line function
5612 /// definition doesn't match any declaration within the class or namespace.
5613 /// Also sets Params to the list of indices to the parameters that differ
5614 /// between the declaration and the definition. If hasSimilarParameters
5615 /// returns true and Params is empty, then all of the parameters match.
5616 static bool hasSimilarParameters(ASTContext &Context,
5617                                      FunctionDecl *Declaration,
5618                                      FunctionDecl *Definition,
5619                                      SmallVectorImpl<unsigned> &Params) {
5620   Params.clear();
5621   if (Declaration->param_size() != Definition->param_size())
5622     return false;
5623   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5624     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5625     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5626 
5627     // The parameter types are identical
5628     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5629       continue;
5630 
5631     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5632     QualType DefParamBaseTy = getCoreType(DefParamTy);
5633     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5634     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5635 
5636     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5637         (DeclTyName && DeclTyName == DefTyName))
5638       Params.push_back(Idx);
5639     else  // The two parameters aren't even close
5640       return false;
5641   }
5642 
5643   return true;
5644 }
5645 
5646 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5647 /// declarator needs to be rebuilt in the current instantiation.
5648 /// Any bits of declarator which appear before the name are valid for
5649 /// consideration here.  That's specifically the type in the decl spec
5650 /// and the base type in any member-pointer chunks.
5651 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5652                                                     DeclarationName Name) {
5653   // The types we specifically need to rebuild are:
5654   //   - typenames, typeofs, and decltypes
5655   //   - types which will become injected class names
5656   // Of course, we also need to rebuild any type referencing such a
5657   // type.  It's safest to just say "dependent", but we call out a
5658   // few cases here.
5659 
5660   DeclSpec &DS = D.getMutableDeclSpec();
5661   switch (DS.getTypeSpecType()) {
5662   case DeclSpec::TST_typename:
5663   case DeclSpec::TST_typeofType:
5664   case DeclSpec::TST_underlyingType:
5665   case DeclSpec::TST_atomic: {
5666     // Grab the type from the parser.
5667     TypeSourceInfo *TSI = nullptr;
5668     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5669     if (T.isNull() || !T->isInstantiationDependentType()) break;
5670 
5671     // Make sure there's a type source info.  This isn't really much
5672     // of a waste; most dependent types should have type source info
5673     // attached already.
5674     if (!TSI)
5675       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5676 
5677     // Rebuild the type in the current instantiation.
5678     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5679     if (!TSI) return true;
5680 
5681     // Store the new type back in the decl spec.
5682     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5683     DS.UpdateTypeRep(LocType);
5684     break;
5685   }
5686 
5687   case DeclSpec::TST_decltype:
5688   case DeclSpec::TST_typeofExpr: {
5689     Expr *E = DS.getRepAsExpr();
5690     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5691     if (Result.isInvalid()) return true;
5692     DS.UpdateExprRep(Result.get());
5693     break;
5694   }
5695 
5696   default:
5697     // Nothing to do for these decl specs.
5698     break;
5699   }
5700 
5701   // It doesn't matter what order we do this in.
5702   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5703     DeclaratorChunk &Chunk = D.getTypeObject(I);
5704 
5705     // The only type information in the declarator which can come
5706     // before the declaration name is the base type of a member
5707     // pointer.
5708     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5709       continue;
5710 
5711     // Rebuild the scope specifier in-place.
5712     CXXScopeSpec &SS = Chunk.Mem.Scope();
5713     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5714       return true;
5715   }
5716 
5717   return false;
5718 }
5719 
5720 /// Returns true if the declaration is declared in a system header or from a
5721 /// system macro.
5722 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5723   return SM.isInSystemHeader(D->getLocation()) ||
5724          SM.isInSystemMacro(D->getLocation());
5725 }
5726 
5727 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5728   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5729   // of system decl.
5730   if (D->getPreviousDecl() || D->isImplicit())
5731     return;
5732   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5733   if (Status != ReservedIdentifierStatus::NotReserved &&
5734       !isFromSystemHeader(Context.getSourceManager(), D)) {
5735     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5736         << D << static_cast<int>(Status);
5737   }
5738 }
5739 
5740 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5741   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5742   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5743 
5744   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5745       Dcl && Dcl->getDeclContext()->isFileContext())
5746     Dcl->setTopLevelDeclInObjCContainer();
5747 
5748   return Dcl;
5749 }
5750 
5751 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5752 ///   If T is the name of a class, then each of the following shall have a
5753 ///   name different from T:
5754 ///     - every static data member of class T;
5755 ///     - every member function of class T
5756 ///     - every member of class T that is itself a type;
5757 /// \returns true if the declaration name violates these rules.
5758 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5759                                    DeclarationNameInfo NameInfo) {
5760   DeclarationName Name = NameInfo.getName();
5761 
5762   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5763   while (Record && Record->isAnonymousStructOrUnion())
5764     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5765   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5766     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5767     return true;
5768   }
5769 
5770   return false;
5771 }
5772 
5773 /// Diagnose a declaration whose declarator-id has the given
5774 /// nested-name-specifier.
5775 ///
5776 /// \param SS The nested-name-specifier of the declarator-id.
5777 ///
5778 /// \param DC The declaration context to which the nested-name-specifier
5779 /// resolves.
5780 ///
5781 /// \param Name The name of the entity being declared.
5782 ///
5783 /// \param Loc The location of the name of the entity being declared.
5784 ///
5785 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5786 /// we're declaring an explicit / partial specialization / instantiation.
5787 ///
5788 /// \returns true if we cannot safely recover from this error, false otherwise.
5789 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5790                                         DeclarationName Name,
5791                                         SourceLocation Loc, bool IsTemplateId) {
5792   DeclContext *Cur = CurContext;
5793   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5794     Cur = Cur->getParent();
5795 
5796   // If the user provided a superfluous scope specifier that refers back to the
5797   // class in which the entity is already declared, diagnose and ignore it.
5798   //
5799   // class X {
5800   //   void X::f();
5801   // };
5802   //
5803   // Note, it was once ill-formed to give redundant qualification in all
5804   // contexts, but that rule was removed by DR482.
5805   if (Cur->Equals(DC)) {
5806     if (Cur->isRecord()) {
5807       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5808                                       : diag::err_member_extra_qualification)
5809         << Name << FixItHint::CreateRemoval(SS.getRange());
5810       SS.clear();
5811     } else {
5812       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5813     }
5814     return false;
5815   }
5816 
5817   // Check whether the qualifying scope encloses the scope of the original
5818   // declaration. For a template-id, we perform the checks in
5819   // CheckTemplateSpecializationScope.
5820   if (!Cur->Encloses(DC) && !IsTemplateId) {
5821     if (Cur->isRecord())
5822       Diag(Loc, diag::err_member_qualification)
5823         << Name << SS.getRange();
5824     else if (isa<TranslationUnitDecl>(DC))
5825       Diag(Loc, diag::err_invalid_declarator_global_scope)
5826         << Name << SS.getRange();
5827     else if (isa<FunctionDecl>(Cur))
5828       Diag(Loc, diag::err_invalid_declarator_in_function)
5829         << Name << SS.getRange();
5830     else if (isa<BlockDecl>(Cur))
5831       Diag(Loc, diag::err_invalid_declarator_in_block)
5832         << Name << SS.getRange();
5833     else if (isa<ExportDecl>(Cur)) {
5834       if (!isa<NamespaceDecl>(DC))
5835         Diag(Loc, diag::err_export_non_namespace_scope_name)
5836             << Name << SS.getRange();
5837       else
5838         // The cases that DC is not NamespaceDecl should be handled in
5839         // CheckRedeclarationExported.
5840         return false;
5841     } else
5842       Diag(Loc, diag::err_invalid_declarator_scope)
5843       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5844 
5845     return true;
5846   }
5847 
5848   if (Cur->isRecord()) {
5849     // Cannot qualify members within a class.
5850     Diag(Loc, diag::err_member_qualification)
5851       << Name << SS.getRange();
5852     SS.clear();
5853 
5854     // C++ constructors and destructors with incorrect scopes can break
5855     // our AST invariants by having the wrong underlying types. If
5856     // that's the case, then drop this declaration entirely.
5857     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5858          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5859         !Context.hasSameType(Name.getCXXNameType(),
5860                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5861       return true;
5862 
5863     return false;
5864   }
5865 
5866   // C++11 [dcl.meaning]p1:
5867   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5868   //   not begin with a decltype-specifer"
5869   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5870   while (SpecLoc.getPrefix())
5871     SpecLoc = SpecLoc.getPrefix();
5872   if (isa_and_nonnull<DecltypeType>(
5873           SpecLoc.getNestedNameSpecifier()->getAsType()))
5874     Diag(Loc, diag::err_decltype_in_declarator)
5875       << SpecLoc.getTypeLoc().getSourceRange();
5876 
5877   return false;
5878 }
5879 
5880 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5881                                   MultiTemplateParamsArg TemplateParamLists) {
5882   // TODO: consider using NameInfo for diagnostic.
5883   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5884   DeclarationName Name = NameInfo.getName();
5885 
5886   // All of these full declarators require an identifier.  If it doesn't have
5887   // one, the ParsedFreeStandingDeclSpec action should be used.
5888   if (D.isDecompositionDeclarator()) {
5889     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5890   } else if (!Name) {
5891     if (!D.isInvalidType())  // Reject this if we think it is valid.
5892       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5893           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5894     return nullptr;
5895   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5896     return nullptr;
5897 
5898   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5899   // we find one that is.
5900   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5901          (S->getFlags() & Scope::TemplateParamScope) != 0)
5902     S = S->getParent();
5903 
5904   DeclContext *DC = CurContext;
5905   if (D.getCXXScopeSpec().isInvalid())
5906     D.setInvalidType();
5907   else if (D.getCXXScopeSpec().isSet()) {
5908     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5909                                         UPPC_DeclarationQualifier))
5910       return nullptr;
5911 
5912     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5913     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5914     if (!DC || isa<EnumDecl>(DC)) {
5915       // If we could not compute the declaration context, it's because the
5916       // declaration context is dependent but does not refer to a class,
5917       // class template, or class template partial specialization. Complain
5918       // and return early, to avoid the coming semantic disaster.
5919       Diag(D.getIdentifierLoc(),
5920            diag::err_template_qualified_declarator_no_match)
5921         << D.getCXXScopeSpec().getScopeRep()
5922         << D.getCXXScopeSpec().getRange();
5923       return nullptr;
5924     }
5925     bool IsDependentContext = DC->isDependentContext();
5926 
5927     if (!IsDependentContext &&
5928         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5929       return nullptr;
5930 
5931     // If a class is incomplete, do not parse entities inside it.
5932     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5933       Diag(D.getIdentifierLoc(),
5934            diag::err_member_def_undefined_record)
5935         << Name << DC << D.getCXXScopeSpec().getRange();
5936       return nullptr;
5937     }
5938     if (!D.getDeclSpec().isFriendSpecified()) {
5939       if (diagnoseQualifiedDeclaration(
5940               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5941               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5942         if (DC->isRecord())
5943           return nullptr;
5944 
5945         D.setInvalidType();
5946       }
5947     }
5948 
5949     // Check whether we need to rebuild the type of the given
5950     // declaration in the current instantiation.
5951     if (EnteringContext && IsDependentContext &&
5952         TemplateParamLists.size() != 0) {
5953       ContextRAII SavedContext(*this, DC);
5954       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5955         D.setInvalidType();
5956     }
5957   }
5958 
5959   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5960   QualType R = TInfo->getType();
5961 
5962   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5963                                       UPPC_DeclarationType))
5964     D.setInvalidType();
5965 
5966   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5967                         forRedeclarationInCurContext());
5968 
5969   // See if this is a redefinition of a variable in the same scope.
5970   if (!D.getCXXScopeSpec().isSet()) {
5971     bool IsLinkageLookup = false;
5972     bool CreateBuiltins = false;
5973 
5974     // If the declaration we're planning to build will be a function
5975     // or object with linkage, then look for another declaration with
5976     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5977     //
5978     // If the declaration we're planning to build will be declared with
5979     // external linkage in the translation unit, create any builtin with
5980     // the same name.
5981     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5982       /* Do nothing*/;
5983     else if (CurContext->isFunctionOrMethod() &&
5984              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5985               R->isFunctionType())) {
5986       IsLinkageLookup = true;
5987       CreateBuiltins =
5988           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5989     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5990                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5991       CreateBuiltins = true;
5992 
5993     if (IsLinkageLookup) {
5994       Previous.clear(LookupRedeclarationWithLinkage);
5995       Previous.setRedeclarationKind(ForExternalRedeclaration);
5996     }
5997 
5998     LookupName(Previous, S, CreateBuiltins);
5999   } else { // Something like "int foo::x;"
6000     LookupQualifiedName(Previous, DC);
6001 
6002     // C++ [dcl.meaning]p1:
6003     //   When the declarator-id is qualified, the declaration shall refer to a
6004     //  previously declared member of the class or namespace to which the
6005     //  qualifier refers (or, in the case of a namespace, of an element of the
6006     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6007     //  thereof; [...]
6008     //
6009     // Note that we already checked the context above, and that we do not have
6010     // enough information to make sure that Previous contains the declaration
6011     // we want to match. For example, given:
6012     //
6013     //   class X {
6014     //     void f();
6015     //     void f(float);
6016     //   };
6017     //
6018     //   void X::f(int) { } // ill-formed
6019     //
6020     // In this case, Previous will point to the overload set
6021     // containing the two f's declared in X, but neither of them
6022     // matches.
6023 
6024     // C++ [dcl.meaning]p1:
6025     //   [...] the member shall not merely have been introduced by a
6026     //   using-declaration in the scope of the class or namespace nominated by
6027     //   the nested-name-specifier of the declarator-id.
6028     RemoveUsingDecls(Previous);
6029   }
6030 
6031   if (Previous.isSingleResult() &&
6032       Previous.getFoundDecl()->isTemplateParameter()) {
6033     // Maybe we will complain about the shadowed template parameter.
6034     if (!D.isInvalidType())
6035       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6036                                       Previous.getFoundDecl());
6037 
6038     // Just pretend that we didn't see the previous declaration.
6039     Previous.clear();
6040   }
6041 
6042   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6043     // Forget that the previous declaration is the injected-class-name.
6044     Previous.clear();
6045 
6046   // In C++, the previous declaration we find might be a tag type
6047   // (class or enum). In this case, the new declaration will hide the
6048   // tag type. Note that this applies to functions, function templates, and
6049   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6050   if (Previous.isSingleTagDecl() &&
6051       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6052       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6053     Previous.clear();
6054 
6055   // Check that there are no default arguments other than in the parameters
6056   // of a function declaration (C++ only).
6057   if (getLangOpts().CPlusPlus)
6058     CheckExtraCXXDefaultArguments(D);
6059 
6060   NamedDecl *New;
6061 
6062   bool AddToScope = true;
6063   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6064     if (TemplateParamLists.size()) {
6065       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6066       return nullptr;
6067     }
6068 
6069     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6070   } else if (R->isFunctionType()) {
6071     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6072                                   TemplateParamLists,
6073                                   AddToScope);
6074   } else {
6075     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6076                                   AddToScope);
6077   }
6078 
6079   if (!New)
6080     return nullptr;
6081 
6082   // If this has an identifier and is not a function template specialization,
6083   // add it to the scope stack.
6084   if (New->getDeclName() && AddToScope)
6085     PushOnScopeChains(New, S);
6086 
6087   if (isInOpenMPDeclareTargetContext())
6088     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6089 
6090   return New;
6091 }
6092 
6093 /// Helper method to turn variable array types into constant array
6094 /// types in certain situations which would otherwise be errors (for
6095 /// GCC compatibility).
6096 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6097                                                     ASTContext &Context,
6098                                                     bool &SizeIsNegative,
6099                                                     llvm::APSInt &Oversized) {
6100   // This method tries to turn a variable array into a constant
6101   // array even when the size isn't an ICE.  This is necessary
6102   // for compatibility with code that depends on gcc's buggy
6103   // constant expression folding, like struct {char x[(int)(char*)2];}
6104   SizeIsNegative = false;
6105   Oversized = 0;
6106 
6107   if (T->isDependentType())
6108     return QualType();
6109 
6110   QualifierCollector Qs;
6111   const Type *Ty = Qs.strip(T);
6112 
6113   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6114     QualType Pointee = PTy->getPointeeType();
6115     QualType FixedType =
6116         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6117                                             Oversized);
6118     if (FixedType.isNull()) return FixedType;
6119     FixedType = Context.getPointerType(FixedType);
6120     return Qs.apply(Context, FixedType);
6121   }
6122   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6123     QualType Inner = PTy->getInnerType();
6124     QualType FixedType =
6125         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6126                                             Oversized);
6127     if (FixedType.isNull()) return FixedType;
6128     FixedType = Context.getParenType(FixedType);
6129     return Qs.apply(Context, FixedType);
6130   }
6131 
6132   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6133   if (!VLATy)
6134     return QualType();
6135 
6136   QualType ElemTy = VLATy->getElementType();
6137   if (ElemTy->isVariablyModifiedType()) {
6138     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6139                                                  SizeIsNegative, Oversized);
6140     if (ElemTy.isNull())
6141       return QualType();
6142   }
6143 
6144   Expr::EvalResult Result;
6145   if (!VLATy->getSizeExpr() ||
6146       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6147     return QualType();
6148 
6149   llvm::APSInt Res = Result.Val.getInt();
6150 
6151   // Check whether the array size is negative.
6152   if (Res.isSigned() && Res.isNegative()) {
6153     SizeIsNegative = true;
6154     return QualType();
6155   }
6156 
6157   // Check whether the array is too large to be addressed.
6158   unsigned ActiveSizeBits =
6159       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6160        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6161           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6162           : Res.getActiveBits();
6163   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6164     Oversized = Res;
6165     return QualType();
6166   }
6167 
6168   QualType FoldedArrayType = Context.getConstantArrayType(
6169       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6170   return Qs.apply(Context, FoldedArrayType);
6171 }
6172 
6173 static void
6174 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6175   SrcTL = SrcTL.getUnqualifiedLoc();
6176   DstTL = DstTL.getUnqualifiedLoc();
6177   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6178     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6179     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6180                                       DstPTL.getPointeeLoc());
6181     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6182     return;
6183   }
6184   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6185     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6186     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6187                                       DstPTL.getInnerLoc());
6188     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6189     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6190     return;
6191   }
6192   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6193   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6194   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6195   TypeLoc DstElemTL = DstATL.getElementLoc();
6196   if (VariableArrayTypeLoc SrcElemATL =
6197           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6198     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6199     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6200   } else {
6201     DstElemTL.initializeFullCopy(SrcElemTL);
6202   }
6203   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6204   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6205   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6206 }
6207 
6208 /// Helper method to turn variable array types into constant array
6209 /// types in certain situations which would otherwise be errors (for
6210 /// GCC compatibility).
6211 static TypeSourceInfo*
6212 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6213                                               ASTContext &Context,
6214                                               bool &SizeIsNegative,
6215                                               llvm::APSInt &Oversized) {
6216   QualType FixedTy
6217     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6218                                           SizeIsNegative, Oversized);
6219   if (FixedTy.isNull())
6220     return nullptr;
6221   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6222   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6223                                     FixedTInfo->getTypeLoc());
6224   return FixedTInfo;
6225 }
6226 
6227 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6228 /// true if we were successful.
6229 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6230                                            QualType &T, SourceLocation Loc,
6231                                            unsigned FailedFoldDiagID) {
6232   bool SizeIsNegative;
6233   llvm::APSInt Oversized;
6234   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6235       TInfo, Context, SizeIsNegative, Oversized);
6236   if (FixedTInfo) {
6237     Diag(Loc, diag::ext_vla_folded_to_constant);
6238     TInfo = FixedTInfo;
6239     T = FixedTInfo->getType();
6240     return true;
6241   }
6242 
6243   if (SizeIsNegative)
6244     Diag(Loc, diag::err_typecheck_negative_array_size);
6245   else if (Oversized.getBoolValue())
6246     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6247   else if (FailedFoldDiagID)
6248     Diag(Loc, FailedFoldDiagID);
6249   return false;
6250 }
6251 
6252 /// Register the given locally-scoped extern "C" declaration so
6253 /// that it can be found later for redeclarations. We include any extern "C"
6254 /// declaration that is not visible in the translation unit here, not just
6255 /// function-scope declarations.
6256 void
6257 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6258   if (!getLangOpts().CPlusPlus &&
6259       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6260     // Don't need to track declarations in the TU in C.
6261     return;
6262 
6263   // Note that we have a locally-scoped external with this name.
6264   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6265 }
6266 
6267 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6268   // FIXME: We can have multiple results via __attribute__((overloadable)).
6269   auto Result = Context.getExternCContextDecl()->lookup(Name);
6270   return Result.empty() ? nullptr : *Result.begin();
6271 }
6272 
6273 /// Diagnose function specifiers on a declaration of an identifier that
6274 /// does not identify a function.
6275 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6276   // FIXME: We should probably indicate the identifier in question to avoid
6277   // confusion for constructs like "virtual int a(), b;"
6278   if (DS.isVirtualSpecified())
6279     Diag(DS.getVirtualSpecLoc(),
6280          diag::err_virtual_non_function);
6281 
6282   if (DS.hasExplicitSpecifier())
6283     Diag(DS.getExplicitSpecLoc(),
6284          diag::err_explicit_non_function);
6285 
6286   if (DS.isNoreturnSpecified())
6287     Diag(DS.getNoreturnSpecLoc(),
6288          diag::err_noreturn_non_function);
6289 }
6290 
6291 NamedDecl*
6292 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6293                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6294   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6295   if (D.getCXXScopeSpec().isSet()) {
6296     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6297       << D.getCXXScopeSpec().getRange();
6298     D.setInvalidType();
6299     // Pretend we didn't see the scope specifier.
6300     DC = CurContext;
6301     Previous.clear();
6302   }
6303 
6304   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6305 
6306   if (D.getDeclSpec().isInlineSpecified())
6307     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6308         << getLangOpts().CPlusPlus17;
6309   if (D.getDeclSpec().hasConstexprSpecifier())
6310     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6311         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6312 
6313   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6314     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6315       Diag(D.getName().StartLocation,
6316            diag::err_deduction_guide_invalid_specifier)
6317           << "typedef";
6318     else
6319       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6320           << D.getName().getSourceRange();
6321     return nullptr;
6322   }
6323 
6324   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6325   if (!NewTD) return nullptr;
6326 
6327   // Handle attributes prior to checking for duplicates in MergeVarDecl
6328   ProcessDeclAttributes(S, NewTD, D);
6329 
6330   CheckTypedefForVariablyModifiedType(S, NewTD);
6331 
6332   bool Redeclaration = D.isRedeclaration();
6333   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6334   D.setRedeclaration(Redeclaration);
6335   return ND;
6336 }
6337 
6338 void
6339 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6340   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6341   // then it shall have block scope.
6342   // Note that variably modified types must be fixed before merging the decl so
6343   // that redeclarations will match.
6344   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6345   QualType T = TInfo->getType();
6346   if (T->isVariablyModifiedType()) {
6347     setFunctionHasBranchProtectedScope();
6348 
6349     if (S->getFnParent() == nullptr) {
6350       bool SizeIsNegative;
6351       llvm::APSInt Oversized;
6352       TypeSourceInfo *FixedTInfo =
6353         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6354                                                       SizeIsNegative,
6355                                                       Oversized);
6356       if (FixedTInfo) {
6357         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6358         NewTD->setTypeSourceInfo(FixedTInfo);
6359       } else {
6360         if (SizeIsNegative)
6361           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6362         else if (T->isVariableArrayType())
6363           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6364         else if (Oversized.getBoolValue())
6365           Diag(NewTD->getLocation(), diag::err_array_too_large)
6366             << toString(Oversized, 10);
6367         else
6368           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6369         NewTD->setInvalidDecl();
6370       }
6371     }
6372   }
6373 }
6374 
6375 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6376 /// declares a typedef-name, either using the 'typedef' type specifier or via
6377 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6378 NamedDecl*
6379 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6380                            LookupResult &Previous, bool &Redeclaration) {
6381 
6382   // Find the shadowed declaration before filtering for scope.
6383   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6384 
6385   // Merge the decl with the existing one if appropriate. If the decl is
6386   // in an outer scope, it isn't the same thing.
6387   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6388                        /*AllowInlineNamespace*/false);
6389   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6390   if (!Previous.empty()) {
6391     Redeclaration = true;
6392     MergeTypedefNameDecl(S, NewTD, Previous);
6393   } else {
6394     inferGslPointerAttribute(NewTD);
6395   }
6396 
6397   if (ShadowedDecl && !Redeclaration)
6398     CheckShadow(NewTD, ShadowedDecl, Previous);
6399 
6400   // If this is the C FILE type, notify the AST context.
6401   if (IdentifierInfo *II = NewTD->getIdentifier())
6402     if (!NewTD->isInvalidDecl() &&
6403         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6404       if (II->isStr("FILE"))
6405         Context.setFILEDecl(NewTD);
6406       else if (II->isStr("jmp_buf"))
6407         Context.setjmp_bufDecl(NewTD);
6408       else if (II->isStr("sigjmp_buf"))
6409         Context.setsigjmp_bufDecl(NewTD);
6410       else if (II->isStr("ucontext_t"))
6411         Context.setucontext_tDecl(NewTD);
6412     }
6413 
6414   return NewTD;
6415 }
6416 
6417 /// Determines whether the given declaration is an out-of-scope
6418 /// previous declaration.
6419 ///
6420 /// This routine should be invoked when name lookup has found a
6421 /// previous declaration (PrevDecl) that is not in the scope where a
6422 /// new declaration by the same name is being introduced. If the new
6423 /// declaration occurs in a local scope, previous declarations with
6424 /// linkage may still be considered previous declarations (C99
6425 /// 6.2.2p4-5, C++ [basic.link]p6).
6426 ///
6427 /// \param PrevDecl the previous declaration found by name
6428 /// lookup
6429 ///
6430 /// \param DC the context in which the new declaration is being
6431 /// declared.
6432 ///
6433 /// \returns true if PrevDecl is an out-of-scope previous declaration
6434 /// for a new delcaration with the same name.
6435 static bool
6436 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6437                                 ASTContext &Context) {
6438   if (!PrevDecl)
6439     return false;
6440 
6441   if (!PrevDecl->hasLinkage())
6442     return false;
6443 
6444   if (Context.getLangOpts().CPlusPlus) {
6445     // C++ [basic.link]p6:
6446     //   If there is a visible declaration of an entity with linkage
6447     //   having the same name and type, ignoring entities declared
6448     //   outside the innermost enclosing namespace scope, the block
6449     //   scope declaration declares that same entity and receives the
6450     //   linkage of the previous declaration.
6451     DeclContext *OuterContext = DC->getRedeclContext();
6452     if (!OuterContext->isFunctionOrMethod())
6453       // This rule only applies to block-scope declarations.
6454       return false;
6455 
6456     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6457     if (PrevOuterContext->isRecord())
6458       // We found a member function: ignore it.
6459       return false;
6460 
6461     // Find the innermost enclosing namespace for the new and
6462     // previous declarations.
6463     OuterContext = OuterContext->getEnclosingNamespaceContext();
6464     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6465 
6466     // The previous declaration is in a different namespace, so it
6467     // isn't the same function.
6468     if (!OuterContext->Equals(PrevOuterContext))
6469       return false;
6470   }
6471 
6472   return true;
6473 }
6474 
6475 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6476   CXXScopeSpec &SS = D.getCXXScopeSpec();
6477   if (!SS.isSet()) return;
6478   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6479 }
6480 
6481 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6482   QualType type = decl->getType();
6483   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6484   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6485     // Various kinds of declaration aren't allowed to be __autoreleasing.
6486     unsigned kind = -1U;
6487     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6488       if (var->hasAttr<BlocksAttr>())
6489         kind = 0; // __block
6490       else if (!var->hasLocalStorage())
6491         kind = 1; // global
6492     } else if (isa<ObjCIvarDecl>(decl)) {
6493       kind = 3; // ivar
6494     } else if (isa<FieldDecl>(decl)) {
6495       kind = 2; // field
6496     }
6497 
6498     if (kind != -1U) {
6499       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6500         << kind;
6501     }
6502   } else if (lifetime == Qualifiers::OCL_None) {
6503     // Try to infer lifetime.
6504     if (!type->isObjCLifetimeType())
6505       return false;
6506 
6507     lifetime = type->getObjCARCImplicitLifetime();
6508     type = Context.getLifetimeQualifiedType(type, lifetime);
6509     decl->setType(type);
6510   }
6511 
6512   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6513     // Thread-local variables cannot have lifetime.
6514     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6515         var->getTLSKind()) {
6516       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6517         << var->getType();
6518       return true;
6519     }
6520   }
6521 
6522   return false;
6523 }
6524 
6525 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6526   if (Decl->getType().hasAddressSpace())
6527     return;
6528   if (Decl->getType()->isDependentType())
6529     return;
6530   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6531     QualType Type = Var->getType();
6532     if (Type->isSamplerT() || Type->isVoidType())
6533       return;
6534     LangAS ImplAS = LangAS::opencl_private;
6535     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6536     // __opencl_c_program_scope_global_variables feature, the address space
6537     // for a variable at program scope or a static or extern variable inside
6538     // a function are inferred to be __global.
6539     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6540         Var->hasGlobalStorage())
6541       ImplAS = LangAS::opencl_global;
6542     // If the original type from a decayed type is an array type and that array
6543     // type has no address space yet, deduce it now.
6544     if (auto DT = dyn_cast<DecayedType>(Type)) {
6545       auto OrigTy = DT->getOriginalType();
6546       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6547         // Add the address space to the original array type and then propagate
6548         // that to the element type through `getAsArrayType`.
6549         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6550         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6551         // Re-generate the decayed type.
6552         Type = Context.getDecayedType(OrigTy);
6553       }
6554     }
6555     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6556     // Apply any qualifiers (including address space) from the array type to
6557     // the element type. This implements C99 6.7.3p8: "If the specification of
6558     // an array type includes any type qualifiers, the element type is so
6559     // qualified, not the array type."
6560     if (Type->isArrayType())
6561       Type = QualType(Context.getAsArrayType(Type), 0);
6562     Decl->setType(Type);
6563   }
6564 }
6565 
6566 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6567   // Ensure that an auto decl is deduced otherwise the checks below might cache
6568   // the wrong linkage.
6569   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6570 
6571   // 'weak' only applies to declarations with external linkage.
6572   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6573     if (!ND.isExternallyVisible()) {
6574       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6575       ND.dropAttr<WeakAttr>();
6576     }
6577   }
6578   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6579     if (ND.isExternallyVisible()) {
6580       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6581       ND.dropAttr<WeakRefAttr>();
6582       ND.dropAttr<AliasAttr>();
6583     }
6584   }
6585 
6586   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6587     if (VD->hasInit()) {
6588       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6589         assert(VD->isThisDeclarationADefinition() &&
6590                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6591         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6592         VD->dropAttr<AliasAttr>();
6593       }
6594     }
6595   }
6596 
6597   // 'selectany' only applies to externally visible variable declarations.
6598   // It does not apply to functions.
6599   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6600     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6601       S.Diag(Attr->getLocation(),
6602              diag::err_attribute_selectany_non_extern_data);
6603       ND.dropAttr<SelectAnyAttr>();
6604     }
6605   }
6606 
6607   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6608     auto *VD = dyn_cast<VarDecl>(&ND);
6609     bool IsAnonymousNS = false;
6610     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6611     if (VD) {
6612       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6613       while (NS && !IsAnonymousNS) {
6614         IsAnonymousNS = NS->isAnonymousNamespace();
6615         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6616       }
6617     }
6618     // dll attributes require external linkage. Static locals may have external
6619     // linkage but still cannot be explicitly imported or exported.
6620     // In Microsoft mode, a variable defined in anonymous namespace must have
6621     // external linkage in order to be exported.
6622     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6623     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6624         (!AnonNSInMicrosoftMode &&
6625          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6626       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6627         << &ND << Attr;
6628       ND.setInvalidDecl();
6629     }
6630   }
6631 
6632   // Check the attributes on the function type, if any.
6633   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6634     // Don't declare this variable in the second operand of the for-statement;
6635     // GCC miscompiles that by ending its lifetime before evaluating the
6636     // third operand. See gcc.gnu.org/PR86769.
6637     AttributedTypeLoc ATL;
6638     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6639          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6640          TL = ATL.getModifiedLoc()) {
6641       // The [[lifetimebound]] attribute can be applied to the implicit object
6642       // parameter of a non-static member function (other than a ctor or dtor)
6643       // by applying it to the function type.
6644       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6645         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6646         if (!MD || MD->isStatic()) {
6647           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6648               << !MD << A->getRange();
6649         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6650           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6651               << isa<CXXDestructorDecl>(MD) << A->getRange();
6652         }
6653       }
6654     }
6655   }
6656 }
6657 
6658 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6659                                            NamedDecl *NewDecl,
6660                                            bool IsSpecialization,
6661                                            bool IsDefinition) {
6662   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6663     return;
6664 
6665   bool IsTemplate = false;
6666   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6667     OldDecl = OldTD->getTemplatedDecl();
6668     IsTemplate = true;
6669     if (!IsSpecialization)
6670       IsDefinition = false;
6671   }
6672   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6673     NewDecl = NewTD->getTemplatedDecl();
6674     IsTemplate = true;
6675   }
6676 
6677   if (!OldDecl || !NewDecl)
6678     return;
6679 
6680   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6681   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6682   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6683   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6684 
6685   // dllimport and dllexport are inheritable attributes so we have to exclude
6686   // inherited attribute instances.
6687   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6688                     (NewExportAttr && !NewExportAttr->isInherited());
6689 
6690   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6691   // the only exception being explicit specializations.
6692   // Implicitly generated declarations are also excluded for now because there
6693   // is no other way to switch these to use dllimport or dllexport.
6694   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6695 
6696   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6697     // Allow with a warning for free functions and global variables.
6698     bool JustWarn = false;
6699     if (!OldDecl->isCXXClassMember()) {
6700       auto *VD = dyn_cast<VarDecl>(OldDecl);
6701       if (VD && !VD->getDescribedVarTemplate())
6702         JustWarn = true;
6703       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6704       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6705         JustWarn = true;
6706     }
6707 
6708     // We cannot change a declaration that's been used because IR has already
6709     // been emitted. Dllimported functions will still work though (modulo
6710     // address equality) as they can use the thunk.
6711     if (OldDecl->isUsed())
6712       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6713         JustWarn = false;
6714 
6715     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6716                                : diag::err_attribute_dll_redeclaration;
6717     S.Diag(NewDecl->getLocation(), DiagID)
6718         << NewDecl
6719         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6720     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6721     if (!JustWarn) {
6722       NewDecl->setInvalidDecl();
6723       return;
6724     }
6725   }
6726 
6727   // A redeclaration is not allowed to drop a dllimport attribute, the only
6728   // exceptions being inline function definitions (except for function
6729   // templates), local extern declarations, qualified friend declarations or
6730   // special MSVC extension: in the last case, the declaration is treated as if
6731   // it were marked dllexport.
6732   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6733   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6734   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6735     // Ignore static data because out-of-line definitions are diagnosed
6736     // separately.
6737     IsStaticDataMember = VD->isStaticDataMember();
6738     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6739                    VarDecl::DeclarationOnly;
6740   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6741     IsInline = FD->isInlined();
6742     IsQualifiedFriend = FD->getQualifier() &&
6743                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6744   }
6745 
6746   if (OldImportAttr && !HasNewAttr &&
6747       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6748       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6749     if (IsMicrosoftABI && IsDefinition) {
6750       S.Diag(NewDecl->getLocation(),
6751              diag::warn_redeclaration_without_import_attribute)
6752           << NewDecl;
6753       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6754       NewDecl->dropAttr<DLLImportAttr>();
6755       NewDecl->addAttr(
6756           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6757     } else {
6758       S.Diag(NewDecl->getLocation(),
6759              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6760           << NewDecl << OldImportAttr;
6761       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6762       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6763       OldDecl->dropAttr<DLLImportAttr>();
6764       NewDecl->dropAttr<DLLImportAttr>();
6765     }
6766   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6767     // In MinGW, seeing a function declared inline drops the dllimport
6768     // attribute.
6769     OldDecl->dropAttr<DLLImportAttr>();
6770     NewDecl->dropAttr<DLLImportAttr>();
6771     S.Diag(NewDecl->getLocation(),
6772            diag::warn_dllimport_dropped_from_inline_function)
6773         << NewDecl << OldImportAttr;
6774   }
6775 
6776   // A specialization of a class template member function is processed here
6777   // since it's a redeclaration. If the parent class is dllexport, the
6778   // specialization inherits that attribute. This doesn't happen automatically
6779   // since the parent class isn't instantiated until later.
6780   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6781     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6782         !NewImportAttr && !NewExportAttr) {
6783       if (const DLLExportAttr *ParentExportAttr =
6784               MD->getParent()->getAttr<DLLExportAttr>()) {
6785         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6786         NewAttr->setInherited(true);
6787         NewDecl->addAttr(NewAttr);
6788       }
6789     }
6790   }
6791 }
6792 
6793 /// Given that we are within the definition of the given function,
6794 /// will that definition behave like C99's 'inline', where the
6795 /// definition is discarded except for optimization purposes?
6796 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6797   // Try to avoid calling GetGVALinkageForFunction.
6798 
6799   // All cases of this require the 'inline' keyword.
6800   if (!FD->isInlined()) return false;
6801 
6802   // This is only possible in C++ with the gnu_inline attribute.
6803   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6804     return false;
6805 
6806   // Okay, go ahead and call the relatively-more-expensive function.
6807   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6808 }
6809 
6810 /// Determine whether a variable is extern "C" prior to attaching
6811 /// an initializer. We can't just call isExternC() here, because that
6812 /// will also compute and cache whether the declaration is externally
6813 /// visible, which might change when we attach the initializer.
6814 ///
6815 /// This can only be used if the declaration is known to not be a
6816 /// redeclaration of an internal linkage declaration.
6817 ///
6818 /// For instance:
6819 ///
6820 ///   auto x = []{};
6821 ///
6822 /// Attaching the initializer here makes this declaration not externally
6823 /// visible, because its type has internal linkage.
6824 ///
6825 /// FIXME: This is a hack.
6826 template<typename T>
6827 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6828   if (S.getLangOpts().CPlusPlus) {
6829     // In C++, the overloadable attribute negates the effects of extern "C".
6830     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6831       return false;
6832 
6833     // So do CUDA's host/device attributes.
6834     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6835                                  D->template hasAttr<CUDAHostAttr>()))
6836       return false;
6837   }
6838   return D->isExternC();
6839 }
6840 
6841 static bool shouldConsiderLinkage(const VarDecl *VD) {
6842   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6843   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6844       isa<OMPDeclareMapperDecl>(DC))
6845     return VD->hasExternalStorage();
6846   if (DC->isFileContext())
6847     return true;
6848   if (DC->isRecord())
6849     return false;
6850   if (isa<RequiresExprBodyDecl>(DC))
6851     return false;
6852   llvm_unreachable("Unexpected context");
6853 }
6854 
6855 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6856   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6857   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6858       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6859     return true;
6860   if (DC->isRecord())
6861     return false;
6862   llvm_unreachable("Unexpected context");
6863 }
6864 
6865 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6866                           ParsedAttr::Kind Kind) {
6867   // Check decl attributes on the DeclSpec.
6868   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6869     return true;
6870 
6871   // Walk the declarator structure, checking decl attributes that were in a type
6872   // position to the decl itself.
6873   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6874     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6875       return true;
6876   }
6877 
6878   // Finally, check attributes on the decl itself.
6879   return PD.getAttributes().hasAttribute(Kind);
6880 }
6881 
6882 /// Adjust the \c DeclContext for a function or variable that might be a
6883 /// function-local external declaration.
6884 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6885   if (!DC->isFunctionOrMethod())
6886     return false;
6887 
6888   // If this is a local extern function or variable declared within a function
6889   // template, don't add it into the enclosing namespace scope until it is
6890   // instantiated; it might have a dependent type right now.
6891   if (DC->isDependentContext())
6892     return true;
6893 
6894   // C++11 [basic.link]p7:
6895   //   When a block scope declaration of an entity with linkage is not found to
6896   //   refer to some other declaration, then that entity is a member of the
6897   //   innermost enclosing namespace.
6898   //
6899   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6900   // semantically-enclosing namespace, not a lexically-enclosing one.
6901   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6902     DC = DC->getParent();
6903   return true;
6904 }
6905 
6906 /// Returns true if given declaration has external C language linkage.
6907 static bool isDeclExternC(const Decl *D) {
6908   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6909     return FD->isExternC();
6910   if (const auto *VD = dyn_cast<VarDecl>(D))
6911     return VD->isExternC();
6912 
6913   llvm_unreachable("Unknown type of decl!");
6914 }
6915 
6916 /// Returns true if there hasn't been any invalid type diagnosed.
6917 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6918   DeclContext *DC = NewVD->getDeclContext();
6919   QualType R = NewVD->getType();
6920 
6921   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6922   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6923   // argument.
6924   if (R->isImageType() || R->isPipeType()) {
6925     Se.Diag(NewVD->getLocation(),
6926             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6927         << R;
6928     NewVD->setInvalidDecl();
6929     return false;
6930   }
6931 
6932   // OpenCL v1.2 s6.9.r:
6933   // The event type cannot be used to declare a program scope variable.
6934   // OpenCL v2.0 s6.9.q:
6935   // The clk_event_t and reserve_id_t types cannot be declared in program
6936   // scope.
6937   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6938     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6939       Se.Diag(NewVD->getLocation(),
6940               diag::err_invalid_type_for_program_scope_var)
6941           << R;
6942       NewVD->setInvalidDecl();
6943       return false;
6944     }
6945   }
6946 
6947   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6948   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6949                                                Se.getLangOpts())) {
6950     QualType NR = R.getCanonicalType();
6951     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6952            NR->isReferenceType()) {
6953       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6954           NR->isFunctionReferenceType()) {
6955         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6956             << NR->isReferenceType();
6957         NewVD->setInvalidDecl();
6958         return false;
6959       }
6960       NR = NR->getPointeeType();
6961     }
6962   }
6963 
6964   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6965                                                Se.getLangOpts())) {
6966     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6967     // half array type (unless the cl_khr_fp16 extension is enabled).
6968     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6969       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6970       NewVD->setInvalidDecl();
6971       return false;
6972     }
6973   }
6974 
6975   // OpenCL v1.2 s6.9.r:
6976   // The event type cannot be used with the __local, __constant and __global
6977   // address space qualifiers.
6978   if (R->isEventT()) {
6979     if (R.getAddressSpace() != LangAS::opencl_private) {
6980       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6981       NewVD->setInvalidDecl();
6982       return false;
6983     }
6984   }
6985 
6986   if (R->isSamplerT()) {
6987     // OpenCL v1.2 s6.9.b p4:
6988     // The sampler type cannot be used with the __local and __global address
6989     // space qualifiers.
6990     if (R.getAddressSpace() == LangAS::opencl_local ||
6991         R.getAddressSpace() == LangAS::opencl_global) {
6992       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6993       NewVD->setInvalidDecl();
6994     }
6995 
6996     // OpenCL v1.2 s6.12.14.1:
6997     // A global sampler must be declared with either the constant address
6998     // space qualifier or with the const qualifier.
6999     if (DC->isTranslationUnit() &&
7000         !(R.getAddressSpace() == LangAS::opencl_constant ||
7001           R.isConstQualified())) {
7002       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7003       NewVD->setInvalidDecl();
7004     }
7005     if (NewVD->isInvalidDecl())
7006       return false;
7007   }
7008 
7009   return true;
7010 }
7011 
7012 template <typename AttrTy>
7013 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7014   const TypedefNameDecl *TND = TT->getDecl();
7015   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7016     AttrTy *Clone = Attribute->clone(S.Context);
7017     Clone->setInherited(true);
7018     D->addAttr(Clone);
7019   }
7020 }
7021 
7022 NamedDecl *Sema::ActOnVariableDeclarator(
7023     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7024     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7025     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7026   QualType R = TInfo->getType();
7027   DeclarationName Name = GetNameForDeclarator(D).getName();
7028 
7029   IdentifierInfo *II = Name.getAsIdentifierInfo();
7030 
7031   if (D.isDecompositionDeclarator()) {
7032     // Take the name of the first declarator as our name for diagnostic
7033     // purposes.
7034     auto &Decomp = D.getDecompositionDeclarator();
7035     if (!Decomp.bindings().empty()) {
7036       II = Decomp.bindings()[0].Name;
7037       Name = II;
7038     }
7039   } else if (!II) {
7040     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7041     return nullptr;
7042   }
7043 
7044 
7045   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7046   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7047 
7048   // dllimport globals without explicit storage class are treated as extern. We
7049   // have to change the storage class this early to get the right DeclContext.
7050   if (SC == SC_None && !DC->isRecord() &&
7051       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7052       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7053     SC = SC_Extern;
7054 
7055   DeclContext *OriginalDC = DC;
7056   bool IsLocalExternDecl = SC == SC_Extern &&
7057                            adjustContextForLocalExternDecl(DC);
7058 
7059   if (SCSpec == DeclSpec::SCS_mutable) {
7060     // mutable can only appear on non-static class members, so it's always
7061     // an error here
7062     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7063     D.setInvalidType();
7064     SC = SC_None;
7065   }
7066 
7067   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7068       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7069                               D.getDeclSpec().getStorageClassSpecLoc())) {
7070     // In C++11, the 'register' storage class specifier is deprecated.
7071     // Suppress the warning in system macros, it's used in macros in some
7072     // popular C system headers, such as in glibc's htonl() macro.
7073     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7074          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7075                                    : diag::warn_deprecated_register)
7076       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7077   }
7078 
7079   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7080 
7081   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7082     // C99 6.9p2: The storage-class specifiers auto and register shall not
7083     // appear in the declaration specifiers in an external declaration.
7084     // Global Register+Asm is a GNU extension we support.
7085     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7086       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7087       D.setInvalidType();
7088     }
7089   }
7090 
7091   // If this variable has a VLA type and an initializer, try to
7092   // fold to a constant-sized type. This is otherwise invalid.
7093   if (D.hasInitializer() && R->isVariableArrayType())
7094     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7095                                     /*DiagID=*/0);
7096 
7097   bool IsMemberSpecialization = false;
7098   bool IsVariableTemplateSpecialization = false;
7099   bool IsPartialSpecialization = false;
7100   bool IsVariableTemplate = false;
7101   VarDecl *NewVD = nullptr;
7102   VarTemplateDecl *NewTemplate = nullptr;
7103   TemplateParameterList *TemplateParams = nullptr;
7104   if (!getLangOpts().CPlusPlus) {
7105     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7106                             II, R, TInfo, SC);
7107 
7108     if (R->getContainedDeducedType())
7109       ParsingInitForAutoVars.insert(NewVD);
7110 
7111     if (D.isInvalidType())
7112       NewVD->setInvalidDecl();
7113 
7114     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7115         NewVD->hasLocalStorage())
7116       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7117                             NTCUC_AutoVar, NTCUK_Destruct);
7118   } else {
7119     bool Invalid = false;
7120 
7121     if (DC->isRecord() && !CurContext->isRecord()) {
7122       // This is an out-of-line definition of a static data member.
7123       switch (SC) {
7124       case SC_None:
7125         break;
7126       case SC_Static:
7127         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7128              diag::err_static_out_of_line)
7129           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7130         break;
7131       case SC_Auto:
7132       case SC_Register:
7133       case SC_Extern:
7134         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7135         // to names of variables declared in a block or to function parameters.
7136         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7137         // of class members
7138 
7139         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7140              diag::err_storage_class_for_static_member)
7141           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7142         break;
7143       case SC_PrivateExtern:
7144         llvm_unreachable("C storage class in c++!");
7145       }
7146     }
7147 
7148     if (SC == SC_Static && CurContext->isRecord()) {
7149       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7150         // Walk up the enclosing DeclContexts to check for any that are
7151         // incompatible with static data members.
7152         const DeclContext *FunctionOrMethod = nullptr;
7153         const CXXRecordDecl *AnonStruct = nullptr;
7154         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7155           if (Ctxt->isFunctionOrMethod()) {
7156             FunctionOrMethod = Ctxt;
7157             break;
7158           }
7159           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7160           if (ParentDecl && !ParentDecl->getDeclName()) {
7161             AnonStruct = ParentDecl;
7162             break;
7163           }
7164         }
7165         if (FunctionOrMethod) {
7166           // C++ [class.static.data]p5: A local class shall not have static data
7167           // members.
7168           Diag(D.getIdentifierLoc(),
7169                diag::err_static_data_member_not_allowed_in_local_class)
7170             << Name << RD->getDeclName() << RD->getTagKind();
7171         } else if (AnonStruct) {
7172           // C++ [class.static.data]p4: Unnamed classes and classes contained
7173           // directly or indirectly within unnamed classes shall not contain
7174           // static data members.
7175           Diag(D.getIdentifierLoc(),
7176                diag::err_static_data_member_not_allowed_in_anon_struct)
7177             << Name << AnonStruct->getTagKind();
7178           Invalid = true;
7179         } else if (RD->isUnion()) {
7180           // C++98 [class.union]p1: If a union contains a static data member,
7181           // the program is ill-formed. C++11 drops this restriction.
7182           Diag(D.getIdentifierLoc(),
7183                getLangOpts().CPlusPlus11
7184                  ? diag::warn_cxx98_compat_static_data_member_in_union
7185                  : diag::ext_static_data_member_in_union) << Name;
7186         }
7187       }
7188     }
7189 
7190     // Match up the template parameter lists with the scope specifier, then
7191     // determine whether we have a template or a template specialization.
7192     bool InvalidScope = false;
7193     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7194         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7195         D.getCXXScopeSpec(),
7196         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7197             ? D.getName().TemplateId
7198             : nullptr,
7199         TemplateParamLists,
7200         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7201     Invalid |= InvalidScope;
7202 
7203     if (TemplateParams) {
7204       if (!TemplateParams->size() &&
7205           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7206         // There is an extraneous 'template<>' for this variable. Complain
7207         // about it, but allow the declaration of the variable.
7208         Diag(TemplateParams->getTemplateLoc(),
7209              diag::err_template_variable_noparams)
7210           << II
7211           << SourceRange(TemplateParams->getTemplateLoc(),
7212                          TemplateParams->getRAngleLoc());
7213         TemplateParams = nullptr;
7214       } else {
7215         // Check that we can declare a template here.
7216         if (CheckTemplateDeclScope(S, TemplateParams))
7217           return nullptr;
7218 
7219         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7220           // This is an explicit specialization or a partial specialization.
7221           IsVariableTemplateSpecialization = true;
7222           IsPartialSpecialization = TemplateParams->size() > 0;
7223         } else { // if (TemplateParams->size() > 0)
7224           // This is a template declaration.
7225           IsVariableTemplate = true;
7226 
7227           // Only C++1y supports variable templates (N3651).
7228           Diag(D.getIdentifierLoc(),
7229                getLangOpts().CPlusPlus14
7230                    ? diag::warn_cxx11_compat_variable_template
7231                    : diag::ext_variable_template);
7232         }
7233       }
7234     } else {
7235       // Check that we can declare a member specialization here.
7236       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7237           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7238         return nullptr;
7239       assert((Invalid ||
7240               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7241              "should have a 'template<>' for this decl");
7242     }
7243 
7244     if (IsVariableTemplateSpecialization) {
7245       SourceLocation TemplateKWLoc =
7246           TemplateParamLists.size() > 0
7247               ? TemplateParamLists[0]->getTemplateLoc()
7248               : SourceLocation();
7249       DeclResult Res = ActOnVarTemplateSpecialization(
7250           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7251           IsPartialSpecialization);
7252       if (Res.isInvalid())
7253         return nullptr;
7254       NewVD = cast<VarDecl>(Res.get());
7255       AddToScope = false;
7256     } else if (D.isDecompositionDeclarator()) {
7257       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7258                                         D.getIdentifierLoc(), R, TInfo, SC,
7259                                         Bindings);
7260     } else
7261       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7262                               D.getIdentifierLoc(), II, R, TInfo, SC);
7263 
7264     // If this is supposed to be a variable template, create it as such.
7265     if (IsVariableTemplate) {
7266       NewTemplate =
7267           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7268                                   TemplateParams, NewVD);
7269       NewVD->setDescribedVarTemplate(NewTemplate);
7270     }
7271 
7272     // If this decl has an auto type in need of deduction, make a note of the
7273     // Decl so we can diagnose uses of it in its own initializer.
7274     if (R->getContainedDeducedType())
7275       ParsingInitForAutoVars.insert(NewVD);
7276 
7277     if (D.isInvalidType() || Invalid) {
7278       NewVD->setInvalidDecl();
7279       if (NewTemplate)
7280         NewTemplate->setInvalidDecl();
7281     }
7282 
7283     SetNestedNameSpecifier(*this, NewVD, D);
7284 
7285     // If we have any template parameter lists that don't directly belong to
7286     // the variable (matching the scope specifier), store them.
7287     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7288     if (TemplateParamLists.size() > VDTemplateParamLists)
7289       NewVD->setTemplateParameterListsInfo(
7290           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7291   }
7292 
7293   if (D.getDeclSpec().isInlineSpecified()) {
7294     if (!getLangOpts().CPlusPlus) {
7295       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7296           << 0;
7297     } else if (CurContext->isFunctionOrMethod()) {
7298       // 'inline' is not allowed on block scope variable declaration.
7299       Diag(D.getDeclSpec().getInlineSpecLoc(),
7300            diag::err_inline_declaration_block_scope) << Name
7301         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7302     } else {
7303       Diag(D.getDeclSpec().getInlineSpecLoc(),
7304            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7305                                      : diag::ext_inline_variable);
7306       NewVD->setInlineSpecified();
7307     }
7308   }
7309 
7310   // Set the lexical context. If the declarator has a C++ scope specifier, the
7311   // lexical context will be different from the semantic context.
7312   NewVD->setLexicalDeclContext(CurContext);
7313   if (NewTemplate)
7314     NewTemplate->setLexicalDeclContext(CurContext);
7315 
7316   if (IsLocalExternDecl) {
7317     if (D.isDecompositionDeclarator())
7318       for (auto *B : Bindings)
7319         B->setLocalExternDecl();
7320     else
7321       NewVD->setLocalExternDecl();
7322   }
7323 
7324   bool EmitTLSUnsupportedError = false;
7325   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7326     // C++11 [dcl.stc]p4:
7327     //   When thread_local is applied to a variable of block scope the
7328     //   storage-class-specifier static is implied if it does not appear
7329     //   explicitly.
7330     // Core issue: 'static' is not implied if the variable is declared
7331     //   'extern'.
7332     if (NewVD->hasLocalStorage() &&
7333         (SCSpec != DeclSpec::SCS_unspecified ||
7334          TSCS != DeclSpec::TSCS_thread_local ||
7335          !DC->isFunctionOrMethod()))
7336       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7337            diag::err_thread_non_global)
7338         << DeclSpec::getSpecifierName(TSCS);
7339     else if (!Context.getTargetInfo().isTLSSupported()) {
7340       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7341           getLangOpts().SYCLIsDevice) {
7342         // Postpone error emission until we've collected attributes required to
7343         // figure out whether it's a host or device variable and whether the
7344         // error should be ignored.
7345         EmitTLSUnsupportedError = true;
7346         // We still need to mark the variable as TLS so it shows up in AST with
7347         // proper storage class for other tools to use even if we're not going
7348         // to emit any code for it.
7349         NewVD->setTSCSpec(TSCS);
7350       } else
7351         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7352              diag::err_thread_unsupported);
7353     } else
7354       NewVD->setTSCSpec(TSCS);
7355   }
7356 
7357   switch (D.getDeclSpec().getConstexprSpecifier()) {
7358   case ConstexprSpecKind::Unspecified:
7359     break;
7360 
7361   case ConstexprSpecKind::Consteval:
7362     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7363          diag::err_constexpr_wrong_decl_kind)
7364         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7365     LLVM_FALLTHROUGH;
7366 
7367   case ConstexprSpecKind::Constexpr:
7368     NewVD->setConstexpr(true);
7369     // C++1z [dcl.spec.constexpr]p1:
7370     //   A static data member declared with the constexpr specifier is
7371     //   implicitly an inline variable.
7372     if (NewVD->isStaticDataMember() &&
7373         (getLangOpts().CPlusPlus17 ||
7374          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7375       NewVD->setImplicitlyInline();
7376     break;
7377 
7378   case ConstexprSpecKind::Constinit:
7379     if (!NewVD->hasGlobalStorage())
7380       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7381            diag::err_constinit_local_variable);
7382     else
7383       NewVD->addAttr(ConstInitAttr::Create(
7384           Context, D.getDeclSpec().getConstexprSpecLoc(),
7385           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7386     break;
7387   }
7388 
7389   // C99 6.7.4p3
7390   //   An inline definition of a function with external linkage shall
7391   //   not contain a definition of a modifiable object with static or
7392   //   thread storage duration...
7393   // We only apply this when the function is required to be defined
7394   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7395   // that a local variable with thread storage duration still has to
7396   // be marked 'static'.  Also note that it's possible to get these
7397   // semantics in C++ using __attribute__((gnu_inline)).
7398   if (SC == SC_Static && S->getFnParent() != nullptr &&
7399       !NewVD->getType().isConstQualified()) {
7400     FunctionDecl *CurFD = getCurFunctionDecl();
7401     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7402       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7403            diag::warn_static_local_in_extern_inline);
7404       MaybeSuggestAddingStaticToDecl(CurFD);
7405     }
7406   }
7407 
7408   if (D.getDeclSpec().isModulePrivateSpecified()) {
7409     if (IsVariableTemplateSpecialization)
7410       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7411           << (IsPartialSpecialization ? 1 : 0)
7412           << FixItHint::CreateRemoval(
7413                  D.getDeclSpec().getModulePrivateSpecLoc());
7414     else if (IsMemberSpecialization)
7415       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7416         << 2
7417         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7418     else if (NewVD->hasLocalStorage())
7419       Diag(NewVD->getLocation(), diag::err_module_private_local)
7420           << 0 << NewVD
7421           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7422           << FixItHint::CreateRemoval(
7423                  D.getDeclSpec().getModulePrivateSpecLoc());
7424     else {
7425       NewVD->setModulePrivate();
7426       if (NewTemplate)
7427         NewTemplate->setModulePrivate();
7428       for (auto *B : Bindings)
7429         B->setModulePrivate();
7430     }
7431   }
7432 
7433   if (getLangOpts().OpenCL) {
7434     deduceOpenCLAddressSpace(NewVD);
7435 
7436     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7437     if (TSC != TSCS_unspecified) {
7438       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7439            diag::err_opencl_unknown_type_specifier)
7440           << getLangOpts().getOpenCLVersionString()
7441           << DeclSpec::getSpecifierName(TSC) << 1;
7442       NewVD->setInvalidDecl();
7443     }
7444   }
7445 
7446   // Handle attributes prior to checking for duplicates in MergeVarDecl
7447   ProcessDeclAttributes(S, NewVD, D);
7448 
7449   // FIXME: This is probably the wrong location to be doing this and we should
7450   // probably be doing this for more attributes (especially for function
7451   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7452   // the code to copy attributes would be generated by TableGen.
7453   if (R->isFunctionPointerType())
7454     if (const auto *TT = R->getAs<TypedefType>())
7455       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7456 
7457   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7458       getLangOpts().SYCLIsDevice) {
7459     if (EmitTLSUnsupportedError &&
7460         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7461          (getLangOpts().OpenMPIsDevice &&
7462           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7463       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7464            diag::err_thread_unsupported);
7465 
7466     if (EmitTLSUnsupportedError &&
7467         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7468       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7469     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7470     // storage [duration]."
7471     if (SC == SC_None && S->getFnParent() != nullptr &&
7472         (NewVD->hasAttr<CUDASharedAttr>() ||
7473          NewVD->hasAttr<CUDAConstantAttr>())) {
7474       NewVD->setStorageClass(SC_Static);
7475     }
7476   }
7477 
7478   // Ensure that dllimport globals without explicit storage class are treated as
7479   // extern. The storage class is set above using parsed attributes. Now we can
7480   // check the VarDecl itself.
7481   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7482          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7483          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7484 
7485   // In auto-retain/release, infer strong retension for variables of
7486   // retainable type.
7487   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7488     NewVD->setInvalidDecl();
7489 
7490   // Handle GNU asm-label extension (encoded as an attribute).
7491   if (Expr *E = (Expr*)D.getAsmLabel()) {
7492     // The parser guarantees this is a string.
7493     StringLiteral *SE = cast<StringLiteral>(E);
7494     StringRef Label = SE->getString();
7495     if (S->getFnParent() != nullptr) {
7496       switch (SC) {
7497       case SC_None:
7498       case SC_Auto:
7499         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7500         break;
7501       case SC_Register:
7502         // Local Named register
7503         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7504             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7505           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7506         break;
7507       case SC_Static:
7508       case SC_Extern:
7509       case SC_PrivateExtern:
7510         break;
7511       }
7512     } else if (SC == SC_Register) {
7513       // Global Named register
7514       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7515         const auto &TI = Context.getTargetInfo();
7516         bool HasSizeMismatch;
7517 
7518         if (!TI.isValidGCCRegisterName(Label))
7519           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7520         else if (!TI.validateGlobalRegisterVariable(Label,
7521                                                     Context.getTypeSize(R),
7522                                                     HasSizeMismatch))
7523           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7524         else if (HasSizeMismatch)
7525           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7526       }
7527 
7528       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7529         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7530         NewVD->setInvalidDecl(true);
7531       }
7532     }
7533 
7534     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7535                                         /*IsLiteralLabel=*/true,
7536                                         SE->getStrTokenLoc(0)));
7537   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7538     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7539       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7540     if (I != ExtnameUndeclaredIdentifiers.end()) {
7541       if (isDeclExternC(NewVD)) {
7542         NewVD->addAttr(I->second);
7543         ExtnameUndeclaredIdentifiers.erase(I);
7544       } else
7545         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7546             << /*Variable*/1 << NewVD;
7547     }
7548   }
7549 
7550   // Find the shadowed declaration before filtering for scope.
7551   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7552                                 ? getShadowedDeclaration(NewVD, Previous)
7553                                 : nullptr;
7554 
7555   // Don't consider existing declarations that are in a different
7556   // scope and are out-of-semantic-context declarations (if the new
7557   // declaration has linkage).
7558   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7559                        D.getCXXScopeSpec().isNotEmpty() ||
7560                        IsMemberSpecialization ||
7561                        IsVariableTemplateSpecialization);
7562 
7563   // Check whether the previous declaration is in the same block scope. This
7564   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7565   if (getLangOpts().CPlusPlus &&
7566       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7567     NewVD->setPreviousDeclInSameBlockScope(
7568         Previous.isSingleResult() && !Previous.isShadowed() &&
7569         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7570 
7571   if (!getLangOpts().CPlusPlus) {
7572     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7573   } else {
7574     // If this is an explicit specialization of a static data member, check it.
7575     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7576         CheckMemberSpecialization(NewVD, Previous))
7577       NewVD->setInvalidDecl();
7578 
7579     // Merge the decl with the existing one if appropriate.
7580     if (!Previous.empty()) {
7581       if (Previous.isSingleResult() &&
7582           isa<FieldDecl>(Previous.getFoundDecl()) &&
7583           D.getCXXScopeSpec().isSet()) {
7584         // The user tried to define a non-static data member
7585         // out-of-line (C++ [dcl.meaning]p1).
7586         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7587           << D.getCXXScopeSpec().getRange();
7588         Previous.clear();
7589         NewVD->setInvalidDecl();
7590       }
7591     } else if (D.getCXXScopeSpec().isSet()) {
7592       // No previous declaration in the qualifying scope.
7593       Diag(D.getIdentifierLoc(), diag::err_no_member)
7594         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7595         << D.getCXXScopeSpec().getRange();
7596       NewVD->setInvalidDecl();
7597     }
7598 
7599     if (!IsVariableTemplateSpecialization)
7600       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7601 
7602     if (NewTemplate) {
7603       VarTemplateDecl *PrevVarTemplate =
7604           NewVD->getPreviousDecl()
7605               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7606               : nullptr;
7607 
7608       // Check the template parameter list of this declaration, possibly
7609       // merging in the template parameter list from the previous variable
7610       // template declaration.
7611       if (CheckTemplateParameterList(
7612               TemplateParams,
7613               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7614                               : nullptr,
7615               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7616                DC->isDependentContext())
7617                   ? TPC_ClassTemplateMember
7618                   : TPC_VarTemplate))
7619         NewVD->setInvalidDecl();
7620 
7621       // If we are providing an explicit specialization of a static variable
7622       // template, make a note of that.
7623       if (PrevVarTemplate &&
7624           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7625         PrevVarTemplate->setMemberSpecialization();
7626     }
7627   }
7628 
7629   // Diagnose shadowed variables iff this isn't a redeclaration.
7630   if (ShadowedDecl && !D.isRedeclaration())
7631     CheckShadow(NewVD, ShadowedDecl, Previous);
7632 
7633   ProcessPragmaWeak(S, NewVD);
7634 
7635   // If this is the first declaration of an extern C variable, update
7636   // the map of such variables.
7637   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7638       isIncompleteDeclExternC(*this, NewVD))
7639     RegisterLocallyScopedExternCDecl(NewVD, S);
7640 
7641   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7642     MangleNumberingContext *MCtx;
7643     Decl *ManglingContextDecl;
7644     std::tie(MCtx, ManglingContextDecl) =
7645         getCurrentMangleNumberContext(NewVD->getDeclContext());
7646     if (MCtx) {
7647       Context.setManglingNumber(
7648           NewVD, MCtx->getManglingNumber(
7649                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7650       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7651     }
7652   }
7653 
7654   // Special handling of variable named 'main'.
7655   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7656       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7657       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7658 
7659     // C++ [basic.start.main]p3
7660     // A program that declares a variable main at global scope is ill-formed.
7661     if (getLangOpts().CPlusPlus)
7662       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7663 
7664     // In C, and external-linkage variable named main results in undefined
7665     // behavior.
7666     else if (NewVD->hasExternalFormalLinkage())
7667       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7668   }
7669 
7670   if (D.isRedeclaration() && !Previous.empty()) {
7671     NamedDecl *Prev = Previous.getRepresentativeDecl();
7672     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7673                                    D.isFunctionDefinition());
7674   }
7675 
7676   if (NewTemplate) {
7677     if (NewVD->isInvalidDecl())
7678       NewTemplate->setInvalidDecl();
7679     ActOnDocumentableDecl(NewTemplate);
7680     return NewTemplate;
7681   }
7682 
7683   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7684     CompleteMemberSpecialization(NewVD, Previous);
7685 
7686   return NewVD;
7687 }
7688 
7689 /// Enum describing the %select options in diag::warn_decl_shadow.
7690 enum ShadowedDeclKind {
7691   SDK_Local,
7692   SDK_Global,
7693   SDK_StaticMember,
7694   SDK_Field,
7695   SDK_Typedef,
7696   SDK_Using,
7697   SDK_StructuredBinding
7698 };
7699 
7700 /// Determine what kind of declaration we're shadowing.
7701 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7702                                                 const DeclContext *OldDC) {
7703   if (isa<TypeAliasDecl>(ShadowedDecl))
7704     return SDK_Using;
7705   else if (isa<TypedefDecl>(ShadowedDecl))
7706     return SDK_Typedef;
7707   else if (isa<BindingDecl>(ShadowedDecl))
7708     return SDK_StructuredBinding;
7709   else if (isa<RecordDecl>(OldDC))
7710     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7711 
7712   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7713 }
7714 
7715 /// Return the location of the capture if the given lambda captures the given
7716 /// variable \p VD, or an invalid source location otherwise.
7717 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7718                                          const VarDecl *VD) {
7719   for (const Capture &Capture : LSI->Captures) {
7720     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7721       return Capture.getLocation();
7722   }
7723   return SourceLocation();
7724 }
7725 
7726 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7727                                      const LookupResult &R) {
7728   // Only diagnose if we're shadowing an unambiguous field or variable.
7729   if (R.getResultKind() != LookupResult::Found)
7730     return false;
7731 
7732   // Return false if warning is ignored.
7733   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7734 }
7735 
7736 /// Return the declaration shadowed by the given variable \p D, or null
7737 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7738 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7739                                         const LookupResult &R) {
7740   if (!shouldWarnIfShadowedDecl(Diags, R))
7741     return nullptr;
7742 
7743   // Don't diagnose declarations at file scope.
7744   if (D->hasGlobalStorage())
7745     return nullptr;
7746 
7747   NamedDecl *ShadowedDecl = R.getFoundDecl();
7748   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7749                                                             : nullptr;
7750 }
7751 
7752 /// Return the declaration shadowed by the given typedef \p D, or null
7753 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7754 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7755                                         const LookupResult &R) {
7756   // Don't warn if typedef declaration is part of a class
7757   if (D->getDeclContext()->isRecord())
7758     return nullptr;
7759 
7760   if (!shouldWarnIfShadowedDecl(Diags, R))
7761     return nullptr;
7762 
7763   NamedDecl *ShadowedDecl = R.getFoundDecl();
7764   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7765 }
7766 
7767 /// Return the declaration shadowed by the given variable \p D, or null
7768 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7769 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7770                                         const LookupResult &R) {
7771   if (!shouldWarnIfShadowedDecl(Diags, R))
7772     return nullptr;
7773 
7774   NamedDecl *ShadowedDecl = R.getFoundDecl();
7775   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7776                                                             : nullptr;
7777 }
7778 
7779 /// Diagnose variable or built-in function shadowing.  Implements
7780 /// -Wshadow.
7781 ///
7782 /// This method is called whenever a VarDecl is added to a "useful"
7783 /// scope.
7784 ///
7785 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7786 /// \param R the lookup of the name
7787 ///
7788 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7789                        const LookupResult &R) {
7790   DeclContext *NewDC = D->getDeclContext();
7791 
7792   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7793     // Fields are not shadowed by variables in C++ static methods.
7794     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7795       if (MD->isStatic())
7796         return;
7797 
7798     // Fields shadowed by constructor parameters are a special case. Usually
7799     // the constructor initializes the field with the parameter.
7800     if (isa<CXXConstructorDecl>(NewDC))
7801       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7802         // Remember that this was shadowed so we can either warn about its
7803         // modification or its existence depending on warning settings.
7804         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7805         return;
7806       }
7807   }
7808 
7809   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7810     if (shadowedVar->isExternC()) {
7811       // For shadowing external vars, make sure that we point to the global
7812       // declaration, not a locally scoped extern declaration.
7813       for (auto I : shadowedVar->redecls())
7814         if (I->isFileVarDecl()) {
7815           ShadowedDecl = I;
7816           break;
7817         }
7818     }
7819 
7820   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7821 
7822   unsigned WarningDiag = diag::warn_decl_shadow;
7823   SourceLocation CaptureLoc;
7824   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7825       isa<CXXMethodDecl>(NewDC)) {
7826     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7827       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7828         if (RD->getLambdaCaptureDefault() == LCD_None) {
7829           // Try to avoid warnings for lambdas with an explicit capture list.
7830           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7831           // Warn only when the lambda captures the shadowed decl explicitly.
7832           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7833           if (CaptureLoc.isInvalid())
7834             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7835         } else {
7836           // Remember that this was shadowed so we can avoid the warning if the
7837           // shadowed decl isn't captured and the warning settings allow it.
7838           cast<LambdaScopeInfo>(getCurFunction())
7839               ->ShadowingDecls.push_back(
7840                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7841           return;
7842         }
7843       }
7844 
7845       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7846         // A variable can't shadow a local variable in an enclosing scope, if
7847         // they are separated by a non-capturing declaration context.
7848         for (DeclContext *ParentDC = NewDC;
7849              ParentDC && !ParentDC->Equals(OldDC);
7850              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7851           // Only block literals, captured statements, and lambda expressions
7852           // can capture; other scopes don't.
7853           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7854               !isLambdaCallOperator(ParentDC)) {
7855             return;
7856           }
7857         }
7858       }
7859     }
7860   }
7861 
7862   // Only warn about certain kinds of shadowing for class members.
7863   if (NewDC && NewDC->isRecord()) {
7864     // In particular, don't warn about shadowing non-class members.
7865     if (!OldDC->isRecord())
7866       return;
7867 
7868     // TODO: should we warn about static data members shadowing
7869     // static data members from base classes?
7870 
7871     // TODO: don't diagnose for inaccessible shadowed members.
7872     // This is hard to do perfectly because we might friend the
7873     // shadowing context, but that's just a false negative.
7874   }
7875 
7876 
7877   DeclarationName Name = R.getLookupName();
7878 
7879   // Emit warning and note.
7880   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7881   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7882   if (!CaptureLoc.isInvalid())
7883     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7884         << Name << /*explicitly*/ 1;
7885   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7886 }
7887 
7888 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7889 /// when these variables are captured by the lambda.
7890 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7891   for (const auto &Shadow : LSI->ShadowingDecls) {
7892     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7893     // Try to avoid the warning when the shadowed decl isn't captured.
7894     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7895     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7896     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7897                                        ? diag::warn_decl_shadow_uncaptured_local
7898                                        : diag::warn_decl_shadow)
7899         << Shadow.VD->getDeclName()
7900         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7901     if (!CaptureLoc.isInvalid())
7902       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7903           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7904     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7905   }
7906 }
7907 
7908 /// Check -Wshadow without the advantage of a previous lookup.
7909 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7910   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7911     return;
7912 
7913   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7914                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7915   LookupName(R, S);
7916   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7917     CheckShadow(D, ShadowedDecl, R);
7918 }
7919 
7920 /// Check if 'E', which is an expression that is about to be modified, refers
7921 /// to a constructor parameter that shadows a field.
7922 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7923   // Quickly ignore expressions that can't be shadowing ctor parameters.
7924   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7925     return;
7926   E = E->IgnoreParenImpCasts();
7927   auto *DRE = dyn_cast<DeclRefExpr>(E);
7928   if (!DRE)
7929     return;
7930   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7931   auto I = ShadowingDecls.find(D);
7932   if (I == ShadowingDecls.end())
7933     return;
7934   const NamedDecl *ShadowedDecl = I->second;
7935   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7936   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7937   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7938   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7939 
7940   // Avoid issuing multiple warnings about the same decl.
7941   ShadowingDecls.erase(I);
7942 }
7943 
7944 /// Check for conflict between this global or extern "C" declaration and
7945 /// previous global or extern "C" declarations. This is only used in C++.
7946 template<typename T>
7947 static bool checkGlobalOrExternCConflict(
7948     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7949   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7950   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7951 
7952   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7953     // The common case: this global doesn't conflict with any extern "C"
7954     // declaration.
7955     return false;
7956   }
7957 
7958   if (Prev) {
7959     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7960       // Both the old and new declarations have C language linkage. This is a
7961       // redeclaration.
7962       Previous.clear();
7963       Previous.addDecl(Prev);
7964       return true;
7965     }
7966 
7967     // This is a global, non-extern "C" declaration, and there is a previous
7968     // non-global extern "C" declaration. Diagnose if this is a variable
7969     // declaration.
7970     if (!isa<VarDecl>(ND))
7971       return false;
7972   } else {
7973     // The declaration is extern "C". Check for any declaration in the
7974     // translation unit which might conflict.
7975     if (IsGlobal) {
7976       // We have already performed the lookup into the translation unit.
7977       IsGlobal = false;
7978       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7979            I != E; ++I) {
7980         if (isa<VarDecl>(*I)) {
7981           Prev = *I;
7982           break;
7983         }
7984       }
7985     } else {
7986       DeclContext::lookup_result R =
7987           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7988       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7989            I != E; ++I) {
7990         if (isa<VarDecl>(*I)) {
7991           Prev = *I;
7992           break;
7993         }
7994         // FIXME: If we have any other entity with this name in global scope,
7995         // the declaration is ill-formed, but that is a defect: it breaks the
7996         // 'stat' hack, for instance. Only variables can have mangled name
7997         // clashes with extern "C" declarations, so only they deserve a
7998         // diagnostic.
7999       }
8000     }
8001 
8002     if (!Prev)
8003       return false;
8004   }
8005 
8006   // Use the first declaration's location to ensure we point at something which
8007   // is lexically inside an extern "C" linkage-spec.
8008   assert(Prev && "should have found a previous declaration to diagnose");
8009   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8010     Prev = FD->getFirstDecl();
8011   else
8012     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8013 
8014   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8015     << IsGlobal << ND;
8016   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8017     << IsGlobal;
8018   return false;
8019 }
8020 
8021 /// Apply special rules for handling extern "C" declarations. Returns \c true
8022 /// if we have found that this is a redeclaration of some prior entity.
8023 ///
8024 /// Per C++ [dcl.link]p6:
8025 ///   Two declarations [for a function or variable] with C language linkage
8026 ///   with the same name that appear in different scopes refer to the same
8027 ///   [entity]. An entity with C language linkage shall not be declared with
8028 ///   the same name as an entity in global scope.
8029 template<typename T>
8030 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8031                                                   LookupResult &Previous) {
8032   if (!S.getLangOpts().CPlusPlus) {
8033     // In C, when declaring a global variable, look for a corresponding 'extern'
8034     // variable declared in function scope. We don't need this in C++, because
8035     // we find local extern decls in the surrounding file-scope DeclContext.
8036     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8037       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8038         Previous.clear();
8039         Previous.addDecl(Prev);
8040         return true;
8041       }
8042     }
8043     return false;
8044   }
8045 
8046   // A declaration in the translation unit can conflict with an extern "C"
8047   // declaration.
8048   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8049     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8050 
8051   // An extern "C" declaration can conflict with a declaration in the
8052   // translation unit or can be a redeclaration of an extern "C" declaration
8053   // in another scope.
8054   if (isIncompleteDeclExternC(S,ND))
8055     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8056 
8057   // Neither global nor extern "C": nothing to do.
8058   return false;
8059 }
8060 
8061 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8062   // If the decl is already known invalid, don't check it.
8063   if (NewVD->isInvalidDecl())
8064     return;
8065 
8066   QualType T = NewVD->getType();
8067 
8068   // Defer checking an 'auto' type until its initializer is attached.
8069   if (T->isUndeducedType())
8070     return;
8071 
8072   if (NewVD->hasAttrs())
8073     CheckAlignasUnderalignment(NewVD);
8074 
8075   if (T->isObjCObjectType()) {
8076     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8077       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8078     T = Context.getObjCObjectPointerType(T);
8079     NewVD->setType(T);
8080   }
8081 
8082   // Emit an error if an address space was applied to decl with local storage.
8083   // This includes arrays of objects with address space qualifiers, but not
8084   // automatic variables that point to other address spaces.
8085   // ISO/IEC TR 18037 S5.1.2
8086   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8087       T.getAddressSpace() != LangAS::Default) {
8088     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8089     NewVD->setInvalidDecl();
8090     return;
8091   }
8092 
8093   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8094   // scope.
8095   if (getLangOpts().OpenCLVersion == 120 &&
8096       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8097                                             getLangOpts()) &&
8098       NewVD->isStaticLocal()) {
8099     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8100     NewVD->setInvalidDecl();
8101     return;
8102   }
8103 
8104   if (getLangOpts().OpenCL) {
8105     if (!diagnoseOpenCLTypes(*this, NewVD))
8106       return;
8107 
8108     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8109     if (NewVD->hasAttr<BlocksAttr>()) {
8110       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8111       return;
8112     }
8113 
8114     if (T->isBlockPointerType()) {
8115       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8116       // can't use 'extern' storage class.
8117       if (!T.isConstQualified()) {
8118         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8119             << 0 /*const*/;
8120         NewVD->setInvalidDecl();
8121         return;
8122       }
8123       if (NewVD->hasExternalStorage()) {
8124         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8125         NewVD->setInvalidDecl();
8126         return;
8127       }
8128     }
8129 
8130     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8131     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8132         NewVD->hasExternalStorage()) {
8133       if (!T->isSamplerT() && !T->isDependentType() &&
8134           !(T.getAddressSpace() == LangAS::opencl_constant ||
8135             (T.getAddressSpace() == LangAS::opencl_global &&
8136              getOpenCLOptions().areProgramScopeVariablesSupported(
8137                  getLangOpts())))) {
8138         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8139         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8140           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8141               << Scope << "global or constant";
8142         else
8143           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8144               << Scope << "constant";
8145         NewVD->setInvalidDecl();
8146         return;
8147       }
8148     } else {
8149       if (T.getAddressSpace() == LangAS::opencl_global) {
8150         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8151             << 1 /*is any function*/ << "global";
8152         NewVD->setInvalidDecl();
8153         return;
8154       }
8155       if (T.getAddressSpace() == LangAS::opencl_constant ||
8156           T.getAddressSpace() == LangAS::opencl_local) {
8157         FunctionDecl *FD = getCurFunctionDecl();
8158         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8159         // in functions.
8160         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8161           if (T.getAddressSpace() == LangAS::opencl_constant)
8162             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8163                 << 0 /*non-kernel only*/ << "constant";
8164           else
8165             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8166                 << 0 /*non-kernel only*/ << "local";
8167           NewVD->setInvalidDecl();
8168           return;
8169         }
8170         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8171         // in the outermost scope of a kernel function.
8172         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8173           if (!getCurScope()->isFunctionScope()) {
8174             if (T.getAddressSpace() == LangAS::opencl_constant)
8175               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8176                   << "constant";
8177             else
8178               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8179                   << "local";
8180             NewVD->setInvalidDecl();
8181             return;
8182           }
8183         }
8184       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8185                  // If we are parsing a template we didn't deduce an addr
8186                  // space yet.
8187                  T.getAddressSpace() != LangAS::Default) {
8188         // Do not allow other address spaces on automatic variable.
8189         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8190         NewVD->setInvalidDecl();
8191         return;
8192       }
8193     }
8194   }
8195 
8196   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8197       && !NewVD->hasAttr<BlocksAttr>()) {
8198     if (getLangOpts().getGC() != LangOptions::NonGC)
8199       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8200     else {
8201       assert(!getLangOpts().ObjCAutoRefCount);
8202       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8203     }
8204   }
8205 
8206   bool isVM = T->isVariablyModifiedType();
8207   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8208       NewVD->hasAttr<BlocksAttr>())
8209     setFunctionHasBranchProtectedScope();
8210 
8211   if ((isVM && NewVD->hasLinkage()) ||
8212       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8213     bool SizeIsNegative;
8214     llvm::APSInt Oversized;
8215     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8216         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8217     QualType FixedT;
8218     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8219       FixedT = FixedTInfo->getType();
8220     else if (FixedTInfo) {
8221       // Type and type-as-written are canonically different. We need to fix up
8222       // both types separately.
8223       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8224                                                    Oversized);
8225     }
8226     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8227       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8228       // FIXME: This won't give the correct result for
8229       // int a[10][n];
8230       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8231 
8232       if (NewVD->isFileVarDecl())
8233         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8234         << SizeRange;
8235       else if (NewVD->isStaticLocal())
8236         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8237         << SizeRange;
8238       else
8239         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8240         << SizeRange;
8241       NewVD->setInvalidDecl();
8242       return;
8243     }
8244 
8245     if (!FixedTInfo) {
8246       if (NewVD->isFileVarDecl())
8247         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8248       else
8249         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8250       NewVD->setInvalidDecl();
8251       return;
8252     }
8253 
8254     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8255     NewVD->setType(FixedT);
8256     NewVD->setTypeSourceInfo(FixedTInfo);
8257   }
8258 
8259   if (T->isVoidType()) {
8260     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8261     //                    of objects and functions.
8262     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8263       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8264         << T;
8265       NewVD->setInvalidDecl();
8266       return;
8267     }
8268   }
8269 
8270   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8271     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8272     NewVD->setInvalidDecl();
8273     return;
8274   }
8275 
8276   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8277     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8278     NewVD->setInvalidDecl();
8279     return;
8280   }
8281 
8282   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8283     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8284     NewVD->setInvalidDecl();
8285     return;
8286   }
8287 
8288   if (NewVD->isConstexpr() && !T->isDependentType() &&
8289       RequireLiteralType(NewVD->getLocation(), T,
8290                          diag::err_constexpr_var_non_literal)) {
8291     NewVD->setInvalidDecl();
8292     return;
8293   }
8294 
8295   // PPC MMA non-pointer types are not allowed as non-local variable types.
8296   if (Context.getTargetInfo().getTriple().isPPC64() &&
8297       !NewVD->isLocalVarDecl() &&
8298       CheckPPCMMAType(T, NewVD->getLocation())) {
8299     NewVD->setInvalidDecl();
8300     return;
8301   }
8302 }
8303 
8304 /// Perform semantic checking on a newly-created variable
8305 /// declaration.
8306 ///
8307 /// This routine performs all of the type-checking required for a
8308 /// variable declaration once it has been built. It is used both to
8309 /// check variables after they have been parsed and their declarators
8310 /// have been translated into a declaration, and to check variables
8311 /// that have been instantiated from a template.
8312 ///
8313 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8314 ///
8315 /// Returns true if the variable declaration is a redeclaration.
8316 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8317   CheckVariableDeclarationType(NewVD);
8318 
8319   // If the decl is already known invalid, don't check it.
8320   if (NewVD->isInvalidDecl())
8321     return false;
8322 
8323   // If we did not find anything by this name, look for a non-visible
8324   // extern "C" declaration with the same name.
8325   if (Previous.empty() &&
8326       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8327     Previous.setShadowed();
8328 
8329   if (!Previous.empty()) {
8330     MergeVarDecl(NewVD, Previous);
8331     return true;
8332   }
8333   return false;
8334 }
8335 
8336 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8337 /// and if so, check that it's a valid override and remember it.
8338 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8339   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8340 
8341   // Look for methods in base classes that this method might override.
8342   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8343                      /*DetectVirtual=*/false);
8344   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8345     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8346     DeclarationName Name = MD->getDeclName();
8347 
8348     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8349       // We really want to find the base class destructor here.
8350       QualType T = Context.getTypeDeclType(BaseRecord);
8351       CanQualType CT = Context.getCanonicalType(T);
8352       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8353     }
8354 
8355     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8356       CXXMethodDecl *BaseMD =
8357           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8358       if (!BaseMD || !BaseMD->isVirtual() ||
8359           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8360                      /*ConsiderCudaAttrs=*/true,
8361                      // C++2a [class.virtual]p2 does not consider requires
8362                      // clauses when overriding.
8363                      /*ConsiderRequiresClauses=*/false))
8364         continue;
8365 
8366       if (Overridden.insert(BaseMD).second) {
8367         MD->addOverriddenMethod(BaseMD);
8368         CheckOverridingFunctionReturnType(MD, BaseMD);
8369         CheckOverridingFunctionAttributes(MD, BaseMD);
8370         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8371         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8372       }
8373 
8374       // A method can only override one function from each base class. We
8375       // don't track indirectly overridden methods from bases of bases.
8376       return true;
8377     }
8378 
8379     return false;
8380   };
8381 
8382   DC->lookupInBases(VisitBase, Paths);
8383   return !Overridden.empty();
8384 }
8385 
8386 namespace {
8387   // Struct for holding all of the extra arguments needed by
8388   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8389   struct ActOnFDArgs {
8390     Scope *S;
8391     Declarator &D;
8392     MultiTemplateParamsArg TemplateParamLists;
8393     bool AddToScope;
8394   };
8395 } // end anonymous namespace
8396 
8397 namespace {
8398 
8399 // Callback to only accept typo corrections that have a non-zero edit distance.
8400 // Also only accept corrections that have the same parent decl.
8401 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8402  public:
8403   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8404                             CXXRecordDecl *Parent)
8405       : Context(Context), OriginalFD(TypoFD),
8406         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8407 
8408   bool ValidateCandidate(const TypoCorrection &candidate) override {
8409     if (candidate.getEditDistance() == 0)
8410       return false;
8411 
8412     SmallVector<unsigned, 1> MismatchedParams;
8413     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8414                                           CDeclEnd = candidate.end();
8415          CDecl != CDeclEnd; ++CDecl) {
8416       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8417 
8418       if (FD && !FD->hasBody() &&
8419           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8420         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8421           CXXRecordDecl *Parent = MD->getParent();
8422           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8423             return true;
8424         } else if (!ExpectedParent) {
8425           return true;
8426         }
8427       }
8428     }
8429 
8430     return false;
8431   }
8432 
8433   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8434     return std::make_unique<DifferentNameValidatorCCC>(*this);
8435   }
8436 
8437  private:
8438   ASTContext &Context;
8439   FunctionDecl *OriginalFD;
8440   CXXRecordDecl *ExpectedParent;
8441 };
8442 
8443 } // end anonymous namespace
8444 
8445 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8446   TypoCorrectedFunctionDefinitions.insert(F);
8447 }
8448 
8449 /// Generate diagnostics for an invalid function redeclaration.
8450 ///
8451 /// This routine handles generating the diagnostic messages for an invalid
8452 /// function redeclaration, including finding possible similar declarations
8453 /// or performing typo correction if there are no previous declarations with
8454 /// the same name.
8455 ///
8456 /// Returns a NamedDecl iff typo correction was performed and substituting in
8457 /// the new declaration name does not cause new errors.
8458 static NamedDecl *DiagnoseInvalidRedeclaration(
8459     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8460     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8461   DeclarationName Name = NewFD->getDeclName();
8462   DeclContext *NewDC = NewFD->getDeclContext();
8463   SmallVector<unsigned, 1> MismatchedParams;
8464   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8465   TypoCorrection Correction;
8466   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8467   unsigned DiagMsg =
8468     IsLocalFriend ? diag::err_no_matching_local_friend :
8469     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8470     diag::err_member_decl_does_not_match;
8471   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8472                     IsLocalFriend ? Sema::LookupLocalFriendName
8473                                   : Sema::LookupOrdinaryName,
8474                     Sema::ForVisibleRedeclaration);
8475 
8476   NewFD->setInvalidDecl();
8477   if (IsLocalFriend)
8478     SemaRef.LookupName(Prev, S);
8479   else
8480     SemaRef.LookupQualifiedName(Prev, NewDC);
8481   assert(!Prev.isAmbiguous() &&
8482          "Cannot have an ambiguity in previous-declaration lookup");
8483   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8484   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8485                                 MD ? MD->getParent() : nullptr);
8486   if (!Prev.empty()) {
8487     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8488          Func != FuncEnd; ++Func) {
8489       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8490       if (FD &&
8491           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8492         // Add 1 to the index so that 0 can mean the mismatch didn't
8493         // involve a parameter
8494         unsigned ParamNum =
8495             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8496         NearMatches.push_back(std::make_pair(FD, ParamNum));
8497       }
8498     }
8499   // If the qualified name lookup yielded nothing, try typo correction
8500   } else if ((Correction = SemaRef.CorrectTypo(
8501                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8502                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8503                   IsLocalFriend ? nullptr : NewDC))) {
8504     // Set up everything for the call to ActOnFunctionDeclarator
8505     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8506                               ExtraArgs.D.getIdentifierLoc());
8507     Previous.clear();
8508     Previous.setLookupName(Correction.getCorrection());
8509     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8510                                     CDeclEnd = Correction.end();
8511          CDecl != CDeclEnd; ++CDecl) {
8512       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8513       if (FD && !FD->hasBody() &&
8514           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8515         Previous.addDecl(FD);
8516       }
8517     }
8518     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8519 
8520     NamedDecl *Result;
8521     // Retry building the function declaration with the new previous
8522     // declarations, and with errors suppressed.
8523     {
8524       // Trap errors.
8525       Sema::SFINAETrap Trap(SemaRef);
8526 
8527       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8528       // pieces need to verify the typo-corrected C++ declaration and hopefully
8529       // eliminate the need for the parameter pack ExtraArgs.
8530       Result = SemaRef.ActOnFunctionDeclarator(
8531           ExtraArgs.S, ExtraArgs.D,
8532           Correction.getCorrectionDecl()->getDeclContext(),
8533           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8534           ExtraArgs.AddToScope);
8535 
8536       if (Trap.hasErrorOccurred())
8537         Result = nullptr;
8538     }
8539 
8540     if (Result) {
8541       // Determine which correction we picked.
8542       Decl *Canonical = Result->getCanonicalDecl();
8543       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8544            I != E; ++I)
8545         if ((*I)->getCanonicalDecl() == Canonical)
8546           Correction.setCorrectionDecl(*I);
8547 
8548       // Let Sema know about the correction.
8549       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8550       SemaRef.diagnoseTypo(
8551           Correction,
8552           SemaRef.PDiag(IsLocalFriend
8553                           ? diag::err_no_matching_local_friend_suggest
8554                           : diag::err_member_decl_does_not_match_suggest)
8555             << Name << NewDC << IsDefinition);
8556       return Result;
8557     }
8558 
8559     // Pretend the typo correction never occurred
8560     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8561                               ExtraArgs.D.getIdentifierLoc());
8562     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8563     Previous.clear();
8564     Previous.setLookupName(Name);
8565   }
8566 
8567   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8568       << Name << NewDC << IsDefinition << NewFD->getLocation();
8569 
8570   bool NewFDisConst = false;
8571   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8572     NewFDisConst = NewMD->isConst();
8573 
8574   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8575        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8576        NearMatch != NearMatchEnd; ++NearMatch) {
8577     FunctionDecl *FD = NearMatch->first;
8578     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8579     bool FDisConst = MD && MD->isConst();
8580     bool IsMember = MD || !IsLocalFriend;
8581 
8582     // FIXME: These notes are poorly worded for the local friend case.
8583     if (unsigned Idx = NearMatch->second) {
8584       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8585       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8586       if (Loc.isInvalid()) Loc = FD->getLocation();
8587       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8588                                  : diag::note_local_decl_close_param_match)
8589         << Idx << FDParam->getType()
8590         << NewFD->getParamDecl(Idx - 1)->getType();
8591     } else if (FDisConst != NewFDisConst) {
8592       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8593           << NewFDisConst << FD->getSourceRange().getEnd()
8594           << (NewFDisConst
8595                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8596                                                  .getConstQualifierLoc())
8597                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8598                                                    .getRParenLoc()
8599                                                    .getLocWithOffset(1),
8600                                                " const"));
8601     } else
8602       SemaRef.Diag(FD->getLocation(),
8603                    IsMember ? diag::note_member_def_close_match
8604                             : diag::note_local_decl_close_match);
8605   }
8606   return nullptr;
8607 }
8608 
8609 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8610   switch (D.getDeclSpec().getStorageClassSpec()) {
8611   default: llvm_unreachable("Unknown storage class!");
8612   case DeclSpec::SCS_auto:
8613   case DeclSpec::SCS_register:
8614   case DeclSpec::SCS_mutable:
8615     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8616                  diag::err_typecheck_sclass_func);
8617     D.getMutableDeclSpec().ClearStorageClassSpecs();
8618     D.setInvalidType();
8619     break;
8620   case DeclSpec::SCS_unspecified: break;
8621   case DeclSpec::SCS_extern:
8622     if (D.getDeclSpec().isExternInLinkageSpec())
8623       return SC_None;
8624     return SC_Extern;
8625   case DeclSpec::SCS_static: {
8626     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8627       // C99 6.7.1p5:
8628       //   The declaration of an identifier for a function that has
8629       //   block scope shall have no explicit storage-class specifier
8630       //   other than extern
8631       // See also (C++ [dcl.stc]p4).
8632       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8633                    diag::err_static_block_func);
8634       break;
8635     } else
8636       return SC_Static;
8637   }
8638   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8639   }
8640 
8641   // No explicit storage class has already been returned
8642   return SC_None;
8643 }
8644 
8645 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8646                                            DeclContext *DC, QualType &R,
8647                                            TypeSourceInfo *TInfo,
8648                                            StorageClass SC,
8649                                            bool &IsVirtualOkay) {
8650   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8651   DeclarationName Name = NameInfo.getName();
8652 
8653   FunctionDecl *NewFD = nullptr;
8654   bool isInline = D.getDeclSpec().isInlineSpecified();
8655 
8656   if (!SemaRef.getLangOpts().CPlusPlus) {
8657     // Determine whether the function was written with a
8658     // prototype. This true when:
8659     //   - there is a prototype in the declarator, or
8660     //   - the type R of the function is some kind of typedef or other non-
8661     //     attributed reference to a type name (which eventually refers to a
8662     //     function type).
8663     bool HasPrototype =
8664       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8665       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8666 
8667     NewFD = FunctionDecl::Create(
8668         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8669         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8670         ConstexprSpecKind::Unspecified,
8671         /*TrailingRequiresClause=*/nullptr);
8672     if (D.isInvalidType())
8673       NewFD->setInvalidDecl();
8674 
8675     return NewFD;
8676   }
8677 
8678   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8679 
8680   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8681   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8682     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8683                  diag::err_constexpr_wrong_decl_kind)
8684         << static_cast<int>(ConstexprKind);
8685     ConstexprKind = ConstexprSpecKind::Unspecified;
8686     D.getMutableDeclSpec().ClearConstexprSpec();
8687   }
8688   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8689 
8690   // Check that the return type is not an abstract class type.
8691   // For record types, this is done by the AbstractClassUsageDiagnoser once
8692   // the class has been completely parsed.
8693   if (!DC->isRecord() &&
8694       SemaRef.RequireNonAbstractType(
8695           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8696           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8697     D.setInvalidType();
8698 
8699   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8700     // This is a C++ constructor declaration.
8701     assert(DC->isRecord() &&
8702            "Constructors can only be declared in a member context");
8703 
8704     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8705     return CXXConstructorDecl::Create(
8706         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8707         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8708         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8709         InheritedConstructor(), TrailingRequiresClause);
8710 
8711   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8712     // This is a C++ destructor declaration.
8713     if (DC->isRecord()) {
8714       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8715       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8716       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8717           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8718           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8719           /*isImplicitlyDeclared=*/false, ConstexprKind,
8720           TrailingRequiresClause);
8721 
8722       // If the destructor needs an implicit exception specification, set it
8723       // now. FIXME: It'd be nice to be able to create the right type to start
8724       // with, but the type needs to reference the destructor declaration.
8725       if (SemaRef.getLangOpts().CPlusPlus11)
8726         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8727 
8728       IsVirtualOkay = true;
8729       return NewDD;
8730 
8731     } else {
8732       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8733       D.setInvalidType();
8734 
8735       // Create a FunctionDecl to satisfy the function definition parsing
8736       // code path.
8737       return FunctionDecl::Create(
8738           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8739           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8740           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8741     }
8742 
8743   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8744     if (!DC->isRecord()) {
8745       SemaRef.Diag(D.getIdentifierLoc(),
8746            diag::err_conv_function_not_member);
8747       return nullptr;
8748     }
8749 
8750     SemaRef.CheckConversionDeclarator(D, R, SC);
8751     if (D.isInvalidType())
8752       return nullptr;
8753 
8754     IsVirtualOkay = true;
8755     return CXXConversionDecl::Create(
8756         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8757         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8758         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8759         TrailingRequiresClause);
8760 
8761   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8762     if (TrailingRequiresClause)
8763       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8764                    diag::err_trailing_requires_clause_on_deduction_guide)
8765           << TrailingRequiresClause->getSourceRange();
8766     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8767 
8768     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8769                                          ExplicitSpecifier, NameInfo, R, TInfo,
8770                                          D.getEndLoc());
8771   } else if (DC->isRecord()) {
8772     // If the name of the function is the same as the name of the record,
8773     // then this must be an invalid constructor that has a return type.
8774     // (The parser checks for a return type and makes the declarator a
8775     // constructor if it has no return type).
8776     if (Name.getAsIdentifierInfo() &&
8777         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8778       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8779         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8780         << SourceRange(D.getIdentifierLoc());
8781       return nullptr;
8782     }
8783 
8784     // This is a C++ method declaration.
8785     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8786         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8787         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8788         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8789     IsVirtualOkay = !Ret->isStatic();
8790     return Ret;
8791   } else {
8792     bool isFriend =
8793         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8794     if (!isFriend && SemaRef.CurContext->isRecord())
8795       return nullptr;
8796 
8797     // Determine whether the function was written with a
8798     // prototype. This true when:
8799     //   - we're in C++ (where every function has a prototype),
8800     return FunctionDecl::Create(
8801         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8802         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8803         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8804   }
8805 }
8806 
8807 enum OpenCLParamType {
8808   ValidKernelParam,
8809   PtrPtrKernelParam,
8810   PtrKernelParam,
8811   InvalidAddrSpacePtrKernelParam,
8812   InvalidKernelParam,
8813   RecordKernelParam
8814 };
8815 
8816 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8817   // Size dependent types are just typedefs to normal integer types
8818   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8819   // integers other than by their names.
8820   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8821 
8822   // Remove typedefs one by one until we reach a typedef
8823   // for a size dependent type.
8824   QualType DesugaredTy = Ty;
8825   do {
8826     ArrayRef<StringRef> Names(SizeTypeNames);
8827     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8828     if (Names.end() != Match)
8829       return true;
8830 
8831     Ty = DesugaredTy;
8832     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8833   } while (DesugaredTy != Ty);
8834 
8835   return false;
8836 }
8837 
8838 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8839   if (PT->isDependentType())
8840     return InvalidKernelParam;
8841 
8842   if (PT->isPointerType() || PT->isReferenceType()) {
8843     QualType PointeeType = PT->getPointeeType();
8844     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8845         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8846         PointeeType.getAddressSpace() == LangAS::Default)
8847       return InvalidAddrSpacePtrKernelParam;
8848 
8849     if (PointeeType->isPointerType()) {
8850       // This is a pointer to pointer parameter.
8851       // Recursively check inner type.
8852       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8853       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8854           ParamKind == InvalidKernelParam)
8855         return ParamKind;
8856 
8857       return PtrPtrKernelParam;
8858     }
8859 
8860     // C++ for OpenCL v1.0 s2.4:
8861     // Moreover the types used in parameters of the kernel functions must be:
8862     // Standard layout types for pointer parameters. The same applies to
8863     // reference if an implementation supports them in kernel parameters.
8864     if (S.getLangOpts().OpenCLCPlusPlus &&
8865         !S.getOpenCLOptions().isAvailableOption(
8866             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8867         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8868         !PointeeType->isStandardLayoutType())
8869       return InvalidKernelParam;
8870 
8871     return PtrKernelParam;
8872   }
8873 
8874   // OpenCL v1.2 s6.9.k:
8875   // Arguments to kernel functions in a program cannot be declared with the
8876   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8877   // uintptr_t or a struct and/or union that contain fields declared to be one
8878   // of these built-in scalar types.
8879   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8880     return InvalidKernelParam;
8881 
8882   if (PT->isImageType())
8883     return PtrKernelParam;
8884 
8885   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8886     return InvalidKernelParam;
8887 
8888   // OpenCL extension spec v1.2 s9.5:
8889   // This extension adds support for half scalar and vector types as built-in
8890   // types that can be used for arithmetic operations, conversions etc.
8891   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8892       PT->isHalfType())
8893     return InvalidKernelParam;
8894 
8895   // Look into an array argument to check if it has a forbidden type.
8896   if (PT->isArrayType()) {
8897     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8898     // Call ourself to check an underlying type of an array. Since the
8899     // getPointeeOrArrayElementType returns an innermost type which is not an
8900     // array, this recursive call only happens once.
8901     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8902   }
8903 
8904   // C++ for OpenCL v1.0 s2.4:
8905   // Moreover the types used in parameters of the kernel functions must be:
8906   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8907   // types) for parameters passed by value;
8908   if (S.getLangOpts().OpenCLCPlusPlus &&
8909       !S.getOpenCLOptions().isAvailableOption(
8910           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8911       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8912     return InvalidKernelParam;
8913 
8914   if (PT->isRecordType())
8915     return RecordKernelParam;
8916 
8917   return ValidKernelParam;
8918 }
8919 
8920 static void checkIsValidOpenCLKernelParameter(
8921   Sema &S,
8922   Declarator &D,
8923   ParmVarDecl *Param,
8924   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8925   QualType PT = Param->getType();
8926 
8927   // Cache the valid types we encounter to avoid rechecking structs that are
8928   // used again
8929   if (ValidTypes.count(PT.getTypePtr()))
8930     return;
8931 
8932   switch (getOpenCLKernelParameterType(S, PT)) {
8933   case PtrPtrKernelParam:
8934     // OpenCL v3.0 s6.11.a:
8935     // A kernel function argument cannot be declared as a pointer to a pointer
8936     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8937     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8938       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8939       D.setInvalidType();
8940       return;
8941     }
8942 
8943     ValidTypes.insert(PT.getTypePtr());
8944     return;
8945 
8946   case InvalidAddrSpacePtrKernelParam:
8947     // OpenCL v1.0 s6.5:
8948     // __kernel function arguments declared to be a pointer of a type can point
8949     // to one of the following address spaces only : __global, __local or
8950     // __constant.
8951     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8952     D.setInvalidType();
8953     return;
8954 
8955     // OpenCL v1.2 s6.9.k:
8956     // Arguments to kernel functions in a program cannot be declared with the
8957     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8958     // uintptr_t or a struct and/or union that contain fields declared to be
8959     // one of these built-in scalar types.
8960 
8961   case InvalidKernelParam:
8962     // OpenCL v1.2 s6.8 n:
8963     // A kernel function argument cannot be declared
8964     // of event_t type.
8965     // Do not diagnose half type since it is diagnosed as invalid argument
8966     // type for any function elsewhere.
8967     if (!PT->isHalfType()) {
8968       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8969 
8970       // Explain what typedefs are involved.
8971       const TypedefType *Typedef = nullptr;
8972       while ((Typedef = PT->getAs<TypedefType>())) {
8973         SourceLocation Loc = Typedef->getDecl()->getLocation();
8974         // SourceLocation may be invalid for a built-in type.
8975         if (Loc.isValid())
8976           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8977         PT = Typedef->desugar();
8978       }
8979     }
8980 
8981     D.setInvalidType();
8982     return;
8983 
8984   case PtrKernelParam:
8985   case ValidKernelParam:
8986     ValidTypes.insert(PT.getTypePtr());
8987     return;
8988 
8989   case RecordKernelParam:
8990     break;
8991   }
8992 
8993   // Track nested structs we will inspect
8994   SmallVector<const Decl *, 4> VisitStack;
8995 
8996   // Track where we are in the nested structs. Items will migrate from
8997   // VisitStack to HistoryStack as we do the DFS for bad field.
8998   SmallVector<const FieldDecl *, 4> HistoryStack;
8999   HistoryStack.push_back(nullptr);
9000 
9001   // At this point we already handled everything except of a RecordType or
9002   // an ArrayType of a RecordType.
9003   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9004   const RecordType *RecTy =
9005       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9006   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9007 
9008   VisitStack.push_back(RecTy->getDecl());
9009   assert(VisitStack.back() && "First decl null?");
9010 
9011   do {
9012     const Decl *Next = VisitStack.pop_back_val();
9013     if (!Next) {
9014       assert(!HistoryStack.empty());
9015       // Found a marker, we have gone up a level
9016       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9017         ValidTypes.insert(Hist->getType().getTypePtr());
9018 
9019       continue;
9020     }
9021 
9022     // Adds everything except the original parameter declaration (which is not a
9023     // field itself) to the history stack.
9024     const RecordDecl *RD;
9025     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9026       HistoryStack.push_back(Field);
9027 
9028       QualType FieldTy = Field->getType();
9029       // Other field types (known to be valid or invalid) are handled while we
9030       // walk around RecordDecl::fields().
9031       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9032              "Unexpected type.");
9033       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9034 
9035       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9036     } else {
9037       RD = cast<RecordDecl>(Next);
9038     }
9039 
9040     // Add a null marker so we know when we've gone back up a level
9041     VisitStack.push_back(nullptr);
9042 
9043     for (const auto *FD : RD->fields()) {
9044       QualType QT = FD->getType();
9045 
9046       if (ValidTypes.count(QT.getTypePtr()))
9047         continue;
9048 
9049       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9050       if (ParamType == ValidKernelParam)
9051         continue;
9052 
9053       if (ParamType == RecordKernelParam) {
9054         VisitStack.push_back(FD);
9055         continue;
9056       }
9057 
9058       // OpenCL v1.2 s6.9.p:
9059       // Arguments to kernel functions that are declared to be a struct or union
9060       // do not allow OpenCL objects to be passed as elements of the struct or
9061       // union.
9062       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9063           ParamType == InvalidAddrSpacePtrKernelParam) {
9064         S.Diag(Param->getLocation(),
9065                diag::err_record_with_pointers_kernel_param)
9066           << PT->isUnionType()
9067           << PT;
9068       } else {
9069         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9070       }
9071 
9072       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9073           << OrigRecDecl->getDeclName();
9074 
9075       // We have an error, now let's go back up through history and show where
9076       // the offending field came from
9077       for (ArrayRef<const FieldDecl *>::const_iterator
9078                I = HistoryStack.begin() + 1,
9079                E = HistoryStack.end();
9080            I != E; ++I) {
9081         const FieldDecl *OuterField = *I;
9082         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9083           << OuterField->getType();
9084       }
9085 
9086       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9087         << QT->isPointerType()
9088         << QT;
9089       D.setInvalidType();
9090       return;
9091     }
9092   } while (!VisitStack.empty());
9093 }
9094 
9095 /// Find the DeclContext in which a tag is implicitly declared if we see an
9096 /// elaborated type specifier in the specified context, and lookup finds
9097 /// nothing.
9098 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9099   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9100     DC = DC->getParent();
9101   return DC;
9102 }
9103 
9104 /// Find the Scope in which a tag is implicitly declared if we see an
9105 /// elaborated type specifier in the specified context, and lookup finds
9106 /// nothing.
9107 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9108   while (S->isClassScope() ||
9109          (LangOpts.CPlusPlus &&
9110           S->isFunctionPrototypeScope()) ||
9111          ((S->getFlags() & Scope::DeclScope) == 0) ||
9112          (S->getEntity() && S->getEntity()->isTransparentContext()))
9113     S = S->getParent();
9114   return S;
9115 }
9116 
9117 NamedDecl*
9118 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9119                               TypeSourceInfo *TInfo, LookupResult &Previous,
9120                               MultiTemplateParamsArg TemplateParamListsRef,
9121                               bool &AddToScope) {
9122   QualType R = TInfo->getType();
9123 
9124   assert(R->isFunctionType());
9125   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9126     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9127 
9128   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9129   for (TemplateParameterList *TPL : TemplateParamListsRef)
9130     TemplateParamLists.push_back(TPL);
9131   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9132     if (!TemplateParamLists.empty() &&
9133         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9134       TemplateParamLists.back() = Invented;
9135     else
9136       TemplateParamLists.push_back(Invented);
9137   }
9138 
9139   // TODO: consider using NameInfo for diagnostic.
9140   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9141   DeclarationName Name = NameInfo.getName();
9142   StorageClass SC = getFunctionStorageClass(*this, D);
9143 
9144   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9145     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9146          diag::err_invalid_thread)
9147       << DeclSpec::getSpecifierName(TSCS);
9148 
9149   if (D.isFirstDeclarationOfMember())
9150     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9151                            D.getIdentifierLoc());
9152 
9153   bool isFriend = false;
9154   FunctionTemplateDecl *FunctionTemplate = nullptr;
9155   bool isMemberSpecialization = false;
9156   bool isFunctionTemplateSpecialization = false;
9157 
9158   bool isDependentClassScopeExplicitSpecialization = false;
9159   bool HasExplicitTemplateArgs = false;
9160   TemplateArgumentListInfo TemplateArgs;
9161 
9162   bool isVirtualOkay = false;
9163 
9164   DeclContext *OriginalDC = DC;
9165   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9166 
9167   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9168                                               isVirtualOkay);
9169   if (!NewFD) return nullptr;
9170 
9171   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9172     NewFD->setTopLevelDeclInObjCContainer();
9173 
9174   // Set the lexical context. If this is a function-scope declaration, or has a
9175   // C++ scope specifier, or is the object of a friend declaration, the lexical
9176   // context will be different from the semantic context.
9177   NewFD->setLexicalDeclContext(CurContext);
9178 
9179   if (IsLocalExternDecl)
9180     NewFD->setLocalExternDecl();
9181 
9182   if (getLangOpts().CPlusPlus) {
9183     bool isInline = D.getDeclSpec().isInlineSpecified();
9184     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9185     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9186     isFriend = D.getDeclSpec().isFriendSpecified();
9187     if (isFriend && !isInline && D.isFunctionDefinition()) {
9188       // C++ [class.friend]p5
9189       //   A function can be defined in a friend declaration of a
9190       //   class . . . . Such a function is implicitly inline.
9191       NewFD->setImplicitlyInline();
9192     }
9193 
9194     // If this is a method defined in an __interface, and is not a constructor
9195     // or an overloaded operator, then set the pure flag (isVirtual will already
9196     // return true).
9197     if (const CXXRecordDecl *Parent =
9198           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9199       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9200         NewFD->setPure(true);
9201 
9202       // C++ [class.union]p2
9203       //   A union can have member functions, but not virtual functions.
9204       if (isVirtual && Parent->isUnion()) {
9205         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9206         NewFD->setInvalidDecl();
9207       }
9208       if ((Parent->isClass() || Parent->isStruct()) &&
9209           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9210           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9211           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9212         if (auto *Def = Parent->getDefinition())
9213           Def->setInitMethod(true);
9214       }
9215     }
9216 
9217     SetNestedNameSpecifier(*this, NewFD, D);
9218     isMemberSpecialization = false;
9219     isFunctionTemplateSpecialization = false;
9220     if (D.isInvalidType())
9221       NewFD->setInvalidDecl();
9222 
9223     // Match up the template parameter lists with the scope specifier, then
9224     // determine whether we have a template or a template specialization.
9225     bool Invalid = false;
9226     TemplateParameterList *TemplateParams =
9227         MatchTemplateParametersToScopeSpecifier(
9228             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9229             D.getCXXScopeSpec(),
9230             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9231                 ? D.getName().TemplateId
9232                 : nullptr,
9233             TemplateParamLists, isFriend, isMemberSpecialization,
9234             Invalid);
9235     if (TemplateParams) {
9236       // Check that we can declare a template here.
9237       if (CheckTemplateDeclScope(S, TemplateParams))
9238         NewFD->setInvalidDecl();
9239 
9240       if (TemplateParams->size() > 0) {
9241         // This is a function template
9242 
9243         // A destructor cannot be a template.
9244         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9245           Diag(NewFD->getLocation(), diag::err_destructor_template);
9246           NewFD->setInvalidDecl();
9247         }
9248 
9249         // If we're adding a template to a dependent context, we may need to
9250         // rebuilding some of the types used within the template parameter list,
9251         // now that we know what the current instantiation is.
9252         if (DC->isDependentContext()) {
9253           ContextRAII SavedContext(*this, DC);
9254           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9255             Invalid = true;
9256         }
9257 
9258         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9259                                                         NewFD->getLocation(),
9260                                                         Name, TemplateParams,
9261                                                         NewFD);
9262         FunctionTemplate->setLexicalDeclContext(CurContext);
9263         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9264 
9265         // For source fidelity, store the other template param lists.
9266         if (TemplateParamLists.size() > 1) {
9267           NewFD->setTemplateParameterListsInfo(Context,
9268               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9269                   .drop_back(1));
9270         }
9271       } else {
9272         // This is a function template specialization.
9273         isFunctionTemplateSpecialization = true;
9274         // For source fidelity, store all the template param lists.
9275         if (TemplateParamLists.size() > 0)
9276           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9277 
9278         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9279         if (isFriend) {
9280           // We want to remove the "template<>", found here.
9281           SourceRange RemoveRange = TemplateParams->getSourceRange();
9282 
9283           // If we remove the template<> and the name is not a
9284           // template-id, we're actually silently creating a problem:
9285           // the friend declaration will refer to an untemplated decl,
9286           // and clearly the user wants a template specialization.  So
9287           // we need to insert '<>' after the name.
9288           SourceLocation InsertLoc;
9289           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9290             InsertLoc = D.getName().getSourceRange().getEnd();
9291             InsertLoc = getLocForEndOfToken(InsertLoc);
9292           }
9293 
9294           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9295             << Name << RemoveRange
9296             << FixItHint::CreateRemoval(RemoveRange)
9297             << FixItHint::CreateInsertion(InsertLoc, "<>");
9298           Invalid = true;
9299         }
9300       }
9301     } else {
9302       // Check that we can declare a template here.
9303       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9304           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9305         NewFD->setInvalidDecl();
9306 
9307       // All template param lists were matched against the scope specifier:
9308       // this is NOT (an explicit specialization of) a template.
9309       if (TemplateParamLists.size() > 0)
9310         // For source fidelity, store all the template param lists.
9311         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9312     }
9313 
9314     if (Invalid) {
9315       NewFD->setInvalidDecl();
9316       if (FunctionTemplate)
9317         FunctionTemplate->setInvalidDecl();
9318     }
9319 
9320     // C++ [dcl.fct.spec]p5:
9321     //   The virtual specifier shall only be used in declarations of
9322     //   nonstatic class member functions that appear within a
9323     //   member-specification of a class declaration; see 10.3.
9324     //
9325     if (isVirtual && !NewFD->isInvalidDecl()) {
9326       if (!isVirtualOkay) {
9327         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9328              diag::err_virtual_non_function);
9329       } else if (!CurContext->isRecord()) {
9330         // 'virtual' was specified outside of the class.
9331         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9332              diag::err_virtual_out_of_class)
9333           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9334       } else if (NewFD->getDescribedFunctionTemplate()) {
9335         // C++ [temp.mem]p3:
9336         //  A member function template shall not be virtual.
9337         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9338              diag::err_virtual_member_function_template)
9339           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9340       } else {
9341         // Okay: Add virtual to the method.
9342         NewFD->setVirtualAsWritten(true);
9343       }
9344 
9345       if (getLangOpts().CPlusPlus14 &&
9346           NewFD->getReturnType()->isUndeducedType())
9347         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9348     }
9349 
9350     if (getLangOpts().CPlusPlus14 &&
9351         (NewFD->isDependentContext() ||
9352          (isFriend && CurContext->isDependentContext())) &&
9353         NewFD->getReturnType()->isUndeducedType()) {
9354       // If the function template is referenced directly (for instance, as a
9355       // member of the current instantiation), pretend it has a dependent type.
9356       // This is not really justified by the standard, but is the only sane
9357       // thing to do.
9358       // FIXME: For a friend function, we have not marked the function as being
9359       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9360       const FunctionProtoType *FPT =
9361           NewFD->getType()->castAs<FunctionProtoType>();
9362       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9363       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9364                                              FPT->getExtProtoInfo()));
9365     }
9366 
9367     // C++ [dcl.fct.spec]p3:
9368     //  The inline specifier shall not appear on a block scope function
9369     //  declaration.
9370     if (isInline && !NewFD->isInvalidDecl()) {
9371       if (CurContext->isFunctionOrMethod()) {
9372         // 'inline' is not allowed on block scope function declaration.
9373         Diag(D.getDeclSpec().getInlineSpecLoc(),
9374              diag::err_inline_declaration_block_scope) << Name
9375           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9376       }
9377     }
9378 
9379     // C++ [dcl.fct.spec]p6:
9380     //  The explicit specifier shall be used only in the declaration of a
9381     //  constructor or conversion function within its class definition;
9382     //  see 12.3.1 and 12.3.2.
9383     if (hasExplicit && !NewFD->isInvalidDecl() &&
9384         !isa<CXXDeductionGuideDecl>(NewFD)) {
9385       if (!CurContext->isRecord()) {
9386         // 'explicit' was specified outside of the class.
9387         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9388              diag::err_explicit_out_of_class)
9389             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9390       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9391                  !isa<CXXConversionDecl>(NewFD)) {
9392         // 'explicit' was specified on a function that wasn't a constructor
9393         // or conversion function.
9394         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9395              diag::err_explicit_non_ctor_or_conv_function)
9396             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9397       }
9398     }
9399 
9400     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9401     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9402       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9403       // are implicitly inline.
9404       NewFD->setImplicitlyInline();
9405 
9406       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9407       // be either constructors or to return a literal type. Therefore,
9408       // destructors cannot be declared constexpr.
9409       if (isa<CXXDestructorDecl>(NewFD) &&
9410           (!getLangOpts().CPlusPlus20 ||
9411            ConstexprKind == ConstexprSpecKind::Consteval)) {
9412         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9413             << static_cast<int>(ConstexprKind);
9414         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9415                                     ? ConstexprSpecKind::Unspecified
9416                                     : ConstexprSpecKind::Constexpr);
9417       }
9418       // C++20 [dcl.constexpr]p2: An allocation function, or a
9419       // deallocation function shall not be declared with the consteval
9420       // specifier.
9421       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9422           (NewFD->getOverloadedOperator() == OO_New ||
9423            NewFD->getOverloadedOperator() == OO_Array_New ||
9424            NewFD->getOverloadedOperator() == OO_Delete ||
9425            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9426         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9427              diag::err_invalid_consteval_decl_kind)
9428             << NewFD;
9429         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9430       }
9431     }
9432 
9433     // If __module_private__ was specified, mark the function accordingly.
9434     if (D.getDeclSpec().isModulePrivateSpecified()) {
9435       if (isFunctionTemplateSpecialization) {
9436         SourceLocation ModulePrivateLoc
9437           = D.getDeclSpec().getModulePrivateSpecLoc();
9438         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9439           << 0
9440           << FixItHint::CreateRemoval(ModulePrivateLoc);
9441       } else {
9442         NewFD->setModulePrivate();
9443         if (FunctionTemplate)
9444           FunctionTemplate->setModulePrivate();
9445       }
9446     }
9447 
9448     if (isFriend) {
9449       if (FunctionTemplate) {
9450         FunctionTemplate->setObjectOfFriendDecl();
9451         FunctionTemplate->setAccess(AS_public);
9452       }
9453       NewFD->setObjectOfFriendDecl();
9454       NewFD->setAccess(AS_public);
9455     }
9456 
9457     // If a function is defined as defaulted or deleted, mark it as such now.
9458     // We'll do the relevant checks on defaulted / deleted functions later.
9459     switch (D.getFunctionDefinitionKind()) {
9460     case FunctionDefinitionKind::Declaration:
9461     case FunctionDefinitionKind::Definition:
9462       break;
9463 
9464     case FunctionDefinitionKind::Defaulted:
9465       NewFD->setDefaulted();
9466       break;
9467 
9468     case FunctionDefinitionKind::Deleted:
9469       NewFD->setDeletedAsWritten();
9470       break;
9471     }
9472 
9473     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9474         D.isFunctionDefinition()) {
9475       // C++ [class.mfct]p2:
9476       //   A member function may be defined (8.4) in its class definition, in
9477       //   which case it is an inline member function (7.1.2)
9478       NewFD->setImplicitlyInline();
9479     }
9480 
9481     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9482         !CurContext->isRecord()) {
9483       // C++ [class.static]p1:
9484       //   A data or function member of a class may be declared static
9485       //   in a class definition, in which case it is a static member of
9486       //   the class.
9487 
9488       // Complain about the 'static' specifier if it's on an out-of-line
9489       // member function definition.
9490 
9491       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9492       // member function template declaration and class member template
9493       // declaration (MSVC versions before 2015), warn about this.
9494       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9495            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9496              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9497            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9498            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9499         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9500     }
9501 
9502     // C++11 [except.spec]p15:
9503     //   A deallocation function with no exception-specification is treated
9504     //   as if it were specified with noexcept(true).
9505     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9506     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9507          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9508         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9509       NewFD->setType(Context.getFunctionType(
9510           FPT->getReturnType(), FPT->getParamTypes(),
9511           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9512   }
9513 
9514   // Filter out previous declarations that don't match the scope.
9515   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9516                        D.getCXXScopeSpec().isNotEmpty() ||
9517                        isMemberSpecialization ||
9518                        isFunctionTemplateSpecialization);
9519 
9520   // Handle GNU asm-label extension (encoded as an attribute).
9521   if (Expr *E = (Expr*) D.getAsmLabel()) {
9522     // The parser guarantees this is a string.
9523     StringLiteral *SE = cast<StringLiteral>(E);
9524     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9525                                         /*IsLiteralLabel=*/true,
9526                                         SE->getStrTokenLoc(0)));
9527   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9528     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9529       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9530     if (I != ExtnameUndeclaredIdentifiers.end()) {
9531       if (isDeclExternC(NewFD)) {
9532         NewFD->addAttr(I->second);
9533         ExtnameUndeclaredIdentifiers.erase(I);
9534       } else
9535         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9536             << /*Variable*/0 << NewFD;
9537     }
9538   }
9539 
9540   // Copy the parameter declarations from the declarator D to the function
9541   // declaration NewFD, if they are available.  First scavenge them into Params.
9542   SmallVector<ParmVarDecl*, 16> Params;
9543   unsigned FTIIdx;
9544   if (D.isFunctionDeclarator(FTIIdx)) {
9545     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9546 
9547     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9548     // function that takes no arguments, not a function that takes a
9549     // single void argument.
9550     // We let through "const void" here because Sema::GetTypeForDeclarator
9551     // already checks for that case.
9552     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9553       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9554         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9555         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9556         Param->setDeclContext(NewFD);
9557         Params.push_back(Param);
9558 
9559         if (Param->isInvalidDecl())
9560           NewFD->setInvalidDecl();
9561       }
9562     }
9563 
9564     if (!getLangOpts().CPlusPlus) {
9565       // In C, find all the tag declarations from the prototype and move them
9566       // into the function DeclContext. Remove them from the surrounding tag
9567       // injection context of the function, which is typically but not always
9568       // the TU.
9569       DeclContext *PrototypeTagContext =
9570           getTagInjectionContext(NewFD->getLexicalDeclContext());
9571       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9572         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9573 
9574         // We don't want to reparent enumerators. Look at their parent enum
9575         // instead.
9576         if (!TD) {
9577           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9578             TD = cast<EnumDecl>(ECD->getDeclContext());
9579         }
9580         if (!TD)
9581           continue;
9582         DeclContext *TagDC = TD->getLexicalDeclContext();
9583         if (!TagDC->containsDecl(TD))
9584           continue;
9585         TagDC->removeDecl(TD);
9586         TD->setDeclContext(NewFD);
9587         NewFD->addDecl(TD);
9588 
9589         // Preserve the lexical DeclContext if it is not the surrounding tag
9590         // injection context of the FD. In this example, the semantic context of
9591         // E will be f and the lexical context will be S, while both the
9592         // semantic and lexical contexts of S will be f:
9593         //   void f(struct S { enum E { a } f; } s);
9594         if (TagDC != PrototypeTagContext)
9595           TD->setLexicalDeclContext(TagDC);
9596       }
9597     }
9598   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9599     // When we're declaring a function with a typedef, typeof, etc as in the
9600     // following example, we'll need to synthesize (unnamed)
9601     // parameters for use in the declaration.
9602     //
9603     // @code
9604     // typedef void fn(int);
9605     // fn f;
9606     // @endcode
9607 
9608     // Synthesize a parameter for each argument type.
9609     for (const auto &AI : FT->param_types()) {
9610       ParmVarDecl *Param =
9611           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9612       Param->setScopeInfo(0, Params.size());
9613       Params.push_back(Param);
9614     }
9615   } else {
9616     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9617            "Should not need args for typedef of non-prototype fn");
9618   }
9619 
9620   // Finally, we know we have the right number of parameters, install them.
9621   NewFD->setParams(Params);
9622 
9623   if (D.getDeclSpec().isNoreturnSpecified())
9624     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9625                                            D.getDeclSpec().getNoreturnSpecLoc(),
9626                                            AttributeCommonInfo::AS_Keyword));
9627 
9628   // Functions returning a variably modified type violate C99 6.7.5.2p2
9629   // because all functions have linkage.
9630   if (!NewFD->isInvalidDecl() &&
9631       NewFD->getReturnType()->isVariablyModifiedType()) {
9632     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9633     NewFD->setInvalidDecl();
9634   }
9635 
9636   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9637   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9638       !NewFD->hasAttr<SectionAttr>())
9639     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9640         Context, PragmaClangTextSection.SectionName,
9641         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9642 
9643   // Apply an implicit SectionAttr if #pragma code_seg is active.
9644   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9645       !NewFD->hasAttr<SectionAttr>()) {
9646     NewFD->addAttr(SectionAttr::CreateImplicit(
9647         Context, CodeSegStack.CurrentValue->getString(),
9648         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9649         SectionAttr::Declspec_allocate));
9650     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9651                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9652                          ASTContext::PSF_Read,
9653                      NewFD))
9654       NewFD->dropAttr<SectionAttr>();
9655   }
9656 
9657   // Apply an implicit CodeSegAttr from class declspec or
9658   // apply an implicit SectionAttr from #pragma code_seg if active.
9659   if (!NewFD->hasAttr<CodeSegAttr>()) {
9660     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9661                                                                  D.isFunctionDefinition())) {
9662       NewFD->addAttr(SAttr);
9663     }
9664   }
9665 
9666   // Handle attributes.
9667   ProcessDeclAttributes(S, NewFD, D);
9668 
9669   if (getLangOpts().OpenCL) {
9670     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9671     // type declaration will generate a compilation error.
9672     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9673     if (AddressSpace != LangAS::Default) {
9674       Diag(NewFD->getLocation(),
9675            diag::err_opencl_return_value_with_address_space);
9676       NewFD->setInvalidDecl();
9677     }
9678   }
9679 
9680   if (!getLangOpts().CPlusPlus) {
9681     // Perform semantic checking on the function declaration.
9682     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9683       CheckMain(NewFD, D.getDeclSpec());
9684 
9685     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9686       CheckMSVCRTEntryPoint(NewFD);
9687 
9688     if (!NewFD->isInvalidDecl())
9689       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9690                                                   isMemberSpecialization));
9691     else if (!Previous.empty())
9692       // Recover gracefully from an invalid redeclaration.
9693       D.setRedeclaration(true);
9694     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9695             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9696            "previous declaration set still overloaded");
9697 
9698     // Diagnose no-prototype function declarations with calling conventions that
9699     // don't support variadic calls. Only do this in C and do it after merging
9700     // possibly prototyped redeclarations.
9701     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9702     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9703       CallingConv CC = FT->getExtInfo().getCC();
9704       if (!supportsVariadicCall(CC)) {
9705         // Windows system headers sometimes accidentally use stdcall without
9706         // (void) parameters, so we relax this to a warning.
9707         int DiagID =
9708             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9709         Diag(NewFD->getLocation(), DiagID)
9710             << FunctionType::getNameForCallConv(CC);
9711       }
9712     }
9713 
9714    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9715        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9716      checkNonTrivialCUnion(NewFD->getReturnType(),
9717                            NewFD->getReturnTypeSourceRange().getBegin(),
9718                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9719   } else {
9720     // C++11 [replacement.functions]p3:
9721     //  The program's definitions shall not be specified as inline.
9722     //
9723     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9724     //
9725     // Suppress the diagnostic if the function is __attribute__((used)), since
9726     // that forces an external definition to be emitted.
9727     if (D.getDeclSpec().isInlineSpecified() &&
9728         NewFD->isReplaceableGlobalAllocationFunction() &&
9729         !NewFD->hasAttr<UsedAttr>())
9730       Diag(D.getDeclSpec().getInlineSpecLoc(),
9731            diag::ext_operator_new_delete_declared_inline)
9732         << NewFD->getDeclName();
9733 
9734     // If the declarator is a template-id, translate the parser's template
9735     // argument list into our AST format.
9736     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9737       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9738       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9739       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9740       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9741                                          TemplateId->NumArgs);
9742       translateTemplateArguments(TemplateArgsPtr,
9743                                  TemplateArgs);
9744 
9745       HasExplicitTemplateArgs = true;
9746 
9747       if (NewFD->isInvalidDecl()) {
9748         HasExplicitTemplateArgs = false;
9749       } else if (FunctionTemplate) {
9750         // Function template with explicit template arguments.
9751         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9752           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9753 
9754         HasExplicitTemplateArgs = false;
9755       } else {
9756         assert((isFunctionTemplateSpecialization ||
9757                 D.getDeclSpec().isFriendSpecified()) &&
9758                "should have a 'template<>' for this decl");
9759         // "friend void foo<>(int);" is an implicit specialization decl.
9760         isFunctionTemplateSpecialization = true;
9761       }
9762     } else if (isFriend && isFunctionTemplateSpecialization) {
9763       // This combination is only possible in a recovery case;  the user
9764       // wrote something like:
9765       //   template <> friend void foo(int);
9766       // which we're recovering from as if the user had written:
9767       //   friend void foo<>(int);
9768       // Go ahead and fake up a template id.
9769       HasExplicitTemplateArgs = true;
9770       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9771       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9772     }
9773 
9774     // We do not add HD attributes to specializations here because
9775     // they may have different constexpr-ness compared to their
9776     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9777     // may end up with different effective targets. Instead, a
9778     // specialization inherits its target attributes from its template
9779     // in the CheckFunctionTemplateSpecialization() call below.
9780     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9781       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9782 
9783     // If it's a friend (and only if it's a friend), it's possible
9784     // that either the specialized function type or the specialized
9785     // template is dependent, and therefore matching will fail.  In
9786     // this case, don't check the specialization yet.
9787     if (isFunctionTemplateSpecialization && isFriend &&
9788         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9789          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9790              TemplateArgs.arguments()))) {
9791       assert(HasExplicitTemplateArgs &&
9792              "friend function specialization without template args");
9793       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9794                                                        Previous))
9795         NewFD->setInvalidDecl();
9796     } else if (isFunctionTemplateSpecialization) {
9797       if (CurContext->isDependentContext() && CurContext->isRecord()
9798           && !isFriend) {
9799         isDependentClassScopeExplicitSpecialization = true;
9800       } else if (!NewFD->isInvalidDecl() &&
9801                  CheckFunctionTemplateSpecialization(
9802                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9803                      Previous))
9804         NewFD->setInvalidDecl();
9805 
9806       // C++ [dcl.stc]p1:
9807       //   A storage-class-specifier shall not be specified in an explicit
9808       //   specialization (14.7.3)
9809       FunctionTemplateSpecializationInfo *Info =
9810           NewFD->getTemplateSpecializationInfo();
9811       if (Info && SC != SC_None) {
9812         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9813           Diag(NewFD->getLocation(),
9814                diag::err_explicit_specialization_inconsistent_storage_class)
9815             << SC
9816             << FixItHint::CreateRemoval(
9817                                       D.getDeclSpec().getStorageClassSpecLoc());
9818 
9819         else
9820           Diag(NewFD->getLocation(),
9821                diag::ext_explicit_specialization_storage_class)
9822             << FixItHint::CreateRemoval(
9823                                       D.getDeclSpec().getStorageClassSpecLoc());
9824       }
9825     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9826       if (CheckMemberSpecialization(NewFD, Previous))
9827           NewFD->setInvalidDecl();
9828     }
9829 
9830     // Perform semantic checking on the function declaration.
9831     if (!isDependentClassScopeExplicitSpecialization) {
9832       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9833         CheckMain(NewFD, D.getDeclSpec());
9834 
9835       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9836         CheckMSVCRTEntryPoint(NewFD);
9837 
9838       if (!NewFD->isInvalidDecl())
9839         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9840                                                     isMemberSpecialization));
9841       else if (!Previous.empty())
9842         // Recover gracefully from an invalid redeclaration.
9843         D.setRedeclaration(true);
9844     }
9845 
9846     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9847             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9848            "previous declaration set still overloaded");
9849 
9850     NamedDecl *PrincipalDecl = (FunctionTemplate
9851                                 ? cast<NamedDecl>(FunctionTemplate)
9852                                 : NewFD);
9853 
9854     if (isFriend && NewFD->getPreviousDecl()) {
9855       AccessSpecifier Access = AS_public;
9856       if (!NewFD->isInvalidDecl())
9857         Access = NewFD->getPreviousDecl()->getAccess();
9858 
9859       NewFD->setAccess(Access);
9860       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9861     }
9862 
9863     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9864         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9865       PrincipalDecl->setNonMemberOperator();
9866 
9867     // If we have a function template, check the template parameter
9868     // list. This will check and merge default template arguments.
9869     if (FunctionTemplate) {
9870       FunctionTemplateDecl *PrevTemplate =
9871                                      FunctionTemplate->getPreviousDecl();
9872       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9873                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9874                                     : nullptr,
9875                             D.getDeclSpec().isFriendSpecified()
9876                               ? (D.isFunctionDefinition()
9877                                    ? TPC_FriendFunctionTemplateDefinition
9878                                    : TPC_FriendFunctionTemplate)
9879                               : (D.getCXXScopeSpec().isSet() &&
9880                                  DC && DC->isRecord() &&
9881                                  DC->isDependentContext())
9882                                   ? TPC_ClassTemplateMember
9883                                   : TPC_FunctionTemplate);
9884     }
9885 
9886     if (NewFD->isInvalidDecl()) {
9887       // Ignore all the rest of this.
9888     } else if (!D.isRedeclaration()) {
9889       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9890                                        AddToScope };
9891       // Fake up an access specifier if it's supposed to be a class member.
9892       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9893         NewFD->setAccess(AS_public);
9894 
9895       // Qualified decls generally require a previous declaration.
9896       if (D.getCXXScopeSpec().isSet()) {
9897         // ...with the major exception of templated-scope or
9898         // dependent-scope friend declarations.
9899 
9900         // TODO: we currently also suppress this check in dependent
9901         // contexts because (1) the parameter depth will be off when
9902         // matching friend templates and (2) we might actually be
9903         // selecting a friend based on a dependent factor.  But there
9904         // are situations where these conditions don't apply and we
9905         // can actually do this check immediately.
9906         //
9907         // Unless the scope is dependent, it's always an error if qualified
9908         // redeclaration lookup found nothing at all. Diagnose that now;
9909         // nothing will diagnose that error later.
9910         if (isFriend &&
9911             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9912              (!Previous.empty() && CurContext->isDependentContext()))) {
9913           // ignore these
9914         } else if (NewFD->isCPUDispatchMultiVersion() ||
9915                    NewFD->isCPUSpecificMultiVersion()) {
9916           // ignore this, we allow the redeclaration behavior here to create new
9917           // versions of the function.
9918         } else {
9919           // The user tried to provide an out-of-line definition for a
9920           // function that is a member of a class or namespace, but there
9921           // was no such member function declared (C++ [class.mfct]p2,
9922           // C++ [namespace.memdef]p2). For example:
9923           //
9924           // class X {
9925           //   void f() const;
9926           // };
9927           //
9928           // void X::f() { } // ill-formed
9929           //
9930           // Complain about this problem, and attempt to suggest close
9931           // matches (e.g., those that differ only in cv-qualifiers and
9932           // whether the parameter types are references).
9933 
9934           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9935                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9936             AddToScope = ExtraArgs.AddToScope;
9937             return Result;
9938           }
9939         }
9940 
9941         // Unqualified local friend declarations are required to resolve
9942         // to something.
9943       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9944         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9945                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9946           AddToScope = ExtraArgs.AddToScope;
9947           return Result;
9948         }
9949       }
9950     } else if (!D.isFunctionDefinition() &&
9951                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9952                !isFriend && !isFunctionTemplateSpecialization &&
9953                !isMemberSpecialization) {
9954       // An out-of-line member function declaration must also be a
9955       // definition (C++ [class.mfct]p2).
9956       // Note that this is not the case for explicit specializations of
9957       // function templates or member functions of class templates, per
9958       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9959       // extension for compatibility with old SWIG code which likes to
9960       // generate them.
9961       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9962         << D.getCXXScopeSpec().getRange();
9963     }
9964   }
9965 
9966   // If this is the first declaration of a library builtin function, add
9967   // attributes as appropriate.
9968   if (!D.isRedeclaration() &&
9969       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9970     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9971       if (unsigned BuiltinID = II->getBuiltinID()) {
9972         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9973           // Validate the type matches unless this builtin is specified as
9974           // matching regardless of its declared type.
9975           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9976             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9977           } else {
9978             ASTContext::GetBuiltinTypeError Error;
9979             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9980             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9981 
9982             if (!Error && !BuiltinType.isNull() &&
9983                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9984                     NewFD->getType(), BuiltinType))
9985               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9986           }
9987         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9988                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9989           // FIXME: We should consider this a builtin only in the std namespace.
9990           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9991         }
9992       }
9993     }
9994   }
9995 
9996   ProcessPragmaWeak(S, NewFD);
9997   checkAttributesAfterMerging(*this, *NewFD);
9998 
9999   AddKnownFunctionAttributes(NewFD);
10000 
10001   if (NewFD->hasAttr<OverloadableAttr>() &&
10002       !NewFD->getType()->getAs<FunctionProtoType>()) {
10003     Diag(NewFD->getLocation(),
10004          diag::err_attribute_overloadable_no_prototype)
10005       << NewFD;
10006 
10007     // Turn this into a variadic function with no parameters.
10008     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10009     FunctionProtoType::ExtProtoInfo EPI(
10010         Context.getDefaultCallingConvention(true, false));
10011     EPI.Variadic = true;
10012     EPI.ExtInfo = FT->getExtInfo();
10013 
10014     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10015     NewFD->setType(R);
10016   }
10017 
10018   // If there's a #pragma GCC visibility in scope, and this isn't a class
10019   // member, set the visibility of this function.
10020   if (!DC->isRecord() && NewFD->isExternallyVisible())
10021     AddPushedVisibilityAttribute(NewFD);
10022 
10023   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10024   // marking the function.
10025   AddCFAuditedAttribute(NewFD);
10026 
10027   // If this is a function definition, check if we have to apply optnone due to
10028   // a pragma.
10029   if(D.isFunctionDefinition())
10030     AddRangeBasedOptnone(NewFD);
10031 
10032   // If this is the first declaration of an extern C variable, update
10033   // the map of such variables.
10034   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10035       isIncompleteDeclExternC(*this, NewFD))
10036     RegisterLocallyScopedExternCDecl(NewFD, S);
10037 
10038   // Set this FunctionDecl's range up to the right paren.
10039   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10040 
10041   if (D.isRedeclaration() && !Previous.empty()) {
10042     NamedDecl *Prev = Previous.getRepresentativeDecl();
10043     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10044                                    isMemberSpecialization ||
10045                                        isFunctionTemplateSpecialization,
10046                                    D.isFunctionDefinition());
10047   }
10048 
10049   if (getLangOpts().CUDA) {
10050     IdentifierInfo *II = NewFD->getIdentifier();
10051     if (II && II->isStr(getCudaConfigureFuncName()) &&
10052         !NewFD->isInvalidDecl() &&
10053         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10054       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10055         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10056             << getCudaConfigureFuncName();
10057       Context.setcudaConfigureCallDecl(NewFD);
10058     }
10059 
10060     // Variadic functions, other than a *declaration* of printf, are not allowed
10061     // in device-side CUDA code, unless someone passed
10062     // -fcuda-allow-variadic-functions.
10063     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10064         (NewFD->hasAttr<CUDADeviceAttr>() ||
10065          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10066         !(II && II->isStr("printf") && NewFD->isExternC() &&
10067           !D.isFunctionDefinition())) {
10068       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10069     }
10070   }
10071 
10072   MarkUnusedFileScopedDecl(NewFD);
10073 
10074 
10075 
10076   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10077     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10078     if (SC == SC_Static) {
10079       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10080       D.setInvalidType();
10081     }
10082 
10083     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10084     if (!NewFD->getReturnType()->isVoidType()) {
10085       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10086       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10087           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10088                                 : FixItHint());
10089       D.setInvalidType();
10090     }
10091 
10092     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10093     for (auto Param : NewFD->parameters())
10094       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10095 
10096     if (getLangOpts().OpenCLCPlusPlus) {
10097       if (DC->isRecord()) {
10098         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10099         D.setInvalidType();
10100       }
10101       if (FunctionTemplate) {
10102         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10103         D.setInvalidType();
10104       }
10105     }
10106   }
10107 
10108   if (getLangOpts().CPlusPlus) {
10109     if (FunctionTemplate) {
10110       if (NewFD->isInvalidDecl())
10111         FunctionTemplate->setInvalidDecl();
10112       return FunctionTemplate;
10113     }
10114 
10115     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10116       CompleteMemberSpecialization(NewFD, Previous);
10117   }
10118 
10119   for (const ParmVarDecl *Param : NewFD->parameters()) {
10120     QualType PT = Param->getType();
10121 
10122     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10123     // types.
10124     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10125       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10126         QualType ElemTy = PipeTy->getElementType();
10127           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10128             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10129             D.setInvalidType();
10130           }
10131       }
10132     }
10133   }
10134 
10135   // Here we have an function template explicit specialization at class scope.
10136   // The actual specialization will be postponed to template instatiation
10137   // time via the ClassScopeFunctionSpecializationDecl node.
10138   if (isDependentClassScopeExplicitSpecialization) {
10139     ClassScopeFunctionSpecializationDecl *NewSpec =
10140                          ClassScopeFunctionSpecializationDecl::Create(
10141                                 Context, CurContext, NewFD->getLocation(),
10142                                 cast<CXXMethodDecl>(NewFD),
10143                                 HasExplicitTemplateArgs, TemplateArgs);
10144     CurContext->addDecl(NewSpec);
10145     AddToScope = false;
10146   }
10147 
10148   // Diagnose availability attributes. Availability cannot be used on functions
10149   // that are run during load/unload.
10150   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10151     if (NewFD->hasAttr<ConstructorAttr>()) {
10152       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10153           << 1;
10154       NewFD->dropAttr<AvailabilityAttr>();
10155     }
10156     if (NewFD->hasAttr<DestructorAttr>()) {
10157       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10158           << 2;
10159       NewFD->dropAttr<AvailabilityAttr>();
10160     }
10161   }
10162 
10163   // Diagnose no_builtin attribute on function declaration that are not a
10164   // definition.
10165   // FIXME: We should really be doing this in
10166   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10167   // the FunctionDecl and at this point of the code
10168   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10169   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10170   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10171     switch (D.getFunctionDefinitionKind()) {
10172     case FunctionDefinitionKind::Defaulted:
10173     case FunctionDefinitionKind::Deleted:
10174       Diag(NBA->getLocation(),
10175            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10176           << NBA->getSpelling();
10177       break;
10178     case FunctionDefinitionKind::Declaration:
10179       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10180           << NBA->getSpelling();
10181       break;
10182     case FunctionDefinitionKind::Definition:
10183       break;
10184     }
10185 
10186   return NewFD;
10187 }
10188 
10189 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10190 /// when __declspec(code_seg) "is applied to a class, all member functions of
10191 /// the class and nested classes -- this includes compiler-generated special
10192 /// member functions -- are put in the specified segment."
10193 /// The actual behavior is a little more complicated. The Microsoft compiler
10194 /// won't check outer classes if there is an active value from #pragma code_seg.
10195 /// The CodeSeg is always applied from the direct parent but only from outer
10196 /// classes when the #pragma code_seg stack is empty. See:
10197 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10198 /// available since MS has removed the page.
10199 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10200   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10201   if (!Method)
10202     return nullptr;
10203   const CXXRecordDecl *Parent = Method->getParent();
10204   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10205     Attr *NewAttr = SAttr->clone(S.getASTContext());
10206     NewAttr->setImplicit(true);
10207     return NewAttr;
10208   }
10209 
10210   // The Microsoft compiler won't check outer classes for the CodeSeg
10211   // when the #pragma code_seg stack is active.
10212   if (S.CodeSegStack.CurrentValue)
10213    return nullptr;
10214 
10215   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10216     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10217       Attr *NewAttr = SAttr->clone(S.getASTContext());
10218       NewAttr->setImplicit(true);
10219       return NewAttr;
10220     }
10221   }
10222   return nullptr;
10223 }
10224 
10225 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10226 /// containing class. Otherwise it will return implicit SectionAttr if the
10227 /// function is a definition and there is an active value on CodeSegStack
10228 /// (from the current #pragma code-seg value).
10229 ///
10230 /// \param FD Function being declared.
10231 /// \param IsDefinition Whether it is a definition or just a declarartion.
10232 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10233 ///          nullptr if no attribute should be added.
10234 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10235                                                        bool IsDefinition) {
10236   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10237     return A;
10238   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10239       CodeSegStack.CurrentValue)
10240     return SectionAttr::CreateImplicit(
10241         getASTContext(), CodeSegStack.CurrentValue->getString(),
10242         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10243         SectionAttr::Declspec_allocate);
10244   return nullptr;
10245 }
10246 
10247 /// Determines if we can perform a correct type check for \p D as a
10248 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10249 /// best-effort check.
10250 ///
10251 /// \param NewD The new declaration.
10252 /// \param OldD The old declaration.
10253 /// \param NewT The portion of the type of the new declaration to check.
10254 /// \param OldT The portion of the type of the old declaration to check.
10255 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10256                                           QualType NewT, QualType OldT) {
10257   if (!NewD->getLexicalDeclContext()->isDependentContext())
10258     return true;
10259 
10260   // For dependently-typed local extern declarations and friends, we can't
10261   // perform a correct type check in general until instantiation:
10262   //
10263   //   int f();
10264   //   template<typename T> void g() { T f(); }
10265   //
10266   // (valid if g() is only instantiated with T = int).
10267   if (NewT->isDependentType() &&
10268       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10269     return false;
10270 
10271   // Similarly, if the previous declaration was a dependent local extern
10272   // declaration, we don't really know its type yet.
10273   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10274     return false;
10275 
10276   return true;
10277 }
10278 
10279 /// Checks if the new declaration declared in dependent context must be
10280 /// put in the same redeclaration chain as the specified declaration.
10281 ///
10282 /// \param D Declaration that is checked.
10283 /// \param PrevDecl Previous declaration found with proper lookup method for the
10284 ///                 same declaration name.
10285 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10286 ///          belongs to.
10287 ///
10288 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10289   if (!D->getLexicalDeclContext()->isDependentContext())
10290     return true;
10291 
10292   // Don't chain dependent friend function definitions until instantiation, to
10293   // permit cases like
10294   //
10295   //   void func();
10296   //   template<typename T> class C1 { friend void func() {} };
10297   //   template<typename T> class C2 { friend void func() {} };
10298   //
10299   // ... which is valid if only one of C1 and C2 is ever instantiated.
10300   //
10301   // FIXME: This need only apply to function definitions. For now, we proxy
10302   // this by checking for a file-scope function. We do not want this to apply
10303   // to friend declarations nominating member functions, because that gets in
10304   // the way of access checks.
10305   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10306     return false;
10307 
10308   auto *VD = dyn_cast<ValueDecl>(D);
10309   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10310   return !VD || !PrevVD ||
10311          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10312                                         PrevVD->getType());
10313 }
10314 
10315 /// Check the target attribute of the function for MultiVersion
10316 /// validity.
10317 ///
10318 /// Returns true if there was an error, false otherwise.
10319 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10320   const auto *TA = FD->getAttr<TargetAttr>();
10321   assert(TA && "MultiVersion Candidate requires a target attribute");
10322   ParsedTargetAttr ParseInfo = TA->parse();
10323   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10324   enum ErrType { Feature = 0, Architecture = 1 };
10325 
10326   if (!ParseInfo.Architecture.empty() &&
10327       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10328     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10329         << Architecture << ParseInfo.Architecture;
10330     return true;
10331   }
10332 
10333   for (const auto &Feat : ParseInfo.Features) {
10334     auto BareFeat = StringRef{Feat}.substr(1);
10335     if (Feat[0] == '-') {
10336       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10337           << Feature << ("no-" + BareFeat).str();
10338       return true;
10339     }
10340 
10341     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10342         !TargetInfo.isValidFeatureName(BareFeat)) {
10343       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10344           << Feature << BareFeat;
10345       return true;
10346     }
10347   }
10348   return false;
10349 }
10350 
10351 // Provide a white-list of attributes that are allowed to be combined with
10352 // multiversion functions.
10353 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10354                                            MultiVersionKind MVType) {
10355   // Note: this list/diagnosis must match the list in
10356   // checkMultiversionAttributesAllSame.
10357   switch (Kind) {
10358   default:
10359     return false;
10360   case attr::Used:
10361     return MVType == MultiVersionKind::Target;
10362   case attr::NonNull:
10363   case attr::NoThrow:
10364     return true;
10365   }
10366 }
10367 
10368 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10369                                                  const FunctionDecl *FD,
10370                                                  const FunctionDecl *CausedFD,
10371                                                  MultiVersionKind MVType) {
10372   const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) {
10373     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10374         << static_cast<unsigned>(MVType) << A;
10375     if (CausedFD)
10376       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10377     return true;
10378   };
10379 
10380   for (const Attr *A : FD->attrs()) {
10381     switch (A->getKind()) {
10382     case attr::CPUDispatch:
10383     case attr::CPUSpecific:
10384       if (MVType != MultiVersionKind::CPUDispatch &&
10385           MVType != MultiVersionKind::CPUSpecific)
10386         return Diagnose(S, A);
10387       break;
10388     case attr::Target:
10389       if (MVType != MultiVersionKind::Target)
10390         return Diagnose(S, A);
10391       break;
10392     case attr::TargetClones:
10393       if (MVType != MultiVersionKind::TargetClones)
10394         return Diagnose(S, A);
10395       break;
10396     default:
10397       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10398         return Diagnose(S, A);
10399       break;
10400     }
10401   }
10402   return false;
10403 }
10404 
10405 bool Sema::areMultiversionVariantFunctionsCompatible(
10406     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10407     const PartialDiagnostic &NoProtoDiagID,
10408     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10409     const PartialDiagnosticAt &NoSupportDiagIDAt,
10410     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10411     bool ConstexprSupported, bool CLinkageMayDiffer) {
10412   enum DoesntSupport {
10413     FuncTemplates = 0,
10414     VirtFuncs = 1,
10415     DeducedReturn = 2,
10416     Constructors = 3,
10417     Destructors = 4,
10418     DeletedFuncs = 5,
10419     DefaultedFuncs = 6,
10420     ConstexprFuncs = 7,
10421     ConstevalFuncs = 8,
10422     Lambda = 9,
10423   };
10424   enum Different {
10425     CallingConv = 0,
10426     ReturnType = 1,
10427     ConstexprSpec = 2,
10428     InlineSpec = 3,
10429     Linkage = 4,
10430     LanguageLinkage = 5,
10431   };
10432 
10433   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10434       !OldFD->getType()->getAs<FunctionProtoType>()) {
10435     Diag(OldFD->getLocation(), NoProtoDiagID);
10436     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10437     return true;
10438   }
10439 
10440   if (NoProtoDiagID.getDiagID() != 0 &&
10441       !NewFD->getType()->getAs<FunctionProtoType>())
10442     return Diag(NewFD->getLocation(), NoProtoDiagID);
10443 
10444   if (!TemplatesSupported &&
10445       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10446     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10447            << FuncTemplates;
10448 
10449   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10450     if (NewCXXFD->isVirtual())
10451       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10452              << VirtFuncs;
10453 
10454     if (isa<CXXConstructorDecl>(NewCXXFD))
10455       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10456              << Constructors;
10457 
10458     if (isa<CXXDestructorDecl>(NewCXXFD))
10459       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10460              << Destructors;
10461   }
10462 
10463   if (NewFD->isDeleted())
10464     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10465            << DeletedFuncs;
10466 
10467   if (NewFD->isDefaulted())
10468     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10469            << DefaultedFuncs;
10470 
10471   if (!ConstexprSupported && NewFD->isConstexpr())
10472     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10473            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10474 
10475   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10476   const auto *NewType = cast<FunctionType>(NewQType);
10477   QualType NewReturnType = NewType->getReturnType();
10478 
10479   if (NewReturnType->isUndeducedType())
10480     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10481            << DeducedReturn;
10482 
10483   // Ensure the return type is identical.
10484   if (OldFD) {
10485     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10486     const auto *OldType = cast<FunctionType>(OldQType);
10487     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10488     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10489 
10490     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10491       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10492 
10493     QualType OldReturnType = OldType->getReturnType();
10494 
10495     if (OldReturnType != NewReturnType)
10496       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10497 
10498     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10499       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10500 
10501     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10502       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10503 
10504     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10505       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10506 
10507     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10508       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10509 
10510     if (CheckEquivalentExceptionSpec(
10511             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10512             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10513       return true;
10514   }
10515   return false;
10516 }
10517 
10518 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10519                                              const FunctionDecl *NewFD,
10520                                              bool CausesMV,
10521                                              MultiVersionKind MVType) {
10522   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10523     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10524     if (OldFD)
10525       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10526     return true;
10527   }
10528 
10529   bool IsCPUSpecificCPUDispatchMVType =
10530       MVType == MultiVersionKind::CPUDispatch ||
10531       MVType == MultiVersionKind::CPUSpecific;
10532 
10533   if (CausesMV && OldFD &&
10534       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10535     return true;
10536 
10537   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10538     return true;
10539 
10540   // Only allow transition to MultiVersion if it hasn't been used.
10541   if (OldFD && CausesMV && OldFD->isUsed(false))
10542     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10543 
10544   return S.areMultiversionVariantFunctionsCompatible(
10545       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10546       PartialDiagnosticAt(NewFD->getLocation(),
10547                           S.PDiag(diag::note_multiversioning_caused_here)),
10548       PartialDiagnosticAt(NewFD->getLocation(),
10549                           S.PDiag(diag::err_multiversion_doesnt_support)
10550                               << static_cast<unsigned>(MVType)),
10551       PartialDiagnosticAt(NewFD->getLocation(),
10552                           S.PDiag(diag::err_multiversion_diff)),
10553       /*TemplatesSupported=*/false,
10554       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10555       /*CLinkageMayDiffer=*/false);
10556 }
10557 
10558 /// Check the validity of a multiversion function declaration that is the
10559 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10560 ///
10561 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10562 ///
10563 /// Returns true if there was an error, false otherwise.
10564 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10565                                            MultiVersionKind MVType,
10566                                            const TargetAttr *TA) {
10567   assert(MVType != MultiVersionKind::None &&
10568          "Function lacks multiversion attribute");
10569 
10570   // Target only causes MV if it is default, otherwise this is a normal
10571   // function.
10572   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10573     return false;
10574 
10575   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10576     FD->setInvalidDecl();
10577     return true;
10578   }
10579 
10580   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10581     FD->setInvalidDecl();
10582     return true;
10583   }
10584 
10585   FD->setIsMultiVersion();
10586   return false;
10587 }
10588 
10589 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10590   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10591     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10592       return true;
10593   }
10594 
10595   return false;
10596 }
10597 
10598 static bool CheckTargetCausesMultiVersioning(
10599     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10600     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10601     LookupResult &Previous) {
10602   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10603   ParsedTargetAttr NewParsed = NewTA->parse();
10604   // Sort order doesn't matter, it just needs to be consistent.
10605   llvm::sort(NewParsed.Features);
10606 
10607   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10608   // to change, this is a simple redeclaration.
10609   if (!NewTA->isDefaultVersion() &&
10610       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10611     return false;
10612 
10613   // Otherwise, this decl causes MultiVersioning.
10614   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10615     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10616     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10617     NewFD->setInvalidDecl();
10618     return true;
10619   }
10620 
10621   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10622                                        MultiVersionKind::Target)) {
10623     NewFD->setInvalidDecl();
10624     return true;
10625   }
10626 
10627   if (CheckMultiVersionValue(S, NewFD)) {
10628     NewFD->setInvalidDecl();
10629     return true;
10630   }
10631 
10632   // If this is 'default', permit the forward declaration.
10633   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10634     Redeclaration = true;
10635     OldDecl = OldFD;
10636     OldFD->setIsMultiVersion();
10637     NewFD->setIsMultiVersion();
10638     return false;
10639   }
10640 
10641   if (CheckMultiVersionValue(S, OldFD)) {
10642     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10643     NewFD->setInvalidDecl();
10644     return true;
10645   }
10646 
10647   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10648 
10649   if (OldParsed == NewParsed) {
10650     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10651     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10652     NewFD->setInvalidDecl();
10653     return true;
10654   }
10655 
10656   for (const auto *FD : OldFD->redecls()) {
10657     const auto *CurTA = FD->getAttr<TargetAttr>();
10658     // We allow forward declarations before ANY multiversioning attributes, but
10659     // nothing after the fact.
10660     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10661         (!CurTA || CurTA->isInherited())) {
10662       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10663           << 0;
10664       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10665       NewFD->setInvalidDecl();
10666       return true;
10667     }
10668   }
10669 
10670   OldFD->setIsMultiVersion();
10671   NewFD->setIsMultiVersion();
10672   Redeclaration = false;
10673   MergeTypeWithPrevious = false;
10674   OldDecl = nullptr;
10675   Previous.clear();
10676   return false;
10677 }
10678 
10679 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10680                                         MultiVersionKind New) {
10681   if (Old == New || Old == MultiVersionKind::None ||
10682       New == MultiVersionKind::None)
10683     return true;
10684 
10685   return (Old == MultiVersionKind::CPUDispatch &&
10686           New == MultiVersionKind::CPUSpecific) ||
10687          (Old == MultiVersionKind::CPUSpecific &&
10688           New == MultiVersionKind::CPUDispatch);
10689 }
10690 
10691 /// Check the validity of a new function declaration being added to an existing
10692 /// multiversioned declaration collection.
10693 static bool CheckMultiVersionAdditionalDecl(
10694     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10695     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10696     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10697     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10698     bool &MergeTypeWithPrevious, LookupResult &Previous) {
10699 
10700   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10701   // Disallow mixing of multiversioning types.
10702   if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) {
10703     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10704     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10705     NewFD->setInvalidDecl();
10706     return true;
10707   }
10708 
10709   ParsedTargetAttr NewParsed;
10710   if (NewTA) {
10711     NewParsed = NewTA->parse();
10712     llvm::sort(NewParsed.Features);
10713   }
10714 
10715   bool UseMemberUsingDeclRules =
10716       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10717 
10718   // Next, check ALL non-overloads to see if this is a redeclaration of a
10719   // previous member of the MultiVersion set.
10720   for (NamedDecl *ND : Previous) {
10721     FunctionDecl *CurFD = ND->getAsFunction();
10722     if (!CurFD)
10723       continue;
10724     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10725       continue;
10726 
10727     switch (NewMVType) {
10728     case MultiVersionKind::None:
10729       assert(OldMVType == MultiVersionKind::TargetClones &&
10730              "Only target_clones can be omitted in subsequent declarations");
10731       break;
10732     case MultiVersionKind::Target: {
10733       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10734       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10735         NewFD->setIsMultiVersion();
10736         Redeclaration = true;
10737         OldDecl = ND;
10738         return false;
10739       }
10740 
10741       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10742       if (CurParsed == NewParsed) {
10743         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10744         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10745         NewFD->setInvalidDecl();
10746         return true;
10747       }
10748       break;
10749     }
10750     case MultiVersionKind::TargetClones: {
10751       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10752       Redeclaration = true;
10753       OldDecl = CurFD;
10754       MergeTypeWithPrevious = true;
10755       NewFD->setIsMultiVersion();
10756 
10757       if (CurClones && NewClones &&
10758           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10759            !std::equal(CurClones->featuresStrs_begin(),
10760                        CurClones->featuresStrs_end(),
10761                        NewClones->featuresStrs_begin()))) {
10762         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10763         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10764         NewFD->setInvalidDecl();
10765         return true;
10766       }
10767 
10768       return false;
10769     }
10770     case MultiVersionKind::CPUSpecific:
10771     case MultiVersionKind::CPUDispatch: {
10772       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10773       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10774       // Handle CPUDispatch/CPUSpecific versions.
10775       // Only 1 CPUDispatch function is allowed, this will make it go through
10776       // the redeclaration errors.
10777       if (NewMVType == MultiVersionKind::CPUDispatch &&
10778           CurFD->hasAttr<CPUDispatchAttr>()) {
10779         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10780             std::equal(
10781                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10782                 NewCPUDisp->cpus_begin(),
10783                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10784                   return Cur->getName() == New->getName();
10785                 })) {
10786           NewFD->setIsMultiVersion();
10787           Redeclaration = true;
10788           OldDecl = ND;
10789           return false;
10790         }
10791 
10792         // If the declarations don't match, this is an error condition.
10793         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10794         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10795         NewFD->setInvalidDecl();
10796         return true;
10797       }
10798       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10799 
10800         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10801             std::equal(
10802                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10803                 NewCPUSpec->cpus_begin(),
10804                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10805                   return Cur->getName() == New->getName();
10806                 })) {
10807           NewFD->setIsMultiVersion();
10808           Redeclaration = true;
10809           OldDecl = ND;
10810           return false;
10811         }
10812 
10813         // Only 1 version of CPUSpecific is allowed for each CPU.
10814         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10815           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10816             if (CurII == NewII) {
10817               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10818                   << NewII;
10819               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10820               NewFD->setInvalidDecl();
10821               return true;
10822             }
10823           }
10824         }
10825       }
10826       break;
10827     }
10828     }
10829   }
10830 
10831   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10832   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10833   // handled in the attribute adding step.
10834   if (NewMVType == MultiVersionKind::Target &&
10835       CheckMultiVersionValue(S, NewFD)) {
10836     NewFD->setInvalidDecl();
10837     return true;
10838   }
10839 
10840   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10841                                        !OldFD->isMultiVersion(), NewMVType)) {
10842     NewFD->setInvalidDecl();
10843     return true;
10844   }
10845 
10846   // Permit forward declarations in the case where these two are compatible.
10847   if (!OldFD->isMultiVersion()) {
10848     OldFD->setIsMultiVersion();
10849     NewFD->setIsMultiVersion();
10850     Redeclaration = true;
10851     OldDecl = OldFD;
10852     return false;
10853   }
10854 
10855   NewFD->setIsMultiVersion();
10856   Redeclaration = false;
10857   MergeTypeWithPrevious = false;
10858   OldDecl = nullptr;
10859   Previous.clear();
10860   return false;
10861 }
10862 
10863 /// Check the validity of a mulitversion function declaration.
10864 /// Also sets the multiversion'ness' of the function itself.
10865 ///
10866 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10867 ///
10868 /// Returns true if there was an error, false otherwise.
10869 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10870                                       bool &Redeclaration, NamedDecl *&OldDecl,
10871                                       bool &MergeTypeWithPrevious,
10872                                       LookupResult &Previous) {
10873   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10874   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10875   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10876   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10877   MultiVersionKind MVType = NewFD->getMultiVersionKind();
10878 
10879   // Main isn't allowed to become a multiversion function, however it IS
10880   // permitted to have 'main' be marked with the 'target' optimization hint.
10881   if (NewFD->isMain()) {
10882     if (MVType != MultiVersionKind::None &&
10883         !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10884       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10885       NewFD->setInvalidDecl();
10886       return true;
10887     }
10888     return false;
10889   }
10890 
10891   if (!OldDecl || !OldDecl->getAsFunction() ||
10892       OldDecl->getDeclContext()->getRedeclContext() !=
10893           NewFD->getDeclContext()->getRedeclContext()) {
10894     // If there's no previous declaration, AND this isn't attempting to cause
10895     // multiversioning, this isn't an error condition.
10896     if (MVType == MultiVersionKind::None)
10897       return false;
10898     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10899   }
10900 
10901   FunctionDecl *OldFD = OldDecl->getAsFunction();
10902 
10903   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10904     return false;
10905 
10906   // Multiversioned redeclarations aren't allowed to omit the attribute, except
10907   // for target_clones.
10908   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None &&
10909       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
10910     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10911         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10912     NewFD->setInvalidDecl();
10913     return true;
10914   }
10915 
10916   if (!OldFD->isMultiVersion()) {
10917     switch (MVType) {
10918     case MultiVersionKind::Target:
10919       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10920                                               Redeclaration, OldDecl,
10921                                               MergeTypeWithPrevious, Previous);
10922     case MultiVersionKind::TargetClones:
10923       if (OldFD->isUsed(false)) {
10924         NewFD->setInvalidDecl();
10925         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10926       }
10927       OldFD->setIsMultiVersion();
10928       break;
10929     case MultiVersionKind::CPUDispatch:
10930     case MultiVersionKind::CPUSpecific:
10931     case MultiVersionKind::None:
10932       break;
10933     }
10934   }
10935   // Handle the target potentially causes multiversioning case.
10936   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10937     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10938                                             Redeclaration, OldDecl,
10939                                             MergeTypeWithPrevious, Previous);
10940 
10941   // At this point, we have a multiversion function decl (in OldFD) AND an
10942   // appropriate attribute in the current function decl.  Resolve that these are
10943   // still compatible with previous declarations.
10944   return CheckMultiVersionAdditionalDecl(
10945       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones,
10946       Redeclaration, OldDecl, MergeTypeWithPrevious, Previous);
10947 }
10948 
10949 /// Perform semantic checking of a new function declaration.
10950 ///
10951 /// Performs semantic analysis of the new function declaration
10952 /// NewFD. This routine performs all semantic checking that does not
10953 /// require the actual declarator involved in the declaration, and is
10954 /// used both for the declaration of functions as they are parsed
10955 /// (called via ActOnDeclarator) and for the declaration of functions
10956 /// that have been instantiated via C++ template instantiation (called
10957 /// via InstantiateDecl).
10958 ///
10959 /// \param IsMemberSpecialization whether this new function declaration is
10960 /// a member specialization (that replaces any definition provided by the
10961 /// previous declaration).
10962 ///
10963 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10964 ///
10965 /// \returns true if the function declaration is a redeclaration.
10966 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10967                                     LookupResult &Previous,
10968                                     bool IsMemberSpecialization) {
10969   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10970          "Variably modified return types are not handled here");
10971 
10972   // Determine whether the type of this function should be merged with
10973   // a previous visible declaration. This never happens for functions in C++,
10974   // and always happens in C if the previous declaration was visible.
10975   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10976                                !Previous.isShadowed();
10977 
10978   bool Redeclaration = false;
10979   NamedDecl *OldDecl = nullptr;
10980   bool MayNeedOverloadableChecks = false;
10981 
10982   // Merge or overload the declaration with an existing declaration of
10983   // the same name, if appropriate.
10984   if (!Previous.empty()) {
10985     // Determine whether NewFD is an overload of PrevDecl or
10986     // a declaration that requires merging. If it's an overload,
10987     // there's no more work to do here; we'll just add the new
10988     // function to the scope.
10989     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10990       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10991       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10992         Redeclaration = true;
10993         OldDecl = Candidate;
10994       }
10995     } else {
10996       MayNeedOverloadableChecks = true;
10997       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10998                             /*NewIsUsingDecl*/ false)) {
10999       case Ovl_Match:
11000         Redeclaration = true;
11001         break;
11002 
11003       case Ovl_NonFunction:
11004         Redeclaration = true;
11005         break;
11006 
11007       case Ovl_Overload:
11008         Redeclaration = false;
11009         break;
11010       }
11011     }
11012   }
11013 
11014   // Check for a previous extern "C" declaration with this name.
11015   if (!Redeclaration &&
11016       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11017     if (!Previous.empty()) {
11018       // This is an extern "C" declaration with the same name as a previous
11019       // declaration, and thus redeclares that entity...
11020       Redeclaration = true;
11021       OldDecl = Previous.getFoundDecl();
11022       MergeTypeWithPrevious = false;
11023 
11024       // ... except in the presence of __attribute__((overloadable)).
11025       if (OldDecl->hasAttr<OverloadableAttr>() ||
11026           NewFD->hasAttr<OverloadableAttr>()) {
11027         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11028           MayNeedOverloadableChecks = true;
11029           Redeclaration = false;
11030           OldDecl = nullptr;
11031         }
11032       }
11033     }
11034   }
11035 
11036   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
11037                                 MergeTypeWithPrevious, Previous))
11038     return Redeclaration;
11039 
11040   // PPC MMA non-pointer types are not allowed as function return types.
11041   if (Context.getTargetInfo().getTriple().isPPC64() &&
11042       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11043     NewFD->setInvalidDecl();
11044   }
11045 
11046   // C++11 [dcl.constexpr]p8:
11047   //   A constexpr specifier for a non-static member function that is not
11048   //   a constructor declares that member function to be const.
11049   //
11050   // This needs to be delayed until we know whether this is an out-of-line
11051   // definition of a static member function.
11052   //
11053   // This rule is not present in C++1y, so we produce a backwards
11054   // compatibility warning whenever it happens in C++11.
11055   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11056   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11057       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11058       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11059     CXXMethodDecl *OldMD = nullptr;
11060     if (OldDecl)
11061       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11062     if (!OldMD || !OldMD->isStatic()) {
11063       const FunctionProtoType *FPT =
11064         MD->getType()->castAs<FunctionProtoType>();
11065       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11066       EPI.TypeQuals.addConst();
11067       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11068                                           FPT->getParamTypes(), EPI));
11069 
11070       // Warn that we did this, if we're not performing template instantiation.
11071       // In that case, we'll have warned already when the template was defined.
11072       if (!inTemplateInstantiation()) {
11073         SourceLocation AddConstLoc;
11074         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11075                 .IgnoreParens().getAs<FunctionTypeLoc>())
11076           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11077 
11078         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11079           << FixItHint::CreateInsertion(AddConstLoc, " const");
11080       }
11081     }
11082   }
11083 
11084   if (Redeclaration) {
11085     // NewFD and OldDecl represent declarations that need to be
11086     // merged.
11087     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11088       NewFD->setInvalidDecl();
11089       return Redeclaration;
11090     }
11091 
11092     Previous.clear();
11093     Previous.addDecl(OldDecl);
11094 
11095     if (FunctionTemplateDecl *OldTemplateDecl =
11096             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11097       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11098       FunctionTemplateDecl *NewTemplateDecl
11099         = NewFD->getDescribedFunctionTemplate();
11100       assert(NewTemplateDecl && "Template/non-template mismatch");
11101 
11102       // The call to MergeFunctionDecl above may have created some state in
11103       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11104       // can add it as a redeclaration.
11105       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11106 
11107       NewFD->setPreviousDeclaration(OldFD);
11108       if (NewFD->isCXXClassMember()) {
11109         NewFD->setAccess(OldTemplateDecl->getAccess());
11110         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11111       }
11112 
11113       // If this is an explicit specialization of a member that is a function
11114       // template, mark it as a member specialization.
11115       if (IsMemberSpecialization &&
11116           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11117         NewTemplateDecl->setMemberSpecialization();
11118         assert(OldTemplateDecl->isMemberSpecialization());
11119         // Explicit specializations of a member template do not inherit deleted
11120         // status from the parent member template that they are specializing.
11121         if (OldFD->isDeleted()) {
11122           // FIXME: This assert will not hold in the presence of modules.
11123           assert(OldFD->getCanonicalDecl() == OldFD);
11124           // FIXME: We need an update record for this AST mutation.
11125           OldFD->setDeletedAsWritten(false);
11126         }
11127       }
11128 
11129     } else {
11130       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11131         auto *OldFD = cast<FunctionDecl>(OldDecl);
11132         // This needs to happen first so that 'inline' propagates.
11133         NewFD->setPreviousDeclaration(OldFD);
11134         if (NewFD->isCXXClassMember())
11135           NewFD->setAccess(OldFD->getAccess());
11136       }
11137     }
11138   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11139              !NewFD->getAttr<OverloadableAttr>()) {
11140     assert((Previous.empty() ||
11141             llvm::any_of(Previous,
11142                          [](const NamedDecl *ND) {
11143                            return ND->hasAttr<OverloadableAttr>();
11144                          })) &&
11145            "Non-redecls shouldn't happen without overloadable present");
11146 
11147     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11148       const auto *FD = dyn_cast<FunctionDecl>(ND);
11149       return FD && !FD->hasAttr<OverloadableAttr>();
11150     });
11151 
11152     if (OtherUnmarkedIter != Previous.end()) {
11153       Diag(NewFD->getLocation(),
11154            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11155       Diag((*OtherUnmarkedIter)->getLocation(),
11156            diag::note_attribute_overloadable_prev_overload)
11157           << false;
11158 
11159       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11160     }
11161   }
11162 
11163   if (LangOpts.OpenMP)
11164     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11165 
11166   // Semantic checking for this function declaration (in isolation).
11167 
11168   if (getLangOpts().CPlusPlus) {
11169     // C++-specific checks.
11170     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11171       CheckConstructor(Constructor);
11172     } else if (CXXDestructorDecl *Destructor =
11173                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11174       CXXRecordDecl *Record = Destructor->getParent();
11175       QualType ClassType = Context.getTypeDeclType(Record);
11176 
11177       // FIXME: Shouldn't we be able to perform this check even when the class
11178       // type is dependent? Both gcc and edg can handle that.
11179       if (!ClassType->isDependentType()) {
11180         DeclarationName Name
11181           = Context.DeclarationNames.getCXXDestructorName(
11182                                         Context.getCanonicalType(ClassType));
11183         if (NewFD->getDeclName() != Name) {
11184           Diag(NewFD->getLocation(), diag::err_destructor_name);
11185           NewFD->setInvalidDecl();
11186           return Redeclaration;
11187         }
11188       }
11189     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11190       if (auto *TD = Guide->getDescribedFunctionTemplate())
11191         CheckDeductionGuideTemplate(TD);
11192 
11193       // A deduction guide is not on the list of entities that can be
11194       // explicitly specialized.
11195       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11196         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11197             << /*explicit specialization*/ 1;
11198     }
11199 
11200     // Find any virtual functions that this function overrides.
11201     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11202       if (!Method->isFunctionTemplateSpecialization() &&
11203           !Method->getDescribedFunctionTemplate() &&
11204           Method->isCanonicalDecl()) {
11205         AddOverriddenMethods(Method->getParent(), Method);
11206       }
11207       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11208         // C++2a [class.virtual]p6
11209         // A virtual method shall not have a requires-clause.
11210         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11211              diag::err_constrained_virtual_method);
11212 
11213       if (Method->isStatic())
11214         checkThisInStaticMemberFunctionType(Method);
11215     }
11216 
11217     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11218       ActOnConversionDeclarator(Conversion);
11219 
11220     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11221     if (NewFD->isOverloadedOperator() &&
11222         CheckOverloadedOperatorDeclaration(NewFD)) {
11223       NewFD->setInvalidDecl();
11224       return Redeclaration;
11225     }
11226 
11227     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11228     if (NewFD->getLiteralIdentifier() &&
11229         CheckLiteralOperatorDeclaration(NewFD)) {
11230       NewFD->setInvalidDecl();
11231       return Redeclaration;
11232     }
11233 
11234     // In C++, check default arguments now that we have merged decls. Unless
11235     // the lexical context is the class, because in this case this is done
11236     // during delayed parsing anyway.
11237     if (!CurContext->isRecord())
11238       CheckCXXDefaultArguments(NewFD);
11239 
11240     // If this function is declared as being extern "C", then check to see if
11241     // the function returns a UDT (class, struct, or union type) that is not C
11242     // compatible, and if it does, warn the user.
11243     // But, issue any diagnostic on the first declaration only.
11244     if (Previous.empty() && NewFD->isExternC()) {
11245       QualType R = NewFD->getReturnType();
11246       if (R->isIncompleteType() && !R->isVoidType())
11247         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11248             << NewFD << R;
11249       else if (!R.isPODType(Context) && !R->isVoidType() &&
11250                !R->isObjCObjectPointerType())
11251         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11252     }
11253 
11254     // C++1z [dcl.fct]p6:
11255     //   [...] whether the function has a non-throwing exception-specification
11256     //   [is] part of the function type
11257     //
11258     // This results in an ABI break between C++14 and C++17 for functions whose
11259     // declared type includes an exception-specification in a parameter or
11260     // return type. (Exception specifications on the function itself are OK in
11261     // most cases, and exception specifications are not permitted in most other
11262     // contexts where they could make it into a mangling.)
11263     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11264       auto HasNoexcept = [&](QualType T) -> bool {
11265         // Strip off declarator chunks that could be between us and a function
11266         // type. We don't need to look far, exception specifications are very
11267         // restricted prior to C++17.
11268         if (auto *RT = T->getAs<ReferenceType>())
11269           T = RT->getPointeeType();
11270         else if (T->isAnyPointerType())
11271           T = T->getPointeeType();
11272         else if (auto *MPT = T->getAs<MemberPointerType>())
11273           T = MPT->getPointeeType();
11274         if (auto *FPT = T->getAs<FunctionProtoType>())
11275           if (FPT->isNothrow())
11276             return true;
11277         return false;
11278       };
11279 
11280       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11281       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11282       for (QualType T : FPT->param_types())
11283         AnyNoexcept |= HasNoexcept(T);
11284       if (AnyNoexcept)
11285         Diag(NewFD->getLocation(),
11286              diag::warn_cxx17_compat_exception_spec_in_signature)
11287             << NewFD;
11288     }
11289 
11290     if (!Redeclaration && LangOpts.CUDA)
11291       checkCUDATargetOverload(NewFD, Previous);
11292   }
11293   return Redeclaration;
11294 }
11295 
11296 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11297   // C++11 [basic.start.main]p3:
11298   //   A program that [...] declares main to be inline, static or
11299   //   constexpr is ill-formed.
11300   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11301   //   appear in a declaration of main.
11302   // static main is not an error under C99, but we should warn about it.
11303   // We accept _Noreturn main as an extension.
11304   if (FD->getStorageClass() == SC_Static)
11305     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11306          ? diag::err_static_main : diag::warn_static_main)
11307       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11308   if (FD->isInlineSpecified())
11309     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11310       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11311   if (DS.isNoreturnSpecified()) {
11312     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11313     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11314     Diag(NoreturnLoc, diag::ext_noreturn_main);
11315     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11316       << FixItHint::CreateRemoval(NoreturnRange);
11317   }
11318   if (FD->isConstexpr()) {
11319     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11320         << FD->isConsteval()
11321         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11322     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11323   }
11324 
11325   if (getLangOpts().OpenCL) {
11326     Diag(FD->getLocation(), diag::err_opencl_no_main)
11327         << FD->hasAttr<OpenCLKernelAttr>();
11328     FD->setInvalidDecl();
11329     return;
11330   }
11331 
11332   QualType T = FD->getType();
11333   assert(T->isFunctionType() && "function decl is not of function type");
11334   const FunctionType* FT = T->castAs<FunctionType>();
11335 
11336   // Set default calling convention for main()
11337   if (FT->getCallConv() != CC_C) {
11338     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11339     FD->setType(QualType(FT, 0));
11340     T = Context.getCanonicalType(FD->getType());
11341   }
11342 
11343   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11344     // In C with GNU extensions we allow main() to have non-integer return
11345     // type, but we should warn about the extension, and we disable the
11346     // implicit-return-zero rule.
11347 
11348     // GCC in C mode accepts qualified 'int'.
11349     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11350       FD->setHasImplicitReturnZero(true);
11351     else {
11352       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11353       SourceRange RTRange = FD->getReturnTypeSourceRange();
11354       if (RTRange.isValid())
11355         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11356             << FixItHint::CreateReplacement(RTRange, "int");
11357     }
11358   } else {
11359     // In C and C++, main magically returns 0 if you fall off the end;
11360     // set the flag which tells us that.
11361     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11362 
11363     // All the standards say that main() should return 'int'.
11364     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11365       FD->setHasImplicitReturnZero(true);
11366     else {
11367       // Otherwise, this is just a flat-out error.
11368       SourceRange RTRange = FD->getReturnTypeSourceRange();
11369       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11370           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11371                                 : FixItHint());
11372       FD->setInvalidDecl(true);
11373     }
11374   }
11375 
11376   // Treat protoless main() as nullary.
11377   if (isa<FunctionNoProtoType>(FT)) return;
11378 
11379   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11380   unsigned nparams = FTP->getNumParams();
11381   assert(FD->getNumParams() == nparams);
11382 
11383   bool HasExtraParameters = (nparams > 3);
11384 
11385   if (FTP->isVariadic()) {
11386     Diag(FD->getLocation(), diag::ext_variadic_main);
11387     // FIXME: if we had information about the location of the ellipsis, we
11388     // could add a FixIt hint to remove it as a parameter.
11389   }
11390 
11391   // Darwin passes an undocumented fourth argument of type char**.  If
11392   // other platforms start sprouting these, the logic below will start
11393   // getting shifty.
11394   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11395     HasExtraParameters = false;
11396 
11397   if (HasExtraParameters) {
11398     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11399     FD->setInvalidDecl(true);
11400     nparams = 3;
11401   }
11402 
11403   // FIXME: a lot of the following diagnostics would be improved
11404   // if we had some location information about types.
11405 
11406   QualType CharPP =
11407     Context.getPointerType(Context.getPointerType(Context.CharTy));
11408   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11409 
11410   for (unsigned i = 0; i < nparams; ++i) {
11411     QualType AT = FTP->getParamType(i);
11412 
11413     bool mismatch = true;
11414 
11415     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11416       mismatch = false;
11417     else if (Expected[i] == CharPP) {
11418       // As an extension, the following forms are okay:
11419       //   char const **
11420       //   char const * const *
11421       //   char * const *
11422 
11423       QualifierCollector qs;
11424       const PointerType* PT;
11425       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11426           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11427           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11428                               Context.CharTy)) {
11429         qs.removeConst();
11430         mismatch = !qs.empty();
11431       }
11432     }
11433 
11434     if (mismatch) {
11435       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11436       // TODO: suggest replacing given type with expected type
11437       FD->setInvalidDecl(true);
11438     }
11439   }
11440 
11441   if (nparams == 1 && !FD->isInvalidDecl()) {
11442     Diag(FD->getLocation(), diag::warn_main_one_arg);
11443   }
11444 
11445   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11446     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11447     FD->setInvalidDecl();
11448   }
11449 }
11450 
11451 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11452 
11453   // Default calling convention for main and wmain is __cdecl
11454   if (FD->getName() == "main" || FD->getName() == "wmain")
11455     return false;
11456 
11457   // Default calling convention for MinGW is __cdecl
11458   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11459   if (T.isWindowsGNUEnvironment())
11460     return false;
11461 
11462   // Default calling convention for WinMain, wWinMain and DllMain
11463   // is __stdcall on 32 bit Windows
11464   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11465     return true;
11466 
11467   return false;
11468 }
11469 
11470 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11471   QualType T = FD->getType();
11472   assert(T->isFunctionType() && "function decl is not of function type");
11473   const FunctionType *FT = T->castAs<FunctionType>();
11474 
11475   // Set an implicit return of 'zero' if the function can return some integral,
11476   // enumeration, pointer or nullptr type.
11477   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11478       FT->getReturnType()->isAnyPointerType() ||
11479       FT->getReturnType()->isNullPtrType())
11480     // DllMain is exempt because a return value of zero means it failed.
11481     if (FD->getName() != "DllMain")
11482       FD->setHasImplicitReturnZero(true);
11483 
11484   // Explicity specified calling conventions are applied to MSVC entry points
11485   if (!hasExplicitCallingConv(T)) {
11486     if (isDefaultStdCall(FD, *this)) {
11487       if (FT->getCallConv() != CC_X86StdCall) {
11488         FT = Context.adjustFunctionType(
11489             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11490         FD->setType(QualType(FT, 0));
11491       }
11492     } else if (FT->getCallConv() != CC_C) {
11493       FT = Context.adjustFunctionType(FT,
11494                                       FT->getExtInfo().withCallingConv(CC_C));
11495       FD->setType(QualType(FT, 0));
11496     }
11497   }
11498 
11499   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11500     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11501     FD->setInvalidDecl();
11502   }
11503 }
11504 
11505 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11506   // FIXME: Need strict checking.  In C89, we need to check for
11507   // any assignment, increment, decrement, function-calls, or
11508   // commas outside of a sizeof.  In C99, it's the same list,
11509   // except that the aforementioned are allowed in unevaluated
11510   // expressions.  Everything else falls under the
11511   // "may accept other forms of constant expressions" exception.
11512   //
11513   // Regular C++ code will not end up here (exceptions: language extensions,
11514   // OpenCL C++ etc), so the constant expression rules there don't matter.
11515   if (Init->isValueDependent()) {
11516     assert(Init->containsErrors() &&
11517            "Dependent code should only occur in error-recovery path.");
11518     return true;
11519   }
11520   const Expr *Culprit;
11521   if (Init->isConstantInitializer(Context, false, &Culprit))
11522     return false;
11523   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11524     << Culprit->getSourceRange();
11525   return true;
11526 }
11527 
11528 namespace {
11529   // Visits an initialization expression to see if OrigDecl is evaluated in
11530   // its own initialization and throws a warning if it does.
11531   class SelfReferenceChecker
11532       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11533     Sema &S;
11534     Decl *OrigDecl;
11535     bool isRecordType;
11536     bool isPODType;
11537     bool isReferenceType;
11538 
11539     bool isInitList;
11540     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11541 
11542   public:
11543     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11544 
11545     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11546                                                     S(S), OrigDecl(OrigDecl) {
11547       isPODType = false;
11548       isRecordType = false;
11549       isReferenceType = false;
11550       isInitList = false;
11551       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11552         isPODType = VD->getType().isPODType(S.Context);
11553         isRecordType = VD->getType()->isRecordType();
11554         isReferenceType = VD->getType()->isReferenceType();
11555       }
11556     }
11557 
11558     // For most expressions, just call the visitor.  For initializer lists,
11559     // track the index of the field being initialized since fields are
11560     // initialized in order allowing use of previously initialized fields.
11561     void CheckExpr(Expr *E) {
11562       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11563       if (!InitList) {
11564         Visit(E);
11565         return;
11566       }
11567 
11568       // Track and increment the index here.
11569       isInitList = true;
11570       InitFieldIndex.push_back(0);
11571       for (auto Child : InitList->children()) {
11572         CheckExpr(cast<Expr>(Child));
11573         ++InitFieldIndex.back();
11574       }
11575       InitFieldIndex.pop_back();
11576     }
11577 
11578     // Returns true if MemberExpr is checked and no further checking is needed.
11579     // Returns false if additional checking is required.
11580     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11581       llvm::SmallVector<FieldDecl*, 4> Fields;
11582       Expr *Base = E;
11583       bool ReferenceField = false;
11584 
11585       // Get the field members used.
11586       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11587         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11588         if (!FD)
11589           return false;
11590         Fields.push_back(FD);
11591         if (FD->getType()->isReferenceType())
11592           ReferenceField = true;
11593         Base = ME->getBase()->IgnoreParenImpCasts();
11594       }
11595 
11596       // Keep checking only if the base Decl is the same.
11597       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11598       if (!DRE || DRE->getDecl() != OrigDecl)
11599         return false;
11600 
11601       // A reference field can be bound to an unininitialized field.
11602       if (CheckReference && !ReferenceField)
11603         return true;
11604 
11605       // Convert FieldDecls to their index number.
11606       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11607       for (const FieldDecl *I : llvm::reverse(Fields))
11608         UsedFieldIndex.push_back(I->getFieldIndex());
11609 
11610       // See if a warning is needed by checking the first difference in index
11611       // numbers.  If field being used has index less than the field being
11612       // initialized, then the use is safe.
11613       for (auto UsedIter = UsedFieldIndex.begin(),
11614                 UsedEnd = UsedFieldIndex.end(),
11615                 OrigIter = InitFieldIndex.begin(),
11616                 OrigEnd = InitFieldIndex.end();
11617            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11618         if (*UsedIter < *OrigIter)
11619           return true;
11620         if (*UsedIter > *OrigIter)
11621           break;
11622       }
11623 
11624       // TODO: Add a different warning which will print the field names.
11625       HandleDeclRefExpr(DRE);
11626       return true;
11627     }
11628 
11629     // For most expressions, the cast is directly above the DeclRefExpr.
11630     // For conditional operators, the cast can be outside the conditional
11631     // operator if both expressions are DeclRefExpr's.
11632     void HandleValue(Expr *E) {
11633       E = E->IgnoreParens();
11634       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11635         HandleDeclRefExpr(DRE);
11636         return;
11637       }
11638 
11639       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11640         Visit(CO->getCond());
11641         HandleValue(CO->getTrueExpr());
11642         HandleValue(CO->getFalseExpr());
11643         return;
11644       }
11645 
11646       if (BinaryConditionalOperator *BCO =
11647               dyn_cast<BinaryConditionalOperator>(E)) {
11648         Visit(BCO->getCond());
11649         HandleValue(BCO->getFalseExpr());
11650         return;
11651       }
11652 
11653       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11654         HandleValue(OVE->getSourceExpr());
11655         return;
11656       }
11657 
11658       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11659         if (BO->getOpcode() == BO_Comma) {
11660           Visit(BO->getLHS());
11661           HandleValue(BO->getRHS());
11662           return;
11663         }
11664       }
11665 
11666       if (isa<MemberExpr>(E)) {
11667         if (isInitList) {
11668           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11669                                       false /*CheckReference*/))
11670             return;
11671         }
11672 
11673         Expr *Base = E->IgnoreParenImpCasts();
11674         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11675           // Check for static member variables and don't warn on them.
11676           if (!isa<FieldDecl>(ME->getMemberDecl()))
11677             return;
11678           Base = ME->getBase()->IgnoreParenImpCasts();
11679         }
11680         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11681           HandleDeclRefExpr(DRE);
11682         return;
11683       }
11684 
11685       Visit(E);
11686     }
11687 
11688     // Reference types not handled in HandleValue are handled here since all
11689     // uses of references are bad, not just r-value uses.
11690     void VisitDeclRefExpr(DeclRefExpr *E) {
11691       if (isReferenceType)
11692         HandleDeclRefExpr(E);
11693     }
11694 
11695     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11696       if (E->getCastKind() == CK_LValueToRValue) {
11697         HandleValue(E->getSubExpr());
11698         return;
11699       }
11700 
11701       Inherited::VisitImplicitCastExpr(E);
11702     }
11703 
11704     void VisitMemberExpr(MemberExpr *E) {
11705       if (isInitList) {
11706         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11707           return;
11708       }
11709 
11710       // Don't warn on arrays since they can be treated as pointers.
11711       if (E->getType()->canDecayToPointerType()) return;
11712 
11713       // Warn when a non-static method call is followed by non-static member
11714       // field accesses, which is followed by a DeclRefExpr.
11715       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11716       bool Warn = (MD && !MD->isStatic());
11717       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11718       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11719         if (!isa<FieldDecl>(ME->getMemberDecl()))
11720           Warn = false;
11721         Base = ME->getBase()->IgnoreParenImpCasts();
11722       }
11723 
11724       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11725         if (Warn)
11726           HandleDeclRefExpr(DRE);
11727         return;
11728       }
11729 
11730       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11731       // Visit that expression.
11732       Visit(Base);
11733     }
11734 
11735     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11736       Expr *Callee = E->getCallee();
11737 
11738       if (isa<UnresolvedLookupExpr>(Callee))
11739         return Inherited::VisitCXXOperatorCallExpr(E);
11740 
11741       Visit(Callee);
11742       for (auto Arg: E->arguments())
11743         HandleValue(Arg->IgnoreParenImpCasts());
11744     }
11745 
11746     void VisitUnaryOperator(UnaryOperator *E) {
11747       // For POD record types, addresses of its own members are well-defined.
11748       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11749           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11750         if (!isPODType)
11751           HandleValue(E->getSubExpr());
11752         return;
11753       }
11754 
11755       if (E->isIncrementDecrementOp()) {
11756         HandleValue(E->getSubExpr());
11757         return;
11758       }
11759 
11760       Inherited::VisitUnaryOperator(E);
11761     }
11762 
11763     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11764 
11765     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11766       if (E->getConstructor()->isCopyConstructor()) {
11767         Expr *ArgExpr = E->getArg(0);
11768         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11769           if (ILE->getNumInits() == 1)
11770             ArgExpr = ILE->getInit(0);
11771         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11772           if (ICE->getCastKind() == CK_NoOp)
11773             ArgExpr = ICE->getSubExpr();
11774         HandleValue(ArgExpr);
11775         return;
11776       }
11777       Inherited::VisitCXXConstructExpr(E);
11778     }
11779 
11780     void VisitCallExpr(CallExpr *E) {
11781       // Treat std::move as a use.
11782       if (E->isCallToStdMove()) {
11783         HandleValue(E->getArg(0));
11784         return;
11785       }
11786 
11787       Inherited::VisitCallExpr(E);
11788     }
11789 
11790     void VisitBinaryOperator(BinaryOperator *E) {
11791       if (E->isCompoundAssignmentOp()) {
11792         HandleValue(E->getLHS());
11793         Visit(E->getRHS());
11794         return;
11795       }
11796 
11797       Inherited::VisitBinaryOperator(E);
11798     }
11799 
11800     // A custom visitor for BinaryConditionalOperator is needed because the
11801     // regular visitor would check the condition and true expression separately
11802     // but both point to the same place giving duplicate diagnostics.
11803     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11804       Visit(E->getCond());
11805       Visit(E->getFalseExpr());
11806     }
11807 
11808     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11809       Decl* ReferenceDecl = DRE->getDecl();
11810       if (OrigDecl != ReferenceDecl) return;
11811       unsigned diag;
11812       if (isReferenceType) {
11813         diag = diag::warn_uninit_self_reference_in_reference_init;
11814       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11815         diag = diag::warn_static_self_reference_in_init;
11816       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11817                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11818                  DRE->getDecl()->getType()->isRecordType()) {
11819         diag = diag::warn_uninit_self_reference_in_init;
11820       } else {
11821         // Local variables will be handled by the CFG analysis.
11822         return;
11823       }
11824 
11825       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11826                             S.PDiag(diag)
11827                                 << DRE->getDecl() << OrigDecl->getLocation()
11828                                 << DRE->getSourceRange());
11829     }
11830   };
11831 
11832   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11833   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11834                                  bool DirectInit) {
11835     // Parameters arguments are occassionially constructed with itself,
11836     // for instance, in recursive functions.  Skip them.
11837     if (isa<ParmVarDecl>(OrigDecl))
11838       return;
11839 
11840     E = E->IgnoreParens();
11841 
11842     // Skip checking T a = a where T is not a record or reference type.
11843     // Doing so is a way to silence uninitialized warnings.
11844     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11845       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11846         if (ICE->getCastKind() == CK_LValueToRValue)
11847           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11848             if (DRE->getDecl() == OrigDecl)
11849               return;
11850 
11851     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11852   }
11853 } // end anonymous namespace
11854 
11855 namespace {
11856   // Simple wrapper to add the name of a variable or (if no variable is
11857   // available) a DeclarationName into a diagnostic.
11858   struct VarDeclOrName {
11859     VarDecl *VDecl;
11860     DeclarationName Name;
11861 
11862     friend const Sema::SemaDiagnosticBuilder &
11863     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11864       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11865     }
11866   };
11867 } // end anonymous namespace
11868 
11869 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11870                                             DeclarationName Name, QualType Type,
11871                                             TypeSourceInfo *TSI,
11872                                             SourceRange Range, bool DirectInit,
11873                                             Expr *Init) {
11874   bool IsInitCapture = !VDecl;
11875   assert((!VDecl || !VDecl->isInitCapture()) &&
11876          "init captures are expected to be deduced prior to initialization");
11877 
11878   VarDeclOrName VN{VDecl, Name};
11879 
11880   DeducedType *Deduced = Type->getContainedDeducedType();
11881   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11882 
11883   // C++11 [dcl.spec.auto]p3
11884   if (!Init) {
11885     assert(VDecl && "no init for init capture deduction?");
11886 
11887     // Except for class argument deduction, and then for an initializing
11888     // declaration only, i.e. no static at class scope or extern.
11889     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11890         VDecl->hasExternalStorage() ||
11891         VDecl->isStaticDataMember()) {
11892       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11893         << VDecl->getDeclName() << Type;
11894       return QualType();
11895     }
11896   }
11897 
11898   ArrayRef<Expr*> DeduceInits;
11899   if (Init)
11900     DeduceInits = Init;
11901 
11902   if (DirectInit) {
11903     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11904       DeduceInits = PL->exprs();
11905   }
11906 
11907   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11908     assert(VDecl && "non-auto type for init capture deduction?");
11909     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11910     InitializationKind Kind = InitializationKind::CreateForInit(
11911         VDecl->getLocation(), DirectInit, Init);
11912     // FIXME: Initialization should not be taking a mutable list of inits.
11913     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11914     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11915                                                        InitsCopy);
11916   }
11917 
11918   if (DirectInit) {
11919     if (auto *IL = dyn_cast<InitListExpr>(Init))
11920       DeduceInits = IL->inits();
11921   }
11922 
11923   // Deduction only works if we have exactly one source expression.
11924   if (DeduceInits.empty()) {
11925     // It isn't possible to write this directly, but it is possible to
11926     // end up in this situation with "auto x(some_pack...);"
11927     Diag(Init->getBeginLoc(), IsInitCapture
11928                                   ? diag::err_init_capture_no_expression
11929                                   : diag::err_auto_var_init_no_expression)
11930         << VN << Type << Range;
11931     return QualType();
11932   }
11933 
11934   if (DeduceInits.size() > 1) {
11935     Diag(DeduceInits[1]->getBeginLoc(),
11936          IsInitCapture ? diag::err_init_capture_multiple_expressions
11937                        : diag::err_auto_var_init_multiple_expressions)
11938         << VN << Type << Range;
11939     return QualType();
11940   }
11941 
11942   Expr *DeduceInit = DeduceInits[0];
11943   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11944     Diag(Init->getBeginLoc(), IsInitCapture
11945                                   ? diag::err_init_capture_paren_braces
11946                                   : diag::err_auto_var_init_paren_braces)
11947         << isa<InitListExpr>(Init) << VN << Type << Range;
11948     return QualType();
11949   }
11950 
11951   // Expressions default to 'id' when we're in a debugger.
11952   bool DefaultedAnyToId = false;
11953   if (getLangOpts().DebuggerCastResultToId &&
11954       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11955     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11956     if (Result.isInvalid()) {
11957       return QualType();
11958     }
11959     Init = Result.get();
11960     DefaultedAnyToId = true;
11961   }
11962 
11963   // C++ [dcl.decomp]p1:
11964   //   If the assignment-expression [...] has array type A and no ref-qualifier
11965   //   is present, e has type cv A
11966   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11967       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11968       DeduceInit->getType()->isConstantArrayType())
11969     return Context.getQualifiedType(DeduceInit->getType(),
11970                                     Type.getQualifiers());
11971 
11972   QualType DeducedType;
11973   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11974     if (!IsInitCapture)
11975       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11976     else if (isa<InitListExpr>(Init))
11977       Diag(Range.getBegin(),
11978            diag::err_init_capture_deduction_failure_from_init_list)
11979           << VN
11980           << (DeduceInit->getType().isNull() ? TSI->getType()
11981                                              : DeduceInit->getType())
11982           << DeduceInit->getSourceRange();
11983     else
11984       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11985           << VN << TSI->getType()
11986           << (DeduceInit->getType().isNull() ? TSI->getType()
11987                                              : DeduceInit->getType())
11988           << DeduceInit->getSourceRange();
11989   }
11990 
11991   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11992   // 'id' instead of a specific object type prevents most of our usual
11993   // checks.
11994   // We only want to warn outside of template instantiations, though:
11995   // inside a template, the 'id' could have come from a parameter.
11996   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11997       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11998     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11999     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12000   }
12001 
12002   return DeducedType;
12003 }
12004 
12005 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12006                                          Expr *Init) {
12007   assert(!Init || !Init->containsErrors());
12008   QualType DeducedType = deduceVarTypeFromInitializer(
12009       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12010       VDecl->getSourceRange(), DirectInit, Init);
12011   if (DeducedType.isNull()) {
12012     VDecl->setInvalidDecl();
12013     return true;
12014   }
12015 
12016   VDecl->setType(DeducedType);
12017   assert(VDecl->isLinkageValid());
12018 
12019   // In ARC, infer lifetime.
12020   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12021     VDecl->setInvalidDecl();
12022 
12023   if (getLangOpts().OpenCL)
12024     deduceOpenCLAddressSpace(VDecl);
12025 
12026   // If this is a redeclaration, check that the type we just deduced matches
12027   // the previously declared type.
12028   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12029     // We never need to merge the type, because we cannot form an incomplete
12030     // array of auto, nor deduce such a type.
12031     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12032   }
12033 
12034   // Check the deduced type is valid for a variable declaration.
12035   CheckVariableDeclarationType(VDecl);
12036   return VDecl->isInvalidDecl();
12037 }
12038 
12039 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12040                                               SourceLocation Loc) {
12041   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12042     Init = EWC->getSubExpr();
12043 
12044   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12045     Init = CE->getSubExpr();
12046 
12047   QualType InitType = Init->getType();
12048   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12049           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12050          "shouldn't be called if type doesn't have a non-trivial C struct");
12051   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12052     for (auto I : ILE->inits()) {
12053       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12054           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12055         continue;
12056       SourceLocation SL = I->getExprLoc();
12057       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12058     }
12059     return;
12060   }
12061 
12062   if (isa<ImplicitValueInitExpr>(Init)) {
12063     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12064       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12065                             NTCUK_Init);
12066   } else {
12067     // Assume all other explicit initializers involving copying some existing
12068     // object.
12069     // TODO: ignore any explicit initializers where we can guarantee
12070     // copy-elision.
12071     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12072       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12073   }
12074 }
12075 
12076 namespace {
12077 
12078 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12079   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12080   // in the source code or implicitly by the compiler if it is in a union
12081   // defined in a system header and has non-trivial ObjC ownership
12082   // qualifications. We don't want those fields to participate in determining
12083   // whether the containing union is non-trivial.
12084   return FD->hasAttr<UnavailableAttr>();
12085 }
12086 
12087 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12088     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12089                                     void> {
12090   using Super =
12091       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12092                                     void>;
12093 
12094   DiagNonTrivalCUnionDefaultInitializeVisitor(
12095       QualType OrigTy, SourceLocation OrigLoc,
12096       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12097       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12098 
12099   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12100                      const FieldDecl *FD, bool InNonTrivialUnion) {
12101     if (const auto *AT = S.Context.getAsArrayType(QT))
12102       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12103                                      InNonTrivialUnion);
12104     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12105   }
12106 
12107   void visitARCStrong(QualType QT, const FieldDecl *FD,
12108                       bool InNonTrivialUnion) {
12109     if (InNonTrivialUnion)
12110       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12111           << 1 << 0 << QT << FD->getName();
12112   }
12113 
12114   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12115     if (InNonTrivialUnion)
12116       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12117           << 1 << 0 << QT << FD->getName();
12118   }
12119 
12120   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12121     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12122     if (RD->isUnion()) {
12123       if (OrigLoc.isValid()) {
12124         bool IsUnion = false;
12125         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12126           IsUnion = OrigRD->isUnion();
12127         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12128             << 0 << OrigTy << IsUnion << UseContext;
12129         // Reset OrigLoc so that this diagnostic is emitted only once.
12130         OrigLoc = SourceLocation();
12131       }
12132       InNonTrivialUnion = true;
12133     }
12134 
12135     if (InNonTrivialUnion)
12136       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12137           << 0 << 0 << QT.getUnqualifiedType() << "";
12138 
12139     for (const FieldDecl *FD : RD->fields())
12140       if (!shouldIgnoreForRecordTriviality(FD))
12141         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12142   }
12143 
12144   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12145 
12146   // The non-trivial C union type or the struct/union type that contains a
12147   // non-trivial C union.
12148   QualType OrigTy;
12149   SourceLocation OrigLoc;
12150   Sema::NonTrivialCUnionContext UseContext;
12151   Sema &S;
12152 };
12153 
12154 struct DiagNonTrivalCUnionDestructedTypeVisitor
12155     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12156   using Super =
12157       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12158 
12159   DiagNonTrivalCUnionDestructedTypeVisitor(
12160       QualType OrigTy, SourceLocation OrigLoc,
12161       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12162       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12163 
12164   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12165                      const FieldDecl *FD, bool InNonTrivialUnion) {
12166     if (const auto *AT = S.Context.getAsArrayType(QT))
12167       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12168                                      InNonTrivialUnion);
12169     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12170   }
12171 
12172   void visitARCStrong(QualType QT, const FieldDecl *FD,
12173                       bool InNonTrivialUnion) {
12174     if (InNonTrivialUnion)
12175       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12176           << 1 << 1 << QT << FD->getName();
12177   }
12178 
12179   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12180     if (InNonTrivialUnion)
12181       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12182           << 1 << 1 << QT << FD->getName();
12183   }
12184 
12185   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12186     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12187     if (RD->isUnion()) {
12188       if (OrigLoc.isValid()) {
12189         bool IsUnion = false;
12190         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12191           IsUnion = OrigRD->isUnion();
12192         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12193             << 1 << OrigTy << IsUnion << UseContext;
12194         // Reset OrigLoc so that this diagnostic is emitted only once.
12195         OrigLoc = SourceLocation();
12196       }
12197       InNonTrivialUnion = true;
12198     }
12199 
12200     if (InNonTrivialUnion)
12201       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12202           << 0 << 1 << QT.getUnqualifiedType() << "";
12203 
12204     for (const FieldDecl *FD : RD->fields())
12205       if (!shouldIgnoreForRecordTriviality(FD))
12206         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12207   }
12208 
12209   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12210   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12211                           bool InNonTrivialUnion) {}
12212 
12213   // The non-trivial C union type or the struct/union type that contains a
12214   // non-trivial C union.
12215   QualType OrigTy;
12216   SourceLocation OrigLoc;
12217   Sema::NonTrivialCUnionContext UseContext;
12218   Sema &S;
12219 };
12220 
12221 struct DiagNonTrivalCUnionCopyVisitor
12222     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12223   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12224 
12225   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12226                                  Sema::NonTrivialCUnionContext UseContext,
12227                                  Sema &S)
12228       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12229 
12230   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12231                      const FieldDecl *FD, bool InNonTrivialUnion) {
12232     if (const auto *AT = S.Context.getAsArrayType(QT))
12233       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12234                                      InNonTrivialUnion);
12235     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12236   }
12237 
12238   void visitARCStrong(QualType QT, const FieldDecl *FD,
12239                       bool InNonTrivialUnion) {
12240     if (InNonTrivialUnion)
12241       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12242           << 1 << 2 << QT << FD->getName();
12243   }
12244 
12245   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12246     if (InNonTrivialUnion)
12247       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12248           << 1 << 2 << QT << FD->getName();
12249   }
12250 
12251   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12252     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12253     if (RD->isUnion()) {
12254       if (OrigLoc.isValid()) {
12255         bool IsUnion = false;
12256         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12257           IsUnion = OrigRD->isUnion();
12258         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12259             << 2 << OrigTy << IsUnion << UseContext;
12260         // Reset OrigLoc so that this diagnostic is emitted only once.
12261         OrigLoc = SourceLocation();
12262       }
12263       InNonTrivialUnion = true;
12264     }
12265 
12266     if (InNonTrivialUnion)
12267       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12268           << 0 << 2 << QT.getUnqualifiedType() << "";
12269 
12270     for (const FieldDecl *FD : RD->fields())
12271       if (!shouldIgnoreForRecordTriviality(FD))
12272         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12273   }
12274 
12275   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12276                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12277   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12278   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12279                             bool InNonTrivialUnion) {}
12280 
12281   // The non-trivial C union type or the struct/union type that contains a
12282   // non-trivial C union.
12283   QualType OrigTy;
12284   SourceLocation OrigLoc;
12285   Sema::NonTrivialCUnionContext UseContext;
12286   Sema &S;
12287 };
12288 
12289 } // namespace
12290 
12291 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12292                                  NonTrivialCUnionContext UseContext,
12293                                  unsigned NonTrivialKind) {
12294   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12295           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12296           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12297          "shouldn't be called if type doesn't have a non-trivial C union");
12298 
12299   if ((NonTrivialKind & NTCUK_Init) &&
12300       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12301     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12302         .visit(QT, nullptr, false);
12303   if ((NonTrivialKind & NTCUK_Destruct) &&
12304       QT.hasNonTrivialToPrimitiveDestructCUnion())
12305     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12306         .visit(QT, nullptr, false);
12307   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12308     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12309         .visit(QT, nullptr, false);
12310 }
12311 
12312 /// AddInitializerToDecl - Adds the initializer Init to the
12313 /// declaration dcl. If DirectInit is true, this is C++ direct
12314 /// initialization rather than copy initialization.
12315 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12316   // If there is no declaration, there was an error parsing it.  Just ignore
12317   // the initializer.
12318   if (!RealDecl || RealDecl->isInvalidDecl()) {
12319     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12320     return;
12321   }
12322 
12323   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12324     // Pure-specifiers are handled in ActOnPureSpecifier.
12325     Diag(Method->getLocation(), diag::err_member_function_initialization)
12326       << Method->getDeclName() << Init->getSourceRange();
12327     Method->setInvalidDecl();
12328     return;
12329   }
12330 
12331   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12332   if (!VDecl) {
12333     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12334     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12335     RealDecl->setInvalidDecl();
12336     return;
12337   }
12338 
12339   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12340   if (VDecl->getType()->isUndeducedType()) {
12341     // Attempt typo correction early so that the type of the init expression can
12342     // be deduced based on the chosen correction if the original init contains a
12343     // TypoExpr.
12344     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12345     if (!Res.isUsable()) {
12346       // There are unresolved typos in Init, just drop them.
12347       // FIXME: improve the recovery strategy to preserve the Init.
12348       RealDecl->setInvalidDecl();
12349       return;
12350     }
12351     if (Res.get()->containsErrors()) {
12352       // Invalidate the decl as we don't know the type for recovery-expr yet.
12353       RealDecl->setInvalidDecl();
12354       VDecl->setInit(Res.get());
12355       return;
12356     }
12357     Init = Res.get();
12358 
12359     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12360       return;
12361   }
12362 
12363   // dllimport cannot be used on variable definitions.
12364   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12365     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12366     VDecl->setInvalidDecl();
12367     return;
12368   }
12369 
12370   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12371     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12372     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12373     VDecl->setInvalidDecl();
12374     return;
12375   }
12376 
12377   if (!VDecl->getType()->isDependentType()) {
12378     // A definition must end up with a complete type, which means it must be
12379     // complete with the restriction that an array type might be completed by
12380     // the initializer; note that later code assumes this restriction.
12381     QualType BaseDeclType = VDecl->getType();
12382     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12383       BaseDeclType = Array->getElementType();
12384     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12385                             diag::err_typecheck_decl_incomplete_type)) {
12386       RealDecl->setInvalidDecl();
12387       return;
12388     }
12389 
12390     // The variable can not have an abstract class type.
12391     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12392                                diag::err_abstract_type_in_decl,
12393                                AbstractVariableType))
12394       VDecl->setInvalidDecl();
12395   }
12396 
12397   // If adding the initializer will turn this declaration into a definition,
12398   // and we already have a definition for this variable, diagnose or otherwise
12399   // handle the situation.
12400   if (VarDecl *Def = VDecl->getDefinition())
12401     if (Def != VDecl &&
12402         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12403         !VDecl->isThisDeclarationADemotedDefinition() &&
12404         checkVarDeclRedefinition(Def, VDecl))
12405       return;
12406 
12407   if (getLangOpts().CPlusPlus) {
12408     // C++ [class.static.data]p4
12409     //   If a static data member is of const integral or const
12410     //   enumeration type, its declaration in the class definition can
12411     //   specify a constant-initializer which shall be an integral
12412     //   constant expression (5.19). In that case, the member can appear
12413     //   in integral constant expressions. The member shall still be
12414     //   defined in a namespace scope if it is used in the program and the
12415     //   namespace scope definition shall not contain an initializer.
12416     //
12417     // We already performed a redefinition check above, but for static
12418     // data members we also need to check whether there was an in-class
12419     // declaration with an initializer.
12420     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12421       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12422           << VDecl->getDeclName();
12423       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12424            diag::note_previous_initializer)
12425           << 0;
12426       return;
12427     }
12428 
12429     if (VDecl->hasLocalStorage())
12430       setFunctionHasBranchProtectedScope();
12431 
12432     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12433       VDecl->setInvalidDecl();
12434       return;
12435     }
12436   }
12437 
12438   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12439   // a kernel function cannot be initialized."
12440   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12441     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12442     VDecl->setInvalidDecl();
12443     return;
12444   }
12445 
12446   // The LoaderUninitialized attribute acts as a definition (of undef).
12447   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12448     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12449     VDecl->setInvalidDecl();
12450     return;
12451   }
12452 
12453   // Get the decls type and save a reference for later, since
12454   // CheckInitializerTypes may change it.
12455   QualType DclT = VDecl->getType(), SavT = DclT;
12456 
12457   // Expressions default to 'id' when we're in a debugger
12458   // and we are assigning it to a variable of Objective-C pointer type.
12459   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12460       Init->getType() == Context.UnknownAnyTy) {
12461     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12462     if (Result.isInvalid()) {
12463       VDecl->setInvalidDecl();
12464       return;
12465     }
12466     Init = Result.get();
12467   }
12468 
12469   // Perform the initialization.
12470   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12471   if (!VDecl->isInvalidDecl()) {
12472     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12473     InitializationKind Kind = InitializationKind::CreateForInit(
12474         VDecl->getLocation(), DirectInit, Init);
12475 
12476     MultiExprArg Args = Init;
12477     if (CXXDirectInit)
12478       Args = MultiExprArg(CXXDirectInit->getExprs(),
12479                           CXXDirectInit->getNumExprs());
12480 
12481     // Try to correct any TypoExprs in the initialization arguments.
12482     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12483       ExprResult Res = CorrectDelayedTyposInExpr(
12484           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12485           [this, Entity, Kind](Expr *E) {
12486             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12487             return Init.Failed() ? ExprError() : E;
12488           });
12489       if (Res.isInvalid()) {
12490         VDecl->setInvalidDecl();
12491       } else if (Res.get() != Args[Idx]) {
12492         Args[Idx] = Res.get();
12493       }
12494     }
12495     if (VDecl->isInvalidDecl())
12496       return;
12497 
12498     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12499                                    /*TopLevelOfInitList=*/false,
12500                                    /*TreatUnavailableAsInvalid=*/false);
12501     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12502     if (Result.isInvalid()) {
12503       // If the provided initializer fails to initialize the var decl,
12504       // we attach a recovery expr for better recovery.
12505       auto RecoveryExpr =
12506           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12507       if (RecoveryExpr.get())
12508         VDecl->setInit(RecoveryExpr.get());
12509       return;
12510     }
12511 
12512     Init = Result.getAs<Expr>();
12513   }
12514 
12515   // Check for self-references within variable initializers.
12516   // Variables declared within a function/method body (except for references)
12517   // are handled by a dataflow analysis.
12518   // This is undefined behavior in C++, but valid in C.
12519   if (getLangOpts().CPlusPlus)
12520     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12521         VDecl->getType()->isReferenceType())
12522       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12523 
12524   // If the type changed, it means we had an incomplete type that was
12525   // completed by the initializer. For example:
12526   //   int ary[] = { 1, 3, 5 };
12527   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12528   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12529     VDecl->setType(DclT);
12530 
12531   if (!VDecl->isInvalidDecl()) {
12532     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12533 
12534     if (VDecl->hasAttr<BlocksAttr>())
12535       checkRetainCycles(VDecl, Init);
12536 
12537     // It is safe to assign a weak reference into a strong variable.
12538     // Although this code can still have problems:
12539     //   id x = self.weakProp;
12540     //   id y = self.weakProp;
12541     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12542     // paths through the function. This should be revisited if
12543     // -Wrepeated-use-of-weak is made flow-sensitive.
12544     if (FunctionScopeInfo *FSI = getCurFunction())
12545       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12546            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12547           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12548                            Init->getBeginLoc()))
12549         FSI->markSafeWeakUse(Init);
12550   }
12551 
12552   // The initialization is usually a full-expression.
12553   //
12554   // FIXME: If this is a braced initialization of an aggregate, it is not
12555   // an expression, and each individual field initializer is a separate
12556   // full-expression. For instance, in:
12557   //
12558   //   struct Temp { ~Temp(); };
12559   //   struct S { S(Temp); };
12560   //   struct T { S a, b; } t = { Temp(), Temp() }
12561   //
12562   // we should destroy the first Temp before constructing the second.
12563   ExprResult Result =
12564       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12565                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12566   if (Result.isInvalid()) {
12567     VDecl->setInvalidDecl();
12568     return;
12569   }
12570   Init = Result.get();
12571 
12572   // Attach the initializer to the decl.
12573   VDecl->setInit(Init);
12574 
12575   if (VDecl->isLocalVarDecl()) {
12576     // Don't check the initializer if the declaration is malformed.
12577     if (VDecl->isInvalidDecl()) {
12578       // do nothing
12579 
12580     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12581     // This is true even in C++ for OpenCL.
12582     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12583       CheckForConstantInitializer(Init, DclT);
12584 
12585     // Otherwise, C++ does not restrict the initializer.
12586     } else if (getLangOpts().CPlusPlus) {
12587       // do nothing
12588 
12589     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12590     // static storage duration shall be constant expressions or string literals.
12591     } else if (VDecl->getStorageClass() == SC_Static) {
12592       CheckForConstantInitializer(Init, DclT);
12593 
12594     // C89 is stricter than C99 for aggregate initializers.
12595     // C89 6.5.7p3: All the expressions [...] in an initializer list
12596     // for an object that has aggregate or union type shall be
12597     // constant expressions.
12598     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12599                isa<InitListExpr>(Init)) {
12600       const Expr *Culprit;
12601       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12602         Diag(Culprit->getExprLoc(),
12603              diag::ext_aggregate_init_not_constant)
12604           << Culprit->getSourceRange();
12605       }
12606     }
12607 
12608     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12609       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12610         if (VDecl->hasLocalStorage())
12611           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12612   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12613              VDecl->getLexicalDeclContext()->isRecord()) {
12614     // This is an in-class initialization for a static data member, e.g.,
12615     //
12616     // struct S {
12617     //   static const int value = 17;
12618     // };
12619 
12620     // C++ [class.mem]p4:
12621     //   A member-declarator can contain a constant-initializer only
12622     //   if it declares a static member (9.4) of const integral or
12623     //   const enumeration type, see 9.4.2.
12624     //
12625     // C++11 [class.static.data]p3:
12626     //   If a non-volatile non-inline const static data member is of integral
12627     //   or enumeration type, its declaration in the class definition can
12628     //   specify a brace-or-equal-initializer in which every initializer-clause
12629     //   that is an assignment-expression is a constant expression. A static
12630     //   data member of literal type can be declared in the class definition
12631     //   with the constexpr specifier; if so, its declaration shall specify a
12632     //   brace-or-equal-initializer in which every initializer-clause that is
12633     //   an assignment-expression is a constant expression.
12634 
12635     // Do nothing on dependent types.
12636     if (DclT->isDependentType()) {
12637 
12638     // Allow any 'static constexpr' members, whether or not they are of literal
12639     // type. We separately check that every constexpr variable is of literal
12640     // type.
12641     } else if (VDecl->isConstexpr()) {
12642 
12643     // Require constness.
12644     } else if (!DclT.isConstQualified()) {
12645       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12646         << Init->getSourceRange();
12647       VDecl->setInvalidDecl();
12648 
12649     // We allow integer constant expressions in all cases.
12650     } else if (DclT->isIntegralOrEnumerationType()) {
12651       // Check whether the expression is a constant expression.
12652       SourceLocation Loc;
12653       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12654         // In C++11, a non-constexpr const static data member with an
12655         // in-class initializer cannot be volatile.
12656         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12657       else if (Init->isValueDependent())
12658         ; // Nothing to check.
12659       else if (Init->isIntegerConstantExpr(Context, &Loc))
12660         ; // Ok, it's an ICE!
12661       else if (Init->getType()->isScopedEnumeralType() &&
12662                Init->isCXX11ConstantExpr(Context))
12663         ; // Ok, it is a scoped-enum constant expression.
12664       else if (Init->isEvaluatable(Context)) {
12665         // If we can constant fold the initializer through heroics, accept it,
12666         // but report this as a use of an extension for -pedantic.
12667         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12668           << Init->getSourceRange();
12669       } else {
12670         // Otherwise, this is some crazy unknown case.  Report the issue at the
12671         // location provided by the isIntegerConstantExpr failed check.
12672         Diag(Loc, diag::err_in_class_initializer_non_constant)
12673           << Init->getSourceRange();
12674         VDecl->setInvalidDecl();
12675       }
12676 
12677     // We allow foldable floating-point constants as an extension.
12678     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12679       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12680       // it anyway and provide a fixit to add the 'constexpr'.
12681       if (getLangOpts().CPlusPlus11) {
12682         Diag(VDecl->getLocation(),
12683              diag::ext_in_class_initializer_float_type_cxx11)
12684             << DclT << Init->getSourceRange();
12685         Diag(VDecl->getBeginLoc(),
12686              diag::note_in_class_initializer_float_type_cxx11)
12687             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12688       } else {
12689         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12690           << DclT << Init->getSourceRange();
12691 
12692         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12693           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12694             << Init->getSourceRange();
12695           VDecl->setInvalidDecl();
12696         }
12697       }
12698 
12699     // Suggest adding 'constexpr' in C++11 for literal types.
12700     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12701       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12702           << DclT << Init->getSourceRange()
12703           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12704       VDecl->setConstexpr(true);
12705 
12706     } else {
12707       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12708         << DclT << Init->getSourceRange();
12709       VDecl->setInvalidDecl();
12710     }
12711   } else if (VDecl->isFileVarDecl()) {
12712     // In C, extern is typically used to avoid tentative definitions when
12713     // declaring variables in headers, but adding an intializer makes it a
12714     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12715     // In C++, extern is often used to give implictly static const variables
12716     // external linkage, so don't warn in that case. If selectany is present,
12717     // this might be header code intended for C and C++ inclusion, so apply the
12718     // C++ rules.
12719     if (VDecl->getStorageClass() == SC_Extern &&
12720         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12721          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12722         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12723         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12724       Diag(VDecl->getLocation(), diag::warn_extern_init);
12725 
12726     // In Microsoft C++ mode, a const variable defined in namespace scope has
12727     // external linkage by default if the variable is declared with
12728     // __declspec(dllexport).
12729     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12730         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12731         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12732       VDecl->setStorageClass(SC_Extern);
12733 
12734     // C99 6.7.8p4. All file scoped initializers need to be constant.
12735     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12736       CheckForConstantInitializer(Init, DclT);
12737   }
12738 
12739   QualType InitType = Init->getType();
12740   if (!InitType.isNull() &&
12741       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12742        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12743     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12744 
12745   // We will represent direct-initialization similarly to copy-initialization:
12746   //    int x(1);  -as-> int x = 1;
12747   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12748   //
12749   // Clients that want to distinguish between the two forms, can check for
12750   // direct initializer using VarDecl::getInitStyle().
12751   // A major benefit is that clients that don't particularly care about which
12752   // exactly form was it (like the CodeGen) can handle both cases without
12753   // special case code.
12754 
12755   // C++ 8.5p11:
12756   // The form of initialization (using parentheses or '=') is generally
12757   // insignificant, but does matter when the entity being initialized has a
12758   // class type.
12759   if (CXXDirectInit) {
12760     assert(DirectInit && "Call-style initializer must be direct init.");
12761     VDecl->setInitStyle(VarDecl::CallInit);
12762   } else if (DirectInit) {
12763     // This must be list-initialization. No other way is direct-initialization.
12764     VDecl->setInitStyle(VarDecl::ListInit);
12765   }
12766 
12767   if (LangOpts.OpenMP &&
12768       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12769       VDecl->isFileVarDecl())
12770     DeclsToCheckForDeferredDiags.insert(VDecl);
12771   CheckCompleteVariableDeclaration(VDecl);
12772 }
12773 
12774 /// ActOnInitializerError - Given that there was an error parsing an
12775 /// initializer for the given declaration, try to at least re-establish
12776 /// invariants such as whether a variable's type is either dependent or
12777 /// complete.
12778 void Sema::ActOnInitializerError(Decl *D) {
12779   // Our main concern here is re-establishing invariants like "a
12780   // variable's type is either dependent or complete".
12781   if (!D || D->isInvalidDecl()) return;
12782 
12783   VarDecl *VD = dyn_cast<VarDecl>(D);
12784   if (!VD) return;
12785 
12786   // Bindings are not usable if we can't make sense of the initializer.
12787   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12788     for (auto *BD : DD->bindings())
12789       BD->setInvalidDecl();
12790 
12791   // Auto types are meaningless if we can't make sense of the initializer.
12792   if (VD->getType()->isUndeducedType()) {
12793     D->setInvalidDecl();
12794     return;
12795   }
12796 
12797   QualType Ty = VD->getType();
12798   if (Ty->isDependentType()) return;
12799 
12800   // Require a complete type.
12801   if (RequireCompleteType(VD->getLocation(),
12802                           Context.getBaseElementType(Ty),
12803                           diag::err_typecheck_decl_incomplete_type)) {
12804     VD->setInvalidDecl();
12805     return;
12806   }
12807 
12808   // Require a non-abstract type.
12809   if (RequireNonAbstractType(VD->getLocation(), Ty,
12810                              diag::err_abstract_type_in_decl,
12811                              AbstractVariableType)) {
12812     VD->setInvalidDecl();
12813     return;
12814   }
12815 
12816   // Don't bother complaining about constructors or destructors,
12817   // though.
12818 }
12819 
12820 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12821   // If there is no declaration, there was an error parsing it. Just ignore it.
12822   if (!RealDecl)
12823     return;
12824 
12825   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12826     QualType Type = Var->getType();
12827 
12828     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12829     if (isa<DecompositionDecl>(RealDecl)) {
12830       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12831       Var->setInvalidDecl();
12832       return;
12833     }
12834 
12835     if (Type->isUndeducedType() &&
12836         DeduceVariableDeclarationType(Var, false, nullptr))
12837       return;
12838 
12839     // C++11 [class.static.data]p3: A static data member can be declared with
12840     // the constexpr specifier; if so, its declaration shall specify
12841     // a brace-or-equal-initializer.
12842     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12843     // the definition of a variable [...] or the declaration of a static data
12844     // member.
12845     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12846         !Var->isThisDeclarationADemotedDefinition()) {
12847       if (Var->isStaticDataMember()) {
12848         // C++1z removes the relevant rule; the in-class declaration is always
12849         // a definition there.
12850         if (!getLangOpts().CPlusPlus17 &&
12851             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12852           Diag(Var->getLocation(),
12853                diag::err_constexpr_static_mem_var_requires_init)
12854               << Var;
12855           Var->setInvalidDecl();
12856           return;
12857         }
12858       } else {
12859         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12860         Var->setInvalidDecl();
12861         return;
12862       }
12863     }
12864 
12865     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12866     // be initialized.
12867     if (!Var->isInvalidDecl() &&
12868         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12869         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12870       bool HasConstExprDefaultConstructor = false;
12871       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12872         for (auto *Ctor : RD->ctors()) {
12873           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12874               Ctor->getMethodQualifiers().getAddressSpace() ==
12875                   LangAS::opencl_constant) {
12876             HasConstExprDefaultConstructor = true;
12877           }
12878         }
12879       }
12880       if (!HasConstExprDefaultConstructor) {
12881         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12882         Var->setInvalidDecl();
12883         return;
12884       }
12885     }
12886 
12887     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12888       if (Var->getStorageClass() == SC_Extern) {
12889         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12890             << Var;
12891         Var->setInvalidDecl();
12892         return;
12893       }
12894       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12895                               diag::err_typecheck_decl_incomplete_type)) {
12896         Var->setInvalidDecl();
12897         return;
12898       }
12899       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12900         if (!RD->hasTrivialDefaultConstructor()) {
12901           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12902           Var->setInvalidDecl();
12903           return;
12904         }
12905       }
12906       // The declaration is unitialized, no need for further checks.
12907       return;
12908     }
12909 
12910     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12911     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12912         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12913       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12914                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12915 
12916 
12917     switch (DefKind) {
12918     case VarDecl::Definition:
12919       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12920         break;
12921 
12922       // We have an out-of-line definition of a static data member
12923       // that has an in-class initializer, so we type-check this like
12924       // a declaration.
12925       //
12926       LLVM_FALLTHROUGH;
12927 
12928     case VarDecl::DeclarationOnly:
12929       // It's only a declaration.
12930 
12931       // Block scope. C99 6.7p7: If an identifier for an object is
12932       // declared with no linkage (C99 6.2.2p6), the type for the
12933       // object shall be complete.
12934       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12935           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12936           RequireCompleteType(Var->getLocation(), Type,
12937                               diag::err_typecheck_decl_incomplete_type))
12938         Var->setInvalidDecl();
12939 
12940       // Make sure that the type is not abstract.
12941       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12942           RequireNonAbstractType(Var->getLocation(), Type,
12943                                  diag::err_abstract_type_in_decl,
12944                                  AbstractVariableType))
12945         Var->setInvalidDecl();
12946       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12947           Var->getStorageClass() == SC_PrivateExtern) {
12948         Diag(Var->getLocation(), diag::warn_private_extern);
12949         Diag(Var->getLocation(), diag::note_private_extern);
12950       }
12951 
12952       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12953           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12954         ExternalDeclarations.push_back(Var);
12955 
12956       return;
12957 
12958     case VarDecl::TentativeDefinition:
12959       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12960       // object that has file scope without an initializer, and without a
12961       // storage-class specifier or with the storage-class specifier "static",
12962       // constitutes a tentative definition. Note: A tentative definition with
12963       // external linkage is valid (C99 6.2.2p5).
12964       if (!Var->isInvalidDecl()) {
12965         if (const IncompleteArrayType *ArrayT
12966                                     = Context.getAsIncompleteArrayType(Type)) {
12967           if (RequireCompleteSizedType(
12968                   Var->getLocation(), ArrayT->getElementType(),
12969                   diag::err_array_incomplete_or_sizeless_type))
12970             Var->setInvalidDecl();
12971         } else if (Var->getStorageClass() == SC_Static) {
12972           // C99 6.9.2p3: If the declaration of an identifier for an object is
12973           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12974           // declared type shall not be an incomplete type.
12975           // NOTE: code such as the following
12976           //     static struct s;
12977           //     struct s { int a; };
12978           // is accepted by gcc. Hence here we issue a warning instead of
12979           // an error and we do not invalidate the static declaration.
12980           // NOTE: to avoid multiple warnings, only check the first declaration.
12981           if (Var->isFirstDecl())
12982             RequireCompleteType(Var->getLocation(), Type,
12983                                 diag::ext_typecheck_decl_incomplete_type);
12984         }
12985       }
12986 
12987       // Record the tentative definition; we're done.
12988       if (!Var->isInvalidDecl())
12989         TentativeDefinitions.push_back(Var);
12990       return;
12991     }
12992 
12993     // Provide a specific diagnostic for uninitialized variable
12994     // definitions with incomplete array type.
12995     if (Type->isIncompleteArrayType()) {
12996       Diag(Var->getLocation(),
12997            diag::err_typecheck_incomplete_array_needs_initializer);
12998       Var->setInvalidDecl();
12999       return;
13000     }
13001 
13002     // Provide a specific diagnostic for uninitialized variable
13003     // definitions with reference type.
13004     if (Type->isReferenceType()) {
13005       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13006           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13007       Var->setInvalidDecl();
13008       return;
13009     }
13010 
13011     // Do not attempt to type-check the default initializer for a
13012     // variable with dependent type.
13013     if (Type->isDependentType())
13014       return;
13015 
13016     if (Var->isInvalidDecl())
13017       return;
13018 
13019     if (!Var->hasAttr<AliasAttr>()) {
13020       if (RequireCompleteType(Var->getLocation(),
13021                               Context.getBaseElementType(Type),
13022                               diag::err_typecheck_decl_incomplete_type)) {
13023         Var->setInvalidDecl();
13024         return;
13025       }
13026     } else {
13027       return;
13028     }
13029 
13030     // The variable can not have an abstract class type.
13031     if (RequireNonAbstractType(Var->getLocation(), Type,
13032                                diag::err_abstract_type_in_decl,
13033                                AbstractVariableType)) {
13034       Var->setInvalidDecl();
13035       return;
13036     }
13037 
13038     // Check for jumps past the implicit initializer.  C++0x
13039     // clarifies that this applies to a "variable with automatic
13040     // storage duration", not a "local variable".
13041     // C++11 [stmt.dcl]p3
13042     //   A program that jumps from a point where a variable with automatic
13043     //   storage duration is not in scope to a point where it is in scope is
13044     //   ill-formed unless the variable has scalar type, class type with a
13045     //   trivial default constructor and a trivial destructor, a cv-qualified
13046     //   version of one of these types, or an array of one of the preceding
13047     //   types and is declared without an initializer.
13048     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13049       if (const RecordType *Record
13050             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13051         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13052         // Mark the function (if we're in one) for further checking even if the
13053         // looser rules of C++11 do not require such checks, so that we can
13054         // diagnose incompatibilities with C++98.
13055         if (!CXXRecord->isPOD())
13056           setFunctionHasBranchProtectedScope();
13057       }
13058     }
13059     // In OpenCL, we can't initialize objects in the __local address space,
13060     // even implicitly, so don't synthesize an implicit initializer.
13061     if (getLangOpts().OpenCL &&
13062         Var->getType().getAddressSpace() == LangAS::opencl_local)
13063       return;
13064     // C++03 [dcl.init]p9:
13065     //   If no initializer is specified for an object, and the
13066     //   object is of (possibly cv-qualified) non-POD class type (or
13067     //   array thereof), the object shall be default-initialized; if
13068     //   the object is of const-qualified type, the underlying class
13069     //   type shall have a user-declared default
13070     //   constructor. Otherwise, if no initializer is specified for
13071     //   a non- static object, the object and its subobjects, if
13072     //   any, have an indeterminate initial value); if the object
13073     //   or any of its subobjects are of const-qualified type, the
13074     //   program is ill-formed.
13075     // C++0x [dcl.init]p11:
13076     //   If no initializer is specified for an object, the object is
13077     //   default-initialized; [...].
13078     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13079     InitializationKind Kind
13080       = InitializationKind::CreateDefault(Var->getLocation());
13081 
13082     InitializationSequence InitSeq(*this, Entity, Kind, None);
13083     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13084 
13085     if (Init.get()) {
13086       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13087       // This is important for template substitution.
13088       Var->setInitStyle(VarDecl::CallInit);
13089     } else if (Init.isInvalid()) {
13090       // If default-init fails, attach a recovery-expr initializer to track
13091       // that initialization was attempted and failed.
13092       auto RecoveryExpr =
13093           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13094       if (RecoveryExpr.get())
13095         Var->setInit(RecoveryExpr.get());
13096     }
13097 
13098     CheckCompleteVariableDeclaration(Var);
13099   }
13100 }
13101 
13102 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13103   // If there is no declaration, there was an error parsing it. Ignore it.
13104   if (!D)
13105     return;
13106 
13107   VarDecl *VD = dyn_cast<VarDecl>(D);
13108   if (!VD) {
13109     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13110     D->setInvalidDecl();
13111     return;
13112   }
13113 
13114   VD->setCXXForRangeDecl(true);
13115 
13116   // for-range-declaration cannot be given a storage class specifier.
13117   int Error = -1;
13118   switch (VD->getStorageClass()) {
13119   case SC_None:
13120     break;
13121   case SC_Extern:
13122     Error = 0;
13123     break;
13124   case SC_Static:
13125     Error = 1;
13126     break;
13127   case SC_PrivateExtern:
13128     Error = 2;
13129     break;
13130   case SC_Auto:
13131     Error = 3;
13132     break;
13133   case SC_Register:
13134     Error = 4;
13135     break;
13136   }
13137 
13138   // for-range-declaration cannot be given a storage class specifier con't.
13139   switch (VD->getTSCSpec()) {
13140   case TSCS_thread_local:
13141     Error = 6;
13142     break;
13143   case TSCS___thread:
13144   case TSCS__Thread_local:
13145   case TSCS_unspecified:
13146     break;
13147   }
13148 
13149   if (Error != -1) {
13150     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13151         << VD << Error;
13152     D->setInvalidDecl();
13153   }
13154 }
13155 
13156 StmtResult
13157 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13158                                  IdentifierInfo *Ident,
13159                                  ParsedAttributes &Attrs,
13160                                  SourceLocation AttrEnd) {
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, AttrEnd);
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                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13184 }
13185 
13186 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13187   if (var->isInvalidDecl()) return;
13188 
13189   MaybeAddCUDAConstantAttr(var);
13190 
13191   if (getLangOpts().OpenCL) {
13192     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13193     // initialiser
13194     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13195         !var->hasInit()) {
13196       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13197           << 1 /*Init*/;
13198       var->setInvalidDecl();
13199       return;
13200     }
13201   }
13202 
13203   // In Objective-C, don't allow jumps past the implicit initialization of a
13204   // local retaining variable.
13205   if (getLangOpts().ObjC &&
13206       var->hasLocalStorage()) {
13207     switch (var->getType().getObjCLifetime()) {
13208     case Qualifiers::OCL_None:
13209     case Qualifiers::OCL_ExplicitNone:
13210     case Qualifiers::OCL_Autoreleasing:
13211       break;
13212 
13213     case Qualifiers::OCL_Weak:
13214     case Qualifiers::OCL_Strong:
13215       setFunctionHasBranchProtectedScope();
13216       break;
13217     }
13218   }
13219 
13220   if (var->hasLocalStorage() &&
13221       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13222     setFunctionHasBranchProtectedScope();
13223 
13224   // Warn about externally-visible variables being defined without a
13225   // prior declaration.  We only want to do this for global
13226   // declarations, but we also specifically need to avoid doing it for
13227   // class members because the linkage of an anonymous class can
13228   // change if it's later given a typedef name.
13229   if (var->isThisDeclarationADefinition() &&
13230       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13231       var->isExternallyVisible() && var->hasLinkage() &&
13232       !var->isInline() && !var->getDescribedVarTemplate() &&
13233       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13234       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13235       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13236                                   var->getLocation())) {
13237     // Find a previous declaration that's not a definition.
13238     VarDecl *prev = var->getPreviousDecl();
13239     while (prev && prev->isThisDeclarationADefinition())
13240       prev = prev->getPreviousDecl();
13241 
13242     if (!prev) {
13243       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13244       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13245           << /* variable */ 0;
13246     }
13247   }
13248 
13249   // Cache the result of checking for constant initialization.
13250   Optional<bool> CacheHasConstInit;
13251   const Expr *CacheCulprit = nullptr;
13252   auto checkConstInit = [&]() mutable {
13253     if (!CacheHasConstInit)
13254       CacheHasConstInit = var->getInit()->isConstantInitializer(
13255             Context, var->getType()->isReferenceType(), &CacheCulprit);
13256     return *CacheHasConstInit;
13257   };
13258 
13259   if (var->getTLSKind() == VarDecl::TLS_Static) {
13260     if (var->getType().isDestructedType()) {
13261       // GNU C++98 edits for __thread, [basic.start.term]p3:
13262       //   The type of an object with thread storage duration shall not
13263       //   have a non-trivial destructor.
13264       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13265       if (getLangOpts().CPlusPlus11)
13266         Diag(var->getLocation(), diag::note_use_thread_local);
13267     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13268       if (!checkConstInit()) {
13269         // GNU C++98 edits for __thread, [basic.start.init]p4:
13270         //   An object of thread storage duration shall not require dynamic
13271         //   initialization.
13272         // FIXME: Need strict checking here.
13273         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13274           << CacheCulprit->getSourceRange();
13275         if (getLangOpts().CPlusPlus11)
13276           Diag(var->getLocation(), diag::note_use_thread_local);
13277       }
13278     }
13279   }
13280 
13281 
13282   if (!var->getType()->isStructureType() && var->hasInit() &&
13283       isa<InitListExpr>(var->getInit())) {
13284     const auto *ILE = cast<InitListExpr>(var->getInit());
13285     unsigned NumInits = ILE->getNumInits();
13286     if (NumInits > 2)
13287       for (unsigned I = 0; I < NumInits; ++I) {
13288         const auto *Init = ILE->getInit(I);
13289         if (!Init)
13290           break;
13291         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13292         if (!SL)
13293           break;
13294 
13295         unsigned NumConcat = SL->getNumConcatenated();
13296         // Diagnose missing comma in string array initialization.
13297         // Do not warn when all the elements in the initializer are concatenated
13298         // together. Do not warn for macros too.
13299         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13300           bool OnlyOneMissingComma = true;
13301           for (unsigned J = I + 1; J < NumInits; ++J) {
13302             const auto *Init = ILE->getInit(J);
13303             if (!Init)
13304               break;
13305             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13306             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13307               OnlyOneMissingComma = false;
13308               break;
13309             }
13310           }
13311 
13312           if (OnlyOneMissingComma) {
13313             SmallVector<FixItHint, 1> Hints;
13314             for (unsigned i = 0; i < NumConcat - 1; ++i)
13315               Hints.push_back(FixItHint::CreateInsertion(
13316                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13317 
13318             Diag(SL->getStrTokenLoc(1),
13319                  diag::warn_concatenated_literal_array_init)
13320                 << Hints;
13321             Diag(SL->getBeginLoc(),
13322                  diag::note_concatenated_string_literal_silence);
13323           }
13324           // In any case, stop now.
13325           break;
13326         }
13327       }
13328   }
13329 
13330 
13331   QualType type = var->getType();
13332 
13333   if (var->hasAttr<BlocksAttr>())
13334     getCurFunction()->addByrefBlockVar(var);
13335 
13336   Expr *Init = var->getInit();
13337   bool GlobalStorage = var->hasGlobalStorage();
13338   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13339   QualType baseType = Context.getBaseElementType(type);
13340   bool HasConstInit = true;
13341 
13342   // Check whether the initializer is sufficiently constant.
13343   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13344       !Init->isValueDependent() &&
13345       (GlobalStorage || var->isConstexpr() ||
13346        var->mightBeUsableInConstantExpressions(Context))) {
13347     // If this variable might have a constant initializer or might be usable in
13348     // constant expressions, check whether or not it actually is now.  We can't
13349     // do this lazily, because the result might depend on things that change
13350     // later, such as which constexpr functions happen to be defined.
13351     SmallVector<PartialDiagnosticAt, 8> Notes;
13352     if (!getLangOpts().CPlusPlus11) {
13353       // Prior to C++11, in contexts where a constant initializer is required,
13354       // the set of valid constant initializers is described by syntactic rules
13355       // in [expr.const]p2-6.
13356       // FIXME: Stricter checking for these rules would be useful for constinit /
13357       // -Wglobal-constructors.
13358       HasConstInit = checkConstInit();
13359 
13360       // Compute and cache the constant value, and remember that we have a
13361       // constant initializer.
13362       if (HasConstInit) {
13363         (void)var->checkForConstantInitialization(Notes);
13364         Notes.clear();
13365       } else if (CacheCulprit) {
13366         Notes.emplace_back(CacheCulprit->getExprLoc(),
13367                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13368         Notes.back().second << CacheCulprit->getSourceRange();
13369       }
13370     } else {
13371       // Evaluate the initializer to see if it's a constant initializer.
13372       HasConstInit = var->checkForConstantInitialization(Notes);
13373     }
13374 
13375     if (HasConstInit) {
13376       // FIXME: Consider replacing the initializer with a ConstantExpr.
13377     } else if (var->isConstexpr()) {
13378       SourceLocation DiagLoc = var->getLocation();
13379       // If the note doesn't add any useful information other than a source
13380       // location, fold it into the primary diagnostic.
13381       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13382                                    diag::note_invalid_subexpr_in_const_expr) {
13383         DiagLoc = Notes[0].first;
13384         Notes.clear();
13385       }
13386       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13387           << var << Init->getSourceRange();
13388       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13389         Diag(Notes[I].first, Notes[I].second);
13390     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13391       auto *Attr = var->getAttr<ConstInitAttr>();
13392       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13393           << Init->getSourceRange();
13394       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13395           << Attr->getRange() << Attr->isConstinit();
13396       for (auto &it : Notes)
13397         Diag(it.first, it.second);
13398     } else if (IsGlobal &&
13399                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13400                                            var->getLocation())) {
13401       // Warn about globals which don't have a constant initializer.  Don't
13402       // warn about globals with a non-trivial destructor because we already
13403       // warned about them.
13404       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13405       if (!(RD && !RD->hasTrivialDestructor())) {
13406         // checkConstInit() here permits trivial default initialization even in
13407         // C++11 onwards, where such an initializer is not a constant initializer
13408         // but nonetheless doesn't require a global constructor.
13409         if (!checkConstInit())
13410           Diag(var->getLocation(), diag::warn_global_constructor)
13411               << Init->getSourceRange();
13412       }
13413     }
13414   }
13415 
13416   // Apply section attributes and pragmas to global variables.
13417   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13418       !inTemplateInstantiation()) {
13419     PragmaStack<StringLiteral *> *Stack = nullptr;
13420     int SectionFlags = ASTContext::PSF_Read;
13421     if (var->getType().isConstQualified()) {
13422       if (HasConstInit)
13423         Stack = &ConstSegStack;
13424       else {
13425         Stack = &BSSSegStack;
13426         SectionFlags |= ASTContext::PSF_Write;
13427       }
13428     } else if (var->hasInit() && HasConstInit) {
13429       Stack = &DataSegStack;
13430       SectionFlags |= ASTContext::PSF_Write;
13431     } else {
13432       Stack = &BSSSegStack;
13433       SectionFlags |= ASTContext::PSF_Write;
13434     }
13435     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13436       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13437         SectionFlags |= ASTContext::PSF_Implicit;
13438       UnifySection(SA->getName(), SectionFlags, var);
13439     } else if (Stack->CurrentValue) {
13440       SectionFlags |= ASTContext::PSF_Implicit;
13441       auto SectionName = Stack->CurrentValue->getString();
13442       var->addAttr(SectionAttr::CreateImplicit(
13443           Context, SectionName, Stack->CurrentPragmaLocation,
13444           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13445       if (UnifySection(SectionName, SectionFlags, var))
13446         var->dropAttr<SectionAttr>();
13447     }
13448 
13449     // Apply the init_seg attribute if this has an initializer.  If the
13450     // initializer turns out to not be dynamic, we'll end up ignoring this
13451     // attribute.
13452     if (CurInitSeg && var->getInit())
13453       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13454                                                CurInitSegLoc,
13455                                                AttributeCommonInfo::AS_Pragma));
13456   }
13457 
13458   // All the following checks are C++ only.
13459   if (!getLangOpts().CPlusPlus) {
13460     // If this variable must be emitted, add it as an initializer for the
13461     // current module.
13462     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13463       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13464     return;
13465   }
13466 
13467   // Require the destructor.
13468   if (!type->isDependentType())
13469     if (const RecordType *recordType = baseType->getAs<RecordType>())
13470       FinalizeVarWithDestructor(var, recordType);
13471 
13472   // If this variable must be emitted, add it as an initializer for the current
13473   // module.
13474   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13475     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13476 
13477   // Build the bindings if this is a structured binding declaration.
13478   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13479     CheckCompleteDecompositionDeclaration(DD);
13480 }
13481 
13482 /// Check if VD needs to be dllexport/dllimport due to being in a
13483 /// dllexport/import function.
13484 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13485   assert(VD->isStaticLocal());
13486 
13487   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13488 
13489   // Find outermost function when VD is in lambda function.
13490   while (FD && !getDLLAttr(FD) &&
13491          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13492          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13493     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13494   }
13495 
13496   if (!FD)
13497     return;
13498 
13499   // Static locals inherit dll attributes from their function.
13500   if (Attr *A = getDLLAttr(FD)) {
13501     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13502     NewAttr->setInherited(true);
13503     VD->addAttr(NewAttr);
13504   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13505     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13506     NewAttr->setInherited(true);
13507     VD->addAttr(NewAttr);
13508 
13509     // Export this function to enforce exporting this static variable even
13510     // if it is not used in this compilation unit.
13511     if (!FD->hasAttr<DLLExportAttr>())
13512       FD->addAttr(NewAttr);
13513 
13514   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13515     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13516     NewAttr->setInherited(true);
13517     VD->addAttr(NewAttr);
13518   }
13519 }
13520 
13521 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13522 /// any semantic actions necessary after any initializer has been attached.
13523 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13524   // Note that we are no longer parsing the initializer for this declaration.
13525   ParsingInitForAutoVars.erase(ThisDecl);
13526 
13527   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13528   if (!VD)
13529     return;
13530 
13531   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13532   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13533       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13534     if (PragmaClangBSSSection.Valid)
13535       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13536           Context, PragmaClangBSSSection.SectionName,
13537           PragmaClangBSSSection.PragmaLocation,
13538           AttributeCommonInfo::AS_Pragma));
13539     if (PragmaClangDataSection.Valid)
13540       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13541           Context, PragmaClangDataSection.SectionName,
13542           PragmaClangDataSection.PragmaLocation,
13543           AttributeCommonInfo::AS_Pragma));
13544     if (PragmaClangRodataSection.Valid)
13545       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13546           Context, PragmaClangRodataSection.SectionName,
13547           PragmaClangRodataSection.PragmaLocation,
13548           AttributeCommonInfo::AS_Pragma));
13549     if (PragmaClangRelroSection.Valid)
13550       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13551           Context, PragmaClangRelroSection.SectionName,
13552           PragmaClangRelroSection.PragmaLocation,
13553           AttributeCommonInfo::AS_Pragma));
13554   }
13555 
13556   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13557     for (auto *BD : DD->bindings()) {
13558       FinalizeDeclaration(BD);
13559     }
13560   }
13561 
13562   checkAttributesAfterMerging(*this, *VD);
13563 
13564   // Perform TLS alignment check here after attributes attached to the variable
13565   // which may affect the alignment have been processed. Only perform the check
13566   // if the target has a maximum TLS alignment (zero means no constraints).
13567   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13568     // Protect the check so that it's not performed on dependent types and
13569     // dependent alignments (we can't determine the alignment in that case).
13570     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13571       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13572       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13573         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13574           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13575           << (unsigned)MaxAlignChars.getQuantity();
13576       }
13577     }
13578   }
13579 
13580   if (VD->isStaticLocal())
13581     CheckStaticLocalForDllExport(VD);
13582 
13583   // Perform check for initializers of device-side global variables.
13584   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13585   // 7.5). We must also apply the same checks to all __shared__
13586   // variables whether they are local or not. CUDA also allows
13587   // constant initializers for __constant__ and __device__ variables.
13588   if (getLangOpts().CUDA)
13589     checkAllowedCUDAInitializer(VD);
13590 
13591   // Grab the dllimport or dllexport attribute off of the VarDecl.
13592   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13593 
13594   // Imported static data members cannot be defined out-of-line.
13595   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13596     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13597         VD->isThisDeclarationADefinition()) {
13598       // We allow definitions of dllimport class template static data members
13599       // with a warning.
13600       CXXRecordDecl *Context =
13601         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13602       bool IsClassTemplateMember =
13603           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13604           Context->getDescribedClassTemplate();
13605 
13606       Diag(VD->getLocation(),
13607            IsClassTemplateMember
13608                ? diag::warn_attribute_dllimport_static_field_definition
13609                : diag::err_attribute_dllimport_static_field_definition);
13610       Diag(IA->getLocation(), diag::note_attribute);
13611       if (!IsClassTemplateMember)
13612         VD->setInvalidDecl();
13613     }
13614   }
13615 
13616   // dllimport/dllexport variables cannot be thread local, their TLS index
13617   // isn't exported with the variable.
13618   if (DLLAttr && VD->getTLSKind()) {
13619     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13620     if (F && getDLLAttr(F)) {
13621       assert(VD->isStaticLocal());
13622       // But if this is a static local in a dlimport/dllexport function, the
13623       // function will never be inlined, which means the var would never be
13624       // imported, so having it marked import/export is safe.
13625     } else {
13626       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13627                                                                     << DLLAttr;
13628       VD->setInvalidDecl();
13629     }
13630   }
13631 
13632   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13633     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13634       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13635           << Attr;
13636       VD->dropAttr<UsedAttr>();
13637     }
13638   }
13639   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13640     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13641       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13642           << Attr;
13643       VD->dropAttr<RetainAttr>();
13644     }
13645   }
13646 
13647   const DeclContext *DC = VD->getDeclContext();
13648   // If there's a #pragma GCC visibility in scope, and this isn't a class
13649   // member, set the visibility of this variable.
13650   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13651     AddPushedVisibilityAttribute(VD);
13652 
13653   // FIXME: Warn on unused var template partial specializations.
13654   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13655     MarkUnusedFileScopedDecl(VD);
13656 
13657   // Now we have parsed the initializer and can update the table of magic
13658   // tag values.
13659   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13660       !VD->getType()->isIntegralOrEnumerationType())
13661     return;
13662 
13663   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13664     const Expr *MagicValueExpr = VD->getInit();
13665     if (!MagicValueExpr) {
13666       continue;
13667     }
13668     Optional<llvm::APSInt> MagicValueInt;
13669     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13670       Diag(I->getRange().getBegin(),
13671            diag::err_type_tag_for_datatype_not_ice)
13672         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13673       continue;
13674     }
13675     if (MagicValueInt->getActiveBits() > 64) {
13676       Diag(I->getRange().getBegin(),
13677            diag::err_type_tag_for_datatype_too_large)
13678         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13679       continue;
13680     }
13681     uint64_t MagicValue = MagicValueInt->getZExtValue();
13682     RegisterTypeTagForDatatype(I->getArgumentKind(),
13683                                MagicValue,
13684                                I->getMatchingCType(),
13685                                I->getLayoutCompatible(),
13686                                I->getMustBeNull());
13687   }
13688 }
13689 
13690 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13691   auto *VD = dyn_cast<VarDecl>(DD);
13692   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13693 }
13694 
13695 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13696                                                    ArrayRef<Decl *> Group) {
13697   SmallVector<Decl*, 8> Decls;
13698 
13699   if (DS.isTypeSpecOwned())
13700     Decls.push_back(DS.getRepAsDecl());
13701 
13702   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13703   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13704   bool DiagnosedMultipleDecomps = false;
13705   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13706   bool DiagnosedNonDeducedAuto = false;
13707 
13708   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13709     if (Decl *D = Group[i]) {
13710       // For declarators, there are some additional syntactic-ish checks we need
13711       // to perform.
13712       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13713         if (!FirstDeclaratorInGroup)
13714           FirstDeclaratorInGroup = DD;
13715         if (!FirstDecompDeclaratorInGroup)
13716           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13717         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13718             !hasDeducedAuto(DD))
13719           FirstNonDeducedAutoInGroup = DD;
13720 
13721         if (FirstDeclaratorInGroup != DD) {
13722           // A decomposition declaration cannot be combined with any other
13723           // declaration in the same group.
13724           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13725             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13726                  diag::err_decomp_decl_not_alone)
13727                 << FirstDeclaratorInGroup->getSourceRange()
13728                 << DD->getSourceRange();
13729             DiagnosedMultipleDecomps = true;
13730           }
13731 
13732           // A declarator that uses 'auto' in any way other than to declare a
13733           // variable with a deduced type cannot be combined with any other
13734           // declarator in the same group.
13735           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13736             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13737                  diag::err_auto_non_deduced_not_alone)
13738                 << FirstNonDeducedAutoInGroup->getType()
13739                        ->hasAutoForTrailingReturnType()
13740                 << FirstDeclaratorInGroup->getSourceRange()
13741                 << DD->getSourceRange();
13742             DiagnosedNonDeducedAuto = true;
13743           }
13744         }
13745       }
13746 
13747       Decls.push_back(D);
13748     }
13749   }
13750 
13751   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13752     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13753       handleTagNumbering(Tag, S);
13754       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13755           getLangOpts().CPlusPlus)
13756         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13757     }
13758   }
13759 
13760   return BuildDeclaratorGroup(Decls);
13761 }
13762 
13763 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13764 /// group, performing any necessary semantic checking.
13765 Sema::DeclGroupPtrTy
13766 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13767   // C++14 [dcl.spec.auto]p7: (DR1347)
13768   //   If the type that replaces the placeholder type is not the same in each
13769   //   deduction, the program is ill-formed.
13770   if (Group.size() > 1) {
13771     QualType Deduced;
13772     VarDecl *DeducedDecl = nullptr;
13773     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13774       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13775       if (!D || D->isInvalidDecl())
13776         break;
13777       DeducedType *DT = D->getType()->getContainedDeducedType();
13778       if (!DT || DT->getDeducedType().isNull())
13779         continue;
13780       if (Deduced.isNull()) {
13781         Deduced = DT->getDeducedType();
13782         DeducedDecl = D;
13783       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13784         auto *AT = dyn_cast<AutoType>(DT);
13785         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13786                         diag::err_auto_different_deductions)
13787                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13788                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13789                    << D->getDeclName();
13790         if (DeducedDecl->hasInit())
13791           Dia << DeducedDecl->getInit()->getSourceRange();
13792         if (D->getInit())
13793           Dia << D->getInit()->getSourceRange();
13794         D->setInvalidDecl();
13795         break;
13796       }
13797     }
13798   }
13799 
13800   ActOnDocumentableDecls(Group);
13801 
13802   return DeclGroupPtrTy::make(
13803       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13804 }
13805 
13806 void Sema::ActOnDocumentableDecl(Decl *D) {
13807   ActOnDocumentableDecls(D);
13808 }
13809 
13810 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13811   // Don't parse the comment if Doxygen diagnostics are ignored.
13812   if (Group.empty() || !Group[0])
13813     return;
13814 
13815   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13816                       Group[0]->getLocation()) &&
13817       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13818                       Group[0]->getLocation()))
13819     return;
13820 
13821   if (Group.size() >= 2) {
13822     // This is a decl group.  Normally it will contain only declarations
13823     // produced from declarator list.  But in case we have any definitions or
13824     // additional declaration references:
13825     //   'typedef struct S {} S;'
13826     //   'typedef struct S *S;'
13827     //   'struct S *pS;'
13828     // FinalizeDeclaratorGroup adds these as separate declarations.
13829     Decl *MaybeTagDecl = Group[0];
13830     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13831       Group = Group.slice(1);
13832     }
13833   }
13834 
13835   // FIMXE: We assume every Decl in the group is in the same file.
13836   // This is false when preprocessor constructs the group from decls in
13837   // different files (e. g. macros or #include).
13838   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13839 }
13840 
13841 /// Common checks for a parameter-declaration that should apply to both function
13842 /// parameters and non-type template parameters.
13843 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13844   // Check that there are no default arguments inside the type of this
13845   // parameter.
13846   if (getLangOpts().CPlusPlus)
13847     CheckExtraCXXDefaultArguments(D);
13848 
13849   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13850   if (D.getCXXScopeSpec().isSet()) {
13851     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13852       << D.getCXXScopeSpec().getRange();
13853   }
13854 
13855   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13856   // simple identifier except [...irrelevant cases...].
13857   switch (D.getName().getKind()) {
13858   case UnqualifiedIdKind::IK_Identifier:
13859     break;
13860 
13861   case UnqualifiedIdKind::IK_OperatorFunctionId:
13862   case UnqualifiedIdKind::IK_ConversionFunctionId:
13863   case UnqualifiedIdKind::IK_LiteralOperatorId:
13864   case UnqualifiedIdKind::IK_ConstructorName:
13865   case UnqualifiedIdKind::IK_DestructorName:
13866   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13867   case UnqualifiedIdKind::IK_DeductionGuideName:
13868     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13869       << GetNameForDeclarator(D).getName();
13870     break;
13871 
13872   case UnqualifiedIdKind::IK_TemplateId:
13873   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13874     // GetNameForDeclarator would not produce a useful name in this case.
13875     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13876     break;
13877   }
13878 }
13879 
13880 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13881 /// to introduce parameters into function prototype scope.
13882 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13883   const DeclSpec &DS = D.getDeclSpec();
13884 
13885   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13886 
13887   // C++03 [dcl.stc]p2 also permits 'auto'.
13888   StorageClass SC = SC_None;
13889   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13890     SC = SC_Register;
13891     // In C++11, the 'register' storage class specifier is deprecated.
13892     // In C++17, it is not allowed, but we tolerate it as an extension.
13893     if (getLangOpts().CPlusPlus11) {
13894       Diag(DS.getStorageClassSpecLoc(),
13895            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13896                                      : diag::warn_deprecated_register)
13897         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13898     }
13899   } else if (getLangOpts().CPlusPlus &&
13900              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13901     SC = SC_Auto;
13902   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13903     Diag(DS.getStorageClassSpecLoc(),
13904          diag::err_invalid_storage_class_in_func_decl);
13905     D.getMutableDeclSpec().ClearStorageClassSpecs();
13906   }
13907 
13908   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13909     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13910       << DeclSpec::getSpecifierName(TSCS);
13911   if (DS.isInlineSpecified())
13912     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13913         << getLangOpts().CPlusPlus17;
13914   if (DS.hasConstexprSpecifier())
13915     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13916         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13917 
13918   DiagnoseFunctionSpecifiers(DS);
13919 
13920   CheckFunctionOrTemplateParamDeclarator(S, D);
13921 
13922   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13923   QualType parmDeclType = TInfo->getType();
13924 
13925   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13926   IdentifierInfo *II = D.getIdentifier();
13927   if (II) {
13928     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13929                    ForVisibleRedeclaration);
13930     LookupName(R, S);
13931     if (R.isSingleResult()) {
13932       NamedDecl *PrevDecl = R.getFoundDecl();
13933       if (PrevDecl->isTemplateParameter()) {
13934         // Maybe we will complain about the shadowed template parameter.
13935         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13936         // Just pretend that we didn't see the previous declaration.
13937         PrevDecl = nullptr;
13938       } else if (S->isDeclScope(PrevDecl)) {
13939         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13940         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13941 
13942         // Recover by removing the name
13943         II = nullptr;
13944         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13945         D.setInvalidType(true);
13946       }
13947     }
13948   }
13949 
13950   // Temporarily put parameter variables in the translation unit, not
13951   // the enclosing context.  This prevents them from accidentally
13952   // looking like class members in C++.
13953   ParmVarDecl *New =
13954       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13955                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13956 
13957   if (D.isInvalidType())
13958     New->setInvalidDecl();
13959 
13960   assert(S->isFunctionPrototypeScope());
13961   assert(S->getFunctionPrototypeDepth() >= 1);
13962   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13963                     S->getNextFunctionPrototypeIndex());
13964 
13965   // Add the parameter declaration into this scope.
13966   S->AddDecl(New);
13967   if (II)
13968     IdResolver.AddDecl(New);
13969 
13970   ProcessDeclAttributes(S, New, D);
13971 
13972   if (D.getDeclSpec().isModulePrivateSpecified())
13973     Diag(New->getLocation(), diag::err_module_private_local)
13974         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13975         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13976 
13977   if (New->hasAttr<BlocksAttr>()) {
13978     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13979   }
13980 
13981   if (getLangOpts().OpenCL)
13982     deduceOpenCLAddressSpace(New);
13983 
13984   return New;
13985 }
13986 
13987 /// Synthesizes a variable for a parameter arising from a
13988 /// typedef.
13989 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13990                                               SourceLocation Loc,
13991                                               QualType T) {
13992   /* FIXME: setting StartLoc == Loc.
13993      Would it be worth to modify callers so as to provide proper source
13994      location for the unnamed parameters, embedding the parameter's type? */
13995   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13996                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13997                                            SC_None, nullptr);
13998   Param->setImplicit();
13999   return Param;
14000 }
14001 
14002 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14003   // Don't diagnose unused-parameter errors in template instantiations; we
14004   // will already have done so in the template itself.
14005   if (inTemplateInstantiation())
14006     return;
14007 
14008   for (const ParmVarDecl *Parameter : Parameters) {
14009     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14010         !Parameter->hasAttr<UnusedAttr>()) {
14011       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14012         << Parameter->getDeclName();
14013     }
14014   }
14015 }
14016 
14017 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14018     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14019   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14020     return;
14021 
14022   // Warn if the return value is pass-by-value and larger than the specified
14023   // threshold.
14024   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14025     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14026     if (Size > LangOpts.NumLargeByValueCopy)
14027       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14028   }
14029 
14030   // Warn if any parameter is pass-by-value and larger than the specified
14031   // threshold.
14032   for (const ParmVarDecl *Parameter : Parameters) {
14033     QualType T = Parameter->getType();
14034     if (T->isDependentType() || !T.isPODType(Context))
14035       continue;
14036     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14037     if (Size > LangOpts.NumLargeByValueCopy)
14038       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14039           << Parameter << Size;
14040   }
14041 }
14042 
14043 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14044                                   SourceLocation NameLoc, IdentifierInfo *Name,
14045                                   QualType T, TypeSourceInfo *TSInfo,
14046                                   StorageClass SC) {
14047   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14048   if (getLangOpts().ObjCAutoRefCount &&
14049       T.getObjCLifetime() == Qualifiers::OCL_None &&
14050       T->isObjCLifetimeType()) {
14051 
14052     Qualifiers::ObjCLifetime lifetime;
14053 
14054     // Special cases for arrays:
14055     //   - if it's const, use __unsafe_unretained
14056     //   - otherwise, it's an error
14057     if (T->isArrayType()) {
14058       if (!T.isConstQualified()) {
14059         if (DelayedDiagnostics.shouldDelayDiagnostics())
14060           DelayedDiagnostics.add(
14061               sema::DelayedDiagnostic::makeForbiddenType(
14062               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14063         else
14064           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14065               << TSInfo->getTypeLoc().getSourceRange();
14066       }
14067       lifetime = Qualifiers::OCL_ExplicitNone;
14068     } else {
14069       lifetime = T->getObjCARCImplicitLifetime();
14070     }
14071     T = Context.getLifetimeQualifiedType(T, lifetime);
14072   }
14073 
14074   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14075                                          Context.getAdjustedParameterType(T),
14076                                          TSInfo, SC, nullptr);
14077 
14078   // Make a note if we created a new pack in the scope of a lambda, so that
14079   // we know that references to that pack must also be expanded within the
14080   // lambda scope.
14081   if (New->isParameterPack())
14082     if (auto *LSI = getEnclosingLambda())
14083       LSI->LocalPacks.push_back(New);
14084 
14085   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14086       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14087     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14088                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14089 
14090   // Parameters can not be abstract class types.
14091   // For record types, this is done by the AbstractClassUsageDiagnoser once
14092   // the class has been completely parsed.
14093   if (!CurContext->isRecord() &&
14094       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14095                              AbstractParamType))
14096     New->setInvalidDecl();
14097 
14098   // Parameter declarators cannot be interface types. All ObjC objects are
14099   // passed by reference.
14100   if (T->isObjCObjectType()) {
14101     SourceLocation TypeEndLoc =
14102         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14103     Diag(NameLoc,
14104          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14105       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14106     T = Context.getObjCObjectPointerType(T);
14107     New->setType(T);
14108   }
14109 
14110   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14111   // duration shall not be qualified by an address-space qualifier."
14112   // Since all parameters have automatic store duration, they can not have
14113   // an address space.
14114   if (T.getAddressSpace() != LangAS::Default &&
14115       // OpenCL allows function arguments declared to be an array of a type
14116       // to be qualified with an address space.
14117       !(getLangOpts().OpenCL &&
14118         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14119     Diag(NameLoc, diag::err_arg_with_address_space);
14120     New->setInvalidDecl();
14121   }
14122 
14123   // PPC MMA non-pointer types are not allowed as function argument types.
14124   if (Context.getTargetInfo().getTriple().isPPC64() &&
14125       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14126     New->setInvalidDecl();
14127   }
14128 
14129   return New;
14130 }
14131 
14132 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14133                                            SourceLocation LocAfterDecls) {
14134   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14135 
14136   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14137   // for a K&R function.
14138   if (!FTI.hasPrototype) {
14139     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14140       --i;
14141       if (FTI.Params[i].Param == nullptr) {
14142         SmallString<256> Code;
14143         llvm::raw_svector_ostream(Code)
14144             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14145         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14146             << FTI.Params[i].Ident
14147             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14148 
14149         // Implicitly declare the argument as type 'int' for lack of a better
14150         // type.
14151         AttributeFactory attrs;
14152         DeclSpec DS(attrs);
14153         const char* PrevSpec; // unused
14154         unsigned DiagID; // unused
14155         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14156                            DiagID, Context.getPrintingPolicy());
14157         // Use the identifier location for the type source range.
14158         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14159         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14160         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14161         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14162         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14163       }
14164     }
14165   }
14166 }
14167 
14168 Decl *
14169 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14170                               MultiTemplateParamsArg TemplateParameterLists,
14171                               SkipBodyInfo *SkipBody) {
14172   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14173   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14174   Scope *ParentScope = FnBodyScope->getParent();
14175 
14176   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14177   // we define a non-templated function definition, we will create a declaration
14178   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14179   // The base function declaration will have the equivalent of an `omp declare
14180   // variant` annotation which specifies the mangled definition as a
14181   // specialization function under the OpenMP context defined as part of the
14182   // `omp begin declare variant`.
14183   SmallVector<FunctionDecl *, 4> Bases;
14184   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14185     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14186         ParentScope, D, TemplateParameterLists, Bases);
14187 
14188   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14189   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14190   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14191 
14192   if (!Bases.empty())
14193     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14194 
14195   return Dcl;
14196 }
14197 
14198 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14199   Consumer.HandleInlineFunctionDefinition(D);
14200 }
14201 
14202 static bool
14203 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14204                                 const FunctionDecl *&PossiblePrototype) {
14205   // Don't warn about invalid declarations.
14206   if (FD->isInvalidDecl())
14207     return false;
14208 
14209   // Or declarations that aren't global.
14210   if (!FD->isGlobal())
14211     return false;
14212 
14213   // Don't warn about C++ member functions.
14214   if (isa<CXXMethodDecl>(FD))
14215     return false;
14216 
14217   // Don't warn about 'main'.
14218   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14219     if (IdentifierInfo *II = FD->getIdentifier())
14220       if (II->isStr("main") || II->isStr("efi_main"))
14221         return false;
14222 
14223   // Don't warn about inline functions.
14224   if (FD->isInlined())
14225     return false;
14226 
14227   // Don't warn about function templates.
14228   if (FD->getDescribedFunctionTemplate())
14229     return false;
14230 
14231   // Don't warn about function template specializations.
14232   if (FD->isFunctionTemplateSpecialization())
14233     return false;
14234 
14235   // Don't warn for OpenCL kernels.
14236   if (FD->hasAttr<OpenCLKernelAttr>())
14237     return false;
14238 
14239   // Don't warn on explicitly deleted functions.
14240   if (FD->isDeleted())
14241     return false;
14242 
14243   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14244        Prev; Prev = Prev->getPreviousDecl()) {
14245     // Ignore any declarations that occur in function or method
14246     // scope, because they aren't visible from the header.
14247     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14248       continue;
14249 
14250     PossiblePrototype = Prev;
14251     return Prev->getType()->isFunctionNoProtoType();
14252   }
14253 
14254   return true;
14255 }
14256 
14257 void
14258 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14259                                    const FunctionDecl *EffectiveDefinition,
14260                                    SkipBodyInfo *SkipBody) {
14261   const FunctionDecl *Definition = EffectiveDefinition;
14262   if (!Definition &&
14263       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14264     return;
14265 
14266   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14267     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14268       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14269         // A merged copy of the same function, instantiated as a member of
14270         // the same class, is OK.
14271         if (declaresSameEntity(OrigFD, OrigDef) &&
14272             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14273                                cast<Decl>(FD->getLexicalDeclContext())))
14274           return;
14275       }
14276     }
14277   }
14278 
14279   if (canRedefineFunction(Definition, getLangOpts()))
14280     return;
14281 
14282   // Don't emit an error when this is redefinition of a typo-corrected
14283   // definition.
14284   if (TypoCorrectedFunctionDefinitions.count(Definition))
14285     return;
14286 
14287   // If we don't have a visible definition of the function, and it's inline or
14288   // a template, skip the new definition.
14289   if (SkipBody && !hasVisibleDefinition(Definition) &&
14290       (Definition->getFormalLinkage() == InternalLinkage ||
14291        Definition->isInlined() ||
14292        Definition->getDescribedFunctionTemplate() ||
14293        Definition->getNumTemplateParameterLists())) {
14294     SkipBody->ShouldSkip = true;
14295     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14296     if (auto *TD = Definition->getDescribedFunctionTemplate())
14297       makeMergedDefinitionVisible(TD);
14298     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14299     return;
14300   }
14301 
14302   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14303       Definition->getStorageClass() == SC_Extern)
14304     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14305         << FD << getLangOpts().CPlusPlus;
14306   else
14307     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14308 
14309   Diag(Definition->getLocation(), diag::note_previous_definition);
14310   FD->setInvalidDecl();
14311 }
14312 
14313 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14314                                    Sema &S) {
14315   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14316 
14317   LambdaScopeInfo *LSI = S.PushLambdaScope();
14318   LSI->CallOperator = CallOperator;
14319   LSI->Lambda = LambdaClass;
14320   LSI->ReturnType = CallOperator->getReturnType();
14321   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14322 
14323   if (LCD == LCD_None)
14324     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14325   else if (LCD == LCD_ByCopy)
14326     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14327   else if (LCD == LCD_ByRef)
14328     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14329   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14330 
14331   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14332   LSI->Mutable = !CallOperator->isConst();
14333 
14334   // Add the captures to the LSI so they can be noted as already
14335   // captured within tryCaptureVar.
14336   auto I = LambdaClass->field_begin();
14337   for (const auto &C : LambdaClass->captures()) {
14338     if (C.capturesVariable()) {
14339       VarDecl *VD = C.getCapturedVar();
14340       if (VD->isInitCapture())
14341         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14342       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14343       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14344           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14345           /*EllipsisLoc*/C.isPackExpansion()
14346                          ? C.getEllipsisLoc() : SourceLocation(),
14347           I->getType(), /*Invalid*/false);
14348 
14349     } else if (C.capturesThis()) {
14350       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14351                           C.getCaptureKind() == LCK_StarThis);
14352     } else {
14353       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14354                              I->getType());
14355     }
14356     ++I;
14357   }
14358 }
14359 
14360 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14361                                     SkipBodyInfo *SkipBody) {
14362   if (!D) {
14363     // Parsing the function declaration failed in some way. Push on a fake scope
14364     // anyway so we can try to parse the function body.
14365     PushFunctionScope();
14366     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14367     return D;
14368   }
14369 
14370   FunctionDecl *FD = nullptr;
14371 
14372   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14373     FD = FunTmpl->getTemplatedDecl();
14374   else
14375     FD = cast<FunctionDecl>(D);
14376 
14377   // Do not push if it is a lambda because one is already pushed when building
14378   // the lambda in ActOnStartOfLambdaDefinition().
14379   if (!isLambdaCallOperator(FD))
14380     PushExpressionEvaluationContext(
14381         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14382                           : ExprEvalContexts.back().Context);
14383 
14384   // Check for defining attributes before the check for redefinition.
14385   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14386     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14387     FD->dropAttr<AliasAttr>();
14388     FD->setInvalidDecl();
14389   }
14390   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14391     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14392     FD->dropAttr<IFuncAttr>();
14393     FD->setInvalidDecl();
14394   }
14395 
14396   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14397     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14398         Ctor->isDefaultConstructor() &&
14399         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14400       // If this is an MS ABI dllexport default constructor, instantiate any
14401       // default arguments.
14402       InstantiateDefaultCtorDefaultArgs(Ctor);
14403     }
14404   }
14405 
14406   // See if this is a redefinition. If 'will have body' (or similar) is already
14407   // set, then these checks were already performed when it was set.
14408   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14409       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14410     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14411 
14412     // If we're skipping the body, we're done. Don't enter the scope.
14413     if (SkipBody && SkipBody->ShouldSkip)
14414       return D;
14415   }
14416 
14417   // Mark this function as "will have a body eventually".  This lets users to
14418   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14419   // this function.
14420   FD->setWillHaveBody();
14421 
14422   // If we are instantiating a generic lambda call operator, push
14423   // a LambdaScopeInfo onto the function stack.  But use the information
14424   // that's already been calculated (ActOnLambdaExpr) to prime the current
14425   // LambdaScopeInfo.
14426   // When the template operator is being specialized, the LambdaScopeInfo,
14427   // has to be properly restored so that tryCaptureVariable doesn't try
14428   // and capture any new variables. In addition when calculating potential
14429   // captures during transformation of nested lambdas, it is necessary to
14430   // have the LSI properly restored.
14431   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14432     assert(inTemplateInstantiation() &&
14433            "There should be an active template instantiation on the stack "
14434            "when instantiating a generic lambda!");
14435     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14436   } else {
14437     // Enter a new function scope
14438     PushFunctionScope();
14439   }
14440 
14441   // Builtin functions cannot be defined.
14442   if (unsigned BuiltinID = FD->getBuiltinID()) {
14443     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14444         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14445       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14446       FD->setInvalidDecl();
14447     }
14448   }
14449 
14450   // The return type of a function definition must be complete
14451   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14452   QualType ResultType = FD->getReturnType();
14453   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14454       !FD->isInvalidDecl() &&
14455       RequireCompleteType(FD->getLocation(), ResultType,
14456                           diag::err_func_def_incomplete_result))
14457     FD->setInvalidDecl();
14458 
14459   if (FnBodyScope)
14460     PushDeclContext(FnBodyScope, FD);
14461 
14462   // Check the validity of our function parameters
14463   CheckParmsForFunctionDef(FD->parameters(),
14464                            /*CheckParameterNames=*/true);
14465 
14466   // Add non-parameter declarations already in the function to the current
14467   // scope.
14468   if (FnBodyScope) {
14469     for (Decl *NPD : FD->decls()) {
14470       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14471       if (!NonParmDecl)
14472         continue;
14473       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14474              "parameters should not be in newly created FD yet");
14475 
14476       // If the decl has a name, make it accessible in the current scope.
14477       if (NonParmDecl->getDeclName())
14478         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14479 
14480       // Similarly, dive into enums and fish their constants out, making them
14481       // accessible in this scope.
14482       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14483         for (auto *EI : ED->enumerators())
14484           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14485       }
14486     }
14487   }
14488 
14489   // Introduce our parameters into the function scope
14490   for (auto Param : FD->parameters()) {
14491     Param->setOwningFunction(FD);
14492 
14493     // If this has an identifier, add it to the scope stack.
14494     if (Param->getIdentifier() && FnBodyScope) {
14495       CheckShadow(FnBodyScope, Param);
14496 
14497       PushOnScopeChains(Param, FnBodyScope);
14498     }
14499   }
14500 
14501   // Ensure that the function's exception specification is instantiated.
14502   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14503     ResolveExceptionSpec(D->getLocation(), FPT);
14504 
14505   // dllimport cannot be applied to non-inline function definitions.
14506   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14507       !FD->isTemplateInstantiation()) {
14508     assert(!FD->hasAttr<DLLExportAttr>());
14509     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14510     FD->setInvalidDecl();
14511     return D;
14512   }
14513   // We want to attach documentation to original Decl (which might be
14514   // a function template).
14515   ActOnDocumentableDecl(D);
14516   if (getCurLexicalContext()->isObjCContainer() &&
14517       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14518       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14519     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14520 
14521   return D;
14522 }
14523 
14524 /// Given the set of return statements within a function body,
14525 /// compute the variables that are subject to the named return value
14526 /// optimization.
14527 ///
14528 /// Each of the variables that is subject to the named return value
14529 /// optimization will be marked as NRVO variables in the AST, and any
14530 /// return statement that has a marked NRVO variable as its NRVO candidate can
14531 /// use the named return value optimization.
14532 ///
14533 /// This function applies a very simplistic algorithm for NRVO: if every return
14534 /// statement in the scope of a variable has the same NRVO candidate, that
14535 /// candidate is an NRVO variable.
14536 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14537   ReturnStmt **Returns = Scope->Returns.data();
14538 
14539   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14540     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14541       if (!NRVOCandidate->isNRVOVariable())
14542         Returns[I]->setNRVOCandidate(nullptr);
14543     }
14544   }
14545 }
14546 
14547 bool Sema::canDelayFunctionBody(const Declarator &D) {
14548   // We can't delay parsing the body of a constexpr function template (yet).
14549   if (D.getDeclSpec().hasConstexprSpecifier())
14550     return false;
14551 
14552   // We can't delay parsing the body of a function template with a deduced
14553   // return type (yet).
14554   if (D.getDeclSpec().hasAutoTypeSpec()) {
14555     // If the placeholder introduces a non-deduced trailing return type,
14556     // we can still delay parsing it.
14557     if (D.getNumTypeObjects()) {
14558       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14559       if (Outer.Kind == DeclaratorChunk::Function &&
14560           Outer.Fun.hasTrailingReturnType()) {
14561         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14562         return Ty.isNull() || !Ty->isUndeducedType();
14563       }
14564     }
14565     return false;
14566   }
14567 
14568   return true;
14569 }
14570 
14571 bool Sema::canSkipFunctionBody(Decl *D) {
14572   // We cannot skip the body of a function (or function template) which is
14573   // constexpr, since we may need to evaluate its body in order to parse the
14574   // rest of the file.
14575   // We cannot skip the body of a function with an undeduced return type,
14576   // because any callers of that function need to know the type.
14577   if (const FunctionDecl *FD = D->getAsFunction()) {
14578     if (FD->isConstexpr())
14579       return false;
14580     // We can't simply call Type::isUndeducedType here, because inside template
14581     // auto can be deduced to a dependent type, which is not considered
14582     // "undeduced".
14583     if (FD->getReturnType()->getContainedDeducedType())
14584       return false;
14585   }
14586   return Consumer.shouldSkipFunctionBody(D);
14587 }
14588 
14589 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14590   if (!Decl)
14591     return nullptr;
14592   if (FunctionDecl *FD = Decl->getAsFunction())
14593     FD->setHasSkippedBody();
14594   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14595     MD->setHasSkippedBody();
14596   return Decl;
14597 }
14598 
14599 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14600   return ActOnFinishFunctionBody(D, BodyArg, false);
14601 }
14602 
14603 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14604 /// body.
14605 class ExitFunctionBodyRAII {
14606 public:
14607   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14608   ~ExitFunctionBodyRAII() {
14609     if (!IsLambda)
14610       S.PopExpressionEvaluationContext();
14611   }
14612 
14613 private:
14614   Sema &S;
14615   bool IsLambda = false;
14616 };
14617 
14618 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14619   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14620 
14621   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14622     if (EscapeInfo.count(BD))
14623       return EscapeInfo[BD];
14624 
14625     bool R = false;
14626     const BlockDecl *CurBD = BD;
14627 
14628     do {
14629       R = !CurBD->doesNotEscape();
14630       if (R)
14631         break;
14632       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14633     } while (CurBD);
14634 
14635     return EscapeInfo[BD] = R;
14636   };
14637 
14638   // If the location where 'self' is implicitly retained is inside a escaping
14639   // block, emit a diagnostic.
14640   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14641        S.ImplicitlyRetainedSelfLocs)
14642     if (IsOrNestedInEscapingBlock(P.second))
14643       S.Diag(P.first, diag::warn_implicitly_retains_self)
14644           << FixItHint::CreateInsertion(P.first, "self->");
14645 }
14646 
14647 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14648                                     bool IsInstantiation) {
14649   FunctionScopeInfo *FSI = getCurFunction();
14650   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14651 
14652   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14653     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14654 
14655   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14656   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14657 
14658   if (getLangOpts().Coroutines && FSI->isCoroutine())
14659     CheckCompletedCoroutineBody(FD, Body);
14660 
14661   {
14662     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14663     // one is already popped when finishing the lambda in BuildLambdaExpr().
14664     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14665     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14666 
14667     if (FD) {
14668       FD->setBody(Body);
14669       FD->setWillHaveBody(false);
14670 
14671       if (getLangOpts().CPlusPlus14) {
14672         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14673             FD->getReturnType()->isUndeducedType()) {
14674           // For a function with a deduced result type to return void,
14675           // the result type as written must be 'auto' or 'decltype(auto)',
14676           // possibly cv-qualified or constrained, but not ref-qualified.
14677           if (!FD->getReturnType()->getAs<AutoType>()) {
14678             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14679                 << FD->getReturnType();
14680             FD->setInvalidDecl();
14681           } else {
14682             // Falling off the end of the function is the same as 'return;'.
14683             Expr *Dummy = nullptr;
14684             if (DeduceFunctionTypeFromReturnExpr(
14685                     FD, dcl->getLocation(), Dummy,
14686                     FD->getReturnType()->getAs<AutoType>()))
14687               FD->setInvalidDecl();
14688           }
14689         }
14690       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14691         // In C++11, we don't use 'auto' deduction rules for lambda call
14692         // operators because we don't support return type deduction.
14693         auto *LSI = getCurLambda();
14694         if (LSI->HasImplicitReturnType) {
14695           deduceClosureReturnType(*LSI);
14696 
14697           // C++11 [expr.prim.lambda]p4:
14698           //   [...] if there are no return statements in the compound-statement
14699           //   [the deduced type is] the type void
14700           QualType RetType =
14701               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14702 
14703           // Update the return type to the deduced type.
14704           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14705           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14706                                               Proto->getExtProtoInfo()));
14707         }
14708       }
14709 
14710       // If the function implicitly returns zero (like 'main') or is naked,
14711       // don't complain about missing return statements.
14712       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14713         WP.disableCheckFallThrough();
14714 
14715       // MSVC permits the use of pure specifier (=0) on function definition,
14716       // defined at class scope, warn about this non-standard construct.
14717       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14718         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14719 
14720       if (!FD->isInvalidDecl()) {
14721         // Don't diagnose unused parameters of defaulted, deleted or naked
14722         // functions.
14723         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14724             !FD->hasAttr<NakedAttr>())
14725           DiagnoseUnusedParameters(FD->parameters());
14726         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14727                                                FD->getReturnType(), FD);
14728 
14729         // If this is a structor, we need a vtable.
14730         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14731           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14732         else if (CXXDestructorDecl *Destructor =
14733                      dyn_cast<CXXDestructorDecl>(FD))
14734           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14735 
14736         // Try to apply the named return value optimization. We have to check
14737         // if we can do this here because lambdas keep return statements around
14738         // to deduce an implicit return type.
14739         if (FD->getReturnType()->isRecordType() &&
14740             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14741           computeNRVO(Body, FSI);
14742       }
14743 
14744       // GNU warning -Wmissing-prototypes:
14745       //   Warn if a global function is defined without a previous
14746       //   prototype declaration. This warning is issued even if the
14747       //   definition itself provides a prototype. The aim is to detect
14748       //   global functions that fail to be declared in header files.
14749       const FunctionDecl *PossiblePrototype = nullptr;
14750       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14751         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14752 
14753         if (PossiblePrototype) {
14754           // We found a declaration that is not a prototype,
14755           // but that could be a zero-parameter prototype
14756           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14757             TypeLoc TL = TI->getTypeLoc();
14758             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14759               Diag(PossiblePrototype->getLocation(),
14760                    diag::note_declaration_not_a_prototype)
14761                   << (FD->getNumParams() != 0)
14762                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14763                                                     FTL.getRParenLoc(), "void")
14764                                               : FixItHint{});
14765           }
14766         } else {
14767           // Returns true if the token beginning at this Loc is `const`.
14768           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14769                                   const LangOptions &LangOpts) {
14770             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14771             if (LocInfo.first.isInvalid())
14772               return false;
14773 
14774             bool Invalid = false;
14775             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14776             if (Invalid)
14777               return false;
14778 
14779             if (LocInfo.second > Buffer.size())
14780               return false;
14781 
14782             const char *LexStart = Buffer.data() + LocInfo.second;
14783             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14784 
14785             return StartTok.consume_front("const") &&
14786                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14787                     StartTok.startswith("/*") || StartTok.startswith("//"));
14788           };
14789 
14790           auto findBeginLoc = [&]() {
14791             // If the return type has `const` qualifier, we want to insert
14792             // `static` before `const` (and not before the typename).
14793             if ((FD->getReturnType()->isAnyPointerType() &&
14794                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14795                 FD->getReturnType().isConstQualified()) {
14796               // But only do this if we can determine where the `const` is.
14797 
14798               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14799                                getLangOpts()))
14800 
14801                 return FD->getBeginLoc();
14802             }
14803             return FD->getTypeSpecStartLoc();
14804           };
14805           Diag(FD->getTypeSpecStartLoc(),
14806                diag::note_static_for_internal_linkage)
14807               << /* function */ 1
14808               << (FD->getStorageClass() == SC_None
14809                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14810                       : FixItHint{});
14811         }
14812 
14813         // GNU warning -Wstrict-prototypes
14814         //   Warn if K&R function is defined without a previous declaration.
14815         //   This warning is issued only if the definition itself does not
14816         //   provide a prototype. Only K&R definitions do not provide a
14817         //   prototype.
14818         if (!FD->hasWrittenPrototype()) {
14819           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14820           TypeLoc TL = TI->getTypeLoc();
14821           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14822           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14823         }
14824       }
14825 
14826       // Warn on CPUDispatch with an actual body.
14827       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14828         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14829           if (!CmpndBody->body_empty())
14830             Diag(CmpndBody->body_front()->getBeginLoc(),
14831                  diag::warn_dispatch_body_ignored);
14832 
14833       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14834         const CXXMethodDecl *KeyFunction;
14835         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14836             MD->isVirtual() &&
14837             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14838             MD == KeyFunction->getCanonicalDecl()) {
14839           // Update the key-function state if necessary for this ABI.
14840           if (FD->isInlined() &&
14841               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14842             Context.setNonKeyFunction(MD);
14843 
14844             // If the newly-chosen key function is already defined, then we
14845             // need to mark the vtable as used retroactively.
14846             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14847             const FunctionDecl *Definition;
14848             if (KeyFunction && KeyFunction->isDefined(Definition))
14849               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14850           } else {
14851             // We just defined they key function; mark the vtable as used.
14852             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14853           }
14854         }
14855       }
14856 
14857       assert(
14858           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14859           "Function parsing confused");
14860     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14861       assert(MD == getCurMethodDecl() && "Method parsing confused");
14862       MD->setBody(Body);
14863       if (!MD->isInvalidDecl()) {
14864         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14865                                                MD->getReturnType(), MD);
14866 
14867         if (Body)
14868           computeNRVO(Body, FSI);
14869       }
14870       if (FSI->ObjCShouldCallSuper) {
14871         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14872             << MD->getSelector().getAsString();
14873         FSI->ObjCShouldCallSuper = false;
14874       }
14875       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14876         const ObjCMethodDecl *InitMethod = nullptr;
14877         bool isDesignated =
14878             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14879         assert(isDesignated && InitMethod);
14880         (void)isDesignated;
14881 
14882         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14883           auto IFace = MD->getClassInterface();
14884           if (!IFace)
14885             return false;
14886           auto SuperD = IFace->getSuperClass();
14887           if (!SuperD)
14888             return false;
14889           return SuperD->getIdentifier() ==
14890                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14891         };
14892         // Don't issue this warning for unavailable inits or direct subclasses
14893         // of NSObject.
14894         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14895           Diag(MD->getLocation(),
14896                diag::warn_objc_designated_init_missing_super_call);
14897           Diag(InitMethod->getLocation(),
14898                diag::note_objc_designated_init_marked_here);
14899         }
14900         FSI->ObjCWarnForNoDesignatedInitChain = false;
14901       }
14902       if (FSI->ObjCWarnForNoInitDelegation) {
14903         // Don't issue this warning for unavaialable inits.
14904         if (!MD->isUnavailable())
14905           Diag(MD->getLocation(),
14906                diag::warn_objc_secondary_init_missing_init_call);
14907         FSI->ObjCWarnForNoInitDelegation = false;
14908       }
14909 
14910       diagnoseImplicitlyRetainedSelf(*this);
14911     } else {
14912       // Parsing the function declaration failed in some way. Pop the fake scope
14913       // we pushed on.
14914       PopFunctionScopeInfo(ActivePolicy, dcl);
14915       return nullptr;
14916     }
14917 
14918     if (Body && FSI->HasPotentialAvailabilityViolations)
14919       DiagnoseUnguardedAvailabilityViolations(dcl);
14920 
14921     assert(!FSI->ObjCShouldCallSuper &&
14922            "This should only be set for ObjC methods, which should have been "
14923            "handled in the block above.");
14924 
14925     // Verify and clean out per-function state.
14926     if (Body && (!FD || !FD->isDefaulted())) {
14927       // C++ constructors that have function-try-blocks can't have return
14928       // statements in the handlers of that block. (C++ [except.handle]p14)
14929       // Verify this.
14930       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14931         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14932 
14933       // Verify that gotos and switch cases don't jump into scopes illegally.
14934       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14935         DiagnoseInvalidJumps(Body);
14936 
14937       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14938         if (!Destructor->getParent()->isDependentType())
14939           CheckDestructor(Destructor);
14940 
14941         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14942                                                Destructor->getParent());
14943       }
14944 
14945       // If any errors have occurred, clear out any temporaries that may have
14946       // been leftover. This ensures that these temporaries won't be picked up
14947       // for deletion in some later function.
14948       if (hasUncompilableErrorOccurred() ||
14949           getDiagnostics().getSuppressAllDiagnostics()) {
14950         DiscardCleanupsInEvaluationContext();
14951       }
14952       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14953         // Since the body is valid, issue any analysis-based warnings that are
14954         // enabled.
14955         ActivePolicy = &WP;
14956       }
14957 
14958       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14959           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14960         FD->setInvalidDecl();
14961 
14962       if (FD && FD->hasAttr<NakedAttr>()) {
14963         for (const Stmt *S : Body->children()) {
14964           // Allow local register variables without initializer as they don't
14965           // require prologue.
14966           bool RegisterVariables = false;
14967           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14968             for (const auto *Decl : DS->decls()) {
14969               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14970                 RegisterVariables =
14971                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14972                 if (!RegisterVariables)
14973                   break;
14974               }
14975             }
14976           }
14977           if (RegisterVariables)
14978             continue;
14979           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14980             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14981             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14982             FD->setInvalidDecl();
14983             break;
14984           }
14985         }
14986       }
14987 
14988       assert(ExprCleanupObjects.size() ==
14989                  ExprEvalContexts.back().NumCleanupObjects &&
14990              "Leftover temporaries in function");
14991       assert(!Cleanup.exprNeedsCleanups() &&
14992              "Unaccounted cleanups in function");
14993       assert(MaybeODRUseExprs.empty() &&
14994              "Leftover expressions for odr-use checking");
14995     }
14996   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
14997     // the declaration context below. Otherwise, we're unable to transform
14998     // 'this' expressions when transforming immediate context functions.
14999 
15000   if (!IsInstantiation)
15001     PopDeclContext();
15002 
15003   PopFunctionScopeInfo(ActivePolicy, dcl);
15004   // If any errors have occurred, clear out any temporaries that may have
15005   // been leftover. This ensures that these temporaries won't be picked up for
15006   // deletion in some later function.
15007   if (hasUncompilableErrorOccurred()) {
15008     DiscardCleanupsInEvaluationContext();
15009   }
15010 
15011   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15012                                   !LangOpts.OMPTargetTriples.empty())) ||
15013              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15014     auto ES = getEmissionStatus(FD);
15015     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15016         ES == Sema::FunctionEmissionStatus::Unknown)
15017       DeclsToCheckForDeferredDiags.insert(FD);
15018   }
15019 
15020   if (FD && !FD->isDeleted())
15021     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15022 
15023   return dcl;
15024 }
15025 
15026 /// When we finish delayed parsing of an attribute, we must attach it to the
15027 /// relevant Decl.
15028 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15029                                        ParsedAttributes &Attrs) {
15030   // Always attach attributes to the underlying decl.
15031   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15032     D = TD->getTemplatedDecl();
15033   ProcessDeclAttributeList(S, D, Attrs);
15034 
15035   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15036     if (Method->isStatic())
15037       checkThisInStaticMemberFunctionAttributes(Method);
15038 }
15039 
15040 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15041 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15042 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15043                                           IdentifierInfo &II, Scope *S) {
15044   // Find the scope in which the identifier is injected and the corresponding
15045   // DeclContext.
15046   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15047   // In that case, we inject the declaration into the translation unit scope
15048   // instead.
15049   Scope *BlockScope = S;
15050   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15051     BlockScope = BlockScope->getParent();
15052 
15053   Scope *ContextScope = BlockScope;
15054   while (!ContextScope->getEntity())
15055     ContextScope = ContextScope->getParent();
15056   ContextRAII SavedContext(*this, ContextScope->getEntity());
15057 
15058   // Before we produce a declaration for an implicitly defined
15059   // function, see whether there was a locally-scoped declaration of
15060   // this name as a function or variable. If so, use that
15061   // (non-visible) declaration, and complain about it.
15062   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15063   if (ExternCPrev) {
15064     // We still need to inject the function into the enclosing block scope so
15065     // that later (non-call) uses can see it.
15066     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15067 
15068     // C89 footnote 38:
15069     //   If in fact it is not defined as having type "function returning int",
15070     //   the behavior is undefined.
15071     if (!isa<FunctionDecl>(ExternCPrev) ||
15072         !Context.typesAreCompatible(
15073             cast<FunctionDecl>(ExternCPrev)->getType(),
15074             Context.getFunctionNoProtoType(Context.IntTy))) {
15075       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15076           << ExternCPrev << !getLangOpts().C99;
15077       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15078       return ExternCPrev;
15079     }
15080   }
15081 
15082   // Extension in C99.  Legal in C90, but warn about it.
15083   unsigned diag_id;
15084   if (II.getName().startswith("__builtin_"))
15085     diag_id = diag::warn_builtin_unknown;
15086   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15087   else if (getLangOpts().OpenCL)
15088     diag_id = diag::err_opencl_implicit_function_decl;
15089   else if (getLangOpts().C99)
15090     diag_id = diag::ext_implicit_function_decl;
15091   else
15092     diag_id = diag::warn_implicit_function_decl;
15093 
15094   TypoCorrection Corrected;
15095   // Because typo correction is expensive, only do it if the implicit
15096   // function declaration is going to be treated as an error.
15097   //
15098   // Perform the corection before issuing the main diagnostic, as some consumers
15099   // use typo-correction callbacks to enhance the main diagnostic.
15100   if (S && !ExternCPrev &&
15101       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15102     DeclFilterCCC<FunctionDecl> CCC{};
15103     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15104                             S, nullptr, CCC, CTK_NonError);
15105   }
15106 
15107   Diag(Loc, diag_id) << &II;
15108   if (Corrected)
15109     diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15110                  /*ErrorRecovery*/ false);
15111 
15112   // If we found a prior declaration of this function, don't bother building
15113   // another one. We've already pushed that one into scope, so there's nothing
15114   // more to do.
15115   if (ExternCPrev)
15116     return ExternCPrev;
15117 
15118   // Set a Declarator for the implicit definition: int foo();
15119   const char *Dummy;
15120   AttributeFactory attrFactory;
15121   DeclSpec DS(attrFactory);
15122   unsigned DiagID;
15123   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15124                                   Context.getPrintingPolicy());
15125   (void)Error; // Silence warning.
15126   assert(!Error && "Error setting up implicit decl!");
15127   SourceLocation NoLoc;
15128   Declarator D(DS, DeclaratorContext::Block);
15129   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15130                                              /*IsAmbiguous=*/false,
15131                                              /*LParenLoc=*/NoLoc,
15132                                              /*Params=*/nullptr,
15133                                              /*NumParams=*/0,
15134                                              /*EllipsisLoc=*/NoLoc,
15135                                              /*RParenLoc=*/NoLoc,
15136                                              /*RefQualifierIsLvalueRef=*/true,
15137                                              /*RefQualifierLoc=*/NoLoc,
15138                                              /*MutableLoc=*/NoLoc, EST_None,
15139                                              /*ESpecRange=*/SourceRange(),
15140                                              /*Exceptions=*/nullptr,
15141                                              /*ExceptionRanges=*/nullptr,
15142                                              /*NumExceptions=*/0,
15143                                              /*NoexceptExpr=*/nullptr,
15144                                              /*ExceptionSpecTokens=*/nullptr,
15145                                              /*DeclsInPrototype=*/None, Loc,
15146                                              Loc, D),
15147                 std::move(DS.getAttributes()), SourceLocation());
15148   D.SetIdentifier(&II, Loc);
15149 
15150   // Insert this function into the enclosing block scope.
15151   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15152   FD->setImplicit();
15153 
15154   AddKnownFunctionAttributes(FD);
15155 
15156   return FD;
15157 }
15158 
15159 /// If this function is a C++ replaceable global allocation function
15160 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15161 /// adds any function attributes that we know a priori based on the standard.
15162 ///
15163 /// We need to check for duplicate attributes both here and where user-written
15164 /// attributes are applied to declarations.
15165 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15166     FunctionDecl *FD) {
15167   if (FD->isInvalidDecl())
15168     return;
15169 
15170   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15171       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15172     return;
15173 
15174   Optional<unsigned> AlignmentParam;
15175   bool IsNothrow = false;
15176   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15177     return;
15178 
15179   // C++2a [basic.stc.dynamic.allocation]p4:
15180   //   An allocation function that has a non-throwing exception specification
15181   //   indicates failure by returning a null pointer value. Any other allocation
15182   //   function never returns a null pointer value and indicates failure only by
15183   //   throwing an exception [...]
15184   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15185     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15186 
15187   // C++2a [basic.stc.dynamic.allocation]p2:
15188   //   An allocation function attempts to allocate the requested amount of
15189   //   storage. [...] If the request succeeds, the value returned by a
15190   //   replaceable allocation function is a [...] pointer value p0 different
15191   //   from any previously returned value p1 [...]
15192   //
15193   // However, this particular information is being added in codegen,
15194   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15195 
15196   // C++2a [basic.stc.dynamic.allocation]p2:
15197   //   An allocation function attempts to allocate the requested amount of
15198   //   storage. If it is successful, it returns the address of the start of a
15199   //   block of storage whose length in bytes is at least as large as the
15200   //   requested size.
15201   if (!FD->hasAttr<AllocSizeAttr>()) {
15202     FD->addAttr(AllocSizeAttr::CreateImplicit(
15203         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15204         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15205   }
15206 
15207   // C++2a [basic.stc.dynamic.allocation]p3:
15208   //   For an allocation function [...], the pointer returned on a successful
15209   //   call shall represent the address of storage that is aligned as follows:
15210   //   (3.1) If the allocation function takes an argument of type
15211   //         std​::​align_­val_­t, the storage will have the alignment
15212   //         specified by the value of this argument.
15213   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15214     FD->addAttr(AllocAlignAttr::CreateImplicit(
15215         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15216   }
15217 
15218   // FIXME:
15219   // C++2a [basic.stc.dynamic.allocation]p3:
15220   //   For an allocation function [...], the pointer returned on a successful
15221   //   call shall represent the address of storage that is aligned as follows:
15222   //   (3.2) Otherwise, if the allocation function is named operator new[],
15223   //         the storage is aligned for any object that does not have
15224   //         new-extended alignment ([basic.align]) and is no larger than the
15225   //         requested size.
15226   //   (3.3) Otherwise, the storage is aligned for any object that does not
15227   //         have new-extended alignment and is of the requested size.
15228 }
15229 
15230 /// Adds any function attributes that we know a priori based on
15231 /// the declaration of this function.
15232 ///
15233 /// These attributes can apply both to implicitly-declared builtins
15234 /// (like __builtin___printf_chk) or to library-declared functions
15235 /// like NSLog or printf.
15236 ///
15237 /// We need to check for duplicate attributes both here and where user-written
15238 /// attributes are applied to declarations.
15239 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15240   if (FD->isInvalidDecl())
15241     return;
15242 
15243   // If this is a built-in function, map its builtin attributes to
15244   // actual attributes.
15245   if (unsigned BuiltinID = FD->getBuiltinID()) {
15246     // Handle printf-formatting attributes.
15247     unsigned FormatIdx;
15248     bool HasVAListArg;
15249     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15250       if (!FD->hasAttr<FormatAttr>()) {
15251         const char *fmt = "printf";
15252         unsigned int NumParams = FD->getNumParams();
15253         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15254             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15255           fmt = "NSString";
15256         FD->addAttr(FormatAttr::CreateImplicit(Context,
15257                                                &Context.Idents.get(fmt),
15258                                                FormatIdx+1,
15259                                                HasVAListArg ? 0 : FormatIdx+2,
15260                                                FD->getLocation()));
15261       }
15262     }
15263     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15264                                              HasVAListArg)) {
15265      if (!FD->hasAttr<FormatAttr>())
15266        FD->addAttr(FormatAttr::CreateImplicit(Context,
15267                                               &Context.Idents.get("scanf"),
15268                                               FormatIdx+1,
15269                                               HasVAListArg ? 0 : FormatIdx+2,
15270                                               FD->getLocation()));
15271     }
15272 
15273     // Handle automatically recognized callbacks.
15274     SmallVector<int, 4> Encoding;
15275     if (!FD->hasAttr<CallbackAttr>() &&
15276         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15277       FD->addAttr(CallbackAttr::CreateImplicit(
15278           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15279 
15280     // Mark const if we don't care about errno and that is the only thing
15281     // preventing the function from being const. This allows IRgen to use LLVM
15282     // intrinsics for such functions.
15283     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15284         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15285       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15286 
15287     // We make "fma" on GNU or Windows const because we know it does not set
15288     // errno in those environments even though it could set errno based on the
15289     // C standard.
15290     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15291     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15292         !FD->hasAttr<ConstAttr>()) {
15293       switch (BuiltinID) {
15294       case Builtin::BI__builtin_fma:
15295       case Builtin::BI__builtin_fmaf:
15296       case Builtin::BI__builtin_fmal:
15297       case Builtin::BIfma:
15298       case Builtin::BIfmaf:
15299       case Builtin::BIfmal:
15300         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15301         break;
15302       default:
15303         break;
15304       }
15305     }
15306 
15307     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15308         !FD->hasAttr<ReturnsTwiceAttr>())
15309       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15310                                          FD->getLocation()));
15311     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15312       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15313     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15314       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15315     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15316       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15317     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15318         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15319       // Add the appropriate attribute, depending on the CUDA compilation mode
15320       // and which target the builtin belongs to. For example, during host
15321       // compilation, aux builtins are __device__, while the rest are __host__.
15322       if (getLangOpts().CUDAIsDevice !=
15323           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15324         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15325       else
15326         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15327     }
15328 
15329     // Add known guaranteed alignment for allocation functions.
15330     switch (BuiltinID) {
15331     case Builtin::BImemalign:
15332     case Builtin::BIaligned_alloc:
15333       if (!FD->hasAttr<AllocAlignAttr>())
15334         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15335                                                    FD->getLocation()));
15336       break;
15337     default:
15338       break;
15339     }
15340 
15341     // Add allocsize attribute for allocation functions.
15342     switch (BuiltinID) {
15343     case Builtin::BIcalloc:
15344       FD->addAttr(AllocSizeAttr::CreateImplicit(
15345           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15346       break;
15347     case Builtin::BImemalign:
15348     case Builtin::BIaligned_alloc:
15349     case Builtin::BIrealloc:
15350       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15351                                                 ParamIdx(), FD->getLocation()));
15352       break;
15353     case Builtin::BImalloc:
15354       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15355                                                 ParamIdx(), FD->getLocation()));
15356       break;
15357     default:
15358       break;
15359     }
15360   }
15361 
15362   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15363 
15364   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15365   // throw, add an implicit nothrow attribute to any extern "C" function we come
15366   // across.
15367   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15368       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15369     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15370     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15371       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15372   }
15373 
15374   IdentifierInfo *Name = FD->getIdentifier();
15375   if (!Name)
15376     return;
15377   if ((!getLangOpts().CPlusPlus &&
15378        FD->getDeclContext()->isTranslationUnit()) ||
15379       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15380        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15381        LinkageSpecDecl::lang_c)) {
15382     // Okay: this could be a libc/libm/Objective-C function we know
15383     // about.
15384   } else
15385     return;
15386 
15387   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15388     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15389     // target-specific builtins, perhaps?
15390     if (!FD->hasAttr<FormatAttr>())
15391       FD->addAttr(FormatAttr::CreateImplicit(Context,
15392                                              &Context.Idents.get("printf"), 2,
15393                                              Name->isStr("vasprintf") ? 0 : 3,
15394                                              FD->getLocation()));
15395   }
15396 
15397   if (Name->isStr("__CFStringMakeConstantString")) {
15398     // We already have a __builtin___CFStringMakeConstantString,
15399     // but builds that use -fno-constant-cfstrings don't go through that.
15400     if (!FD->hasAttr<FormatArgAttr>())
15401       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15402                                                 FD->getLocation()));
15403   }
15404 }
15405 
15406 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15407                                     TypeSourceInfo *TInfo) {
15408   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15409   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15410 
15411   if (!TInfo) {
15412     assert(D.isInvalidType() && "no declarator info for valid type");
15413     TInfo = Context.getTrivialTypeSourceInfo(T);
15414   }
15415 
15416   // Scope manipulation handled by caller.
15417   TypedefDecl *NewTD =
15418       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15419                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15420 
15421   // Bail out immediately if we have an invalid declaration.
15422   if (D.isInvalidType()) {
15423     NewTD->setInvalidDecl();
15424     return NewTD;
15425   }
15426 
15427   if (D.getDeclSpec().isModulePrivateSpecified()) {
15428     if (CurContext->isFunctionOrMethod())
15429       Diag(NewTD->getLocation(), diag::err_module_private_local)
15430           << 2 << NewTD
15431           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15432           << FixItHint::CreateRemoval(
15433                  D.getDeclSpec().getModulePrivateSpecLoc());
15434     else
15435       NewTD->setModulePrivate();
15436   }
15437 
15438   // C++ [dcl.typedef]p8:
15439   //   If the typedef declaration defines an unnamed class (or
15440   //   enum), the first typedef-name declared by the declaration
15441   //   to be that class type (or enum type) is used to denote the
15442   //   class type (or enum type) for linkage purposes only.
15443   // We need to check whether the type was declared in the declaration.
15444   switch (D.getDeclSpec().getTypeSpecType()) {
15445   case TST_enum:
15446   case TST_struct:
15447   case TST_interface:
15448   case TST_union:
15449   case TST_class: {
15450     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15451     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15452     break;
15453   }
15454 
15455   default:
15456     break;
15457   }
15458 
15459   return NewTD;
15460 }
15461 
15462 /// Check that this is a valid underlying type for an enum declaration.
15463 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15464   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15465   QualType T = TI->getType();
15466 
15467   if (T->isDependentType())
15468     return false;
15469 
15470   // This doesn't use 'isIntegralType' despite the error message mentioning
15471   // integral type because isIntegralType would also allow enum types in C.
15472   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15473     if (BT->isInteger())
15474       return false;
15475 
15476   if (T->isBitIntType())
15477     return false;
15478 
15479   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15480 }
15481 
15482 /// Check whether this is a valid redeclaration of a previous enumeration.
15483 /// \return true if the redeclaration was invalid.
15484 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15485                                   QualType EnumUnderlyingTy, bool IsFixed,
15486                                   const EnumDecl *Prev) {
15487   if (IsScoped != Prev->isScoped()) {
15488     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15489       << Prev->isScoped();
15490     Diag(Prev->getLocation(), diag::note_previous_declaration);
15491     return true;
15492   }
15493 
15494   if (IsFixed && Prev->isFixed()) {
15495     if (!EnumUnderlyingTy->isDependentType() &&
15496         !Prev->getIntegerType()->isDependentType() &&
15497         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15498                                         Prev->getIntegerType())) {
15499       // TODO: Highlight the underlying type of the redeclaration.
15500       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15501         << EnumUnderlyingTy << Prev->getIntegerType();
15502       Diag(Prev->getLocation(), diag::note_previous_declaration)
15503           << Prev->getIntegerTypeRange();
15504       return true;
15505     }
15506   } else if (IsFixed != Prev->isFixed()) {
15507     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15508       << Prev->isFixed();
15509     Diag(Prev->getLocation(), diag::note_previous_declaration);
15510     return true;
15511   }
15512 
15513   return false;
15514 }
15515 
15516 /// Get diagnostic %select index for tag kind for
15517 /// redeclaration diagnostic message.
15518 /// WARNING: Indexes apply to particular diagnostics only!
15519 ///
15520 /// \returns diagnostic %select index.
15521 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15522   switch (Tag) {
15523   case TTK_Struct: return 0;
15524   case TTK_Interface: return 1;
15525   case TTK_Class:  return 2;
15526   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15527   }
15528 }
15529 
15530 /// Determine if tag kind is a class-key compatible with
15531 /// class for redeclaration (class, struct, or __interface).
15532 ///
15533 /// \returns true iff the tag kind is compatible.
15534 static bool isClassCompatTagKind(TagTypeKind Tag)
15535 {
15536   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15537 }
15538 
15539 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15540                                              TagTypeKind TTK) {
15541   if (isa<TypedefDecl>(PrevDecl))
15542     return NTK_Typedef;
15543   else if (isa<TypeAliasDecl>(PrevDecl))
15544     return NTK_TypeAlias;
15545   else if (isa<ClassTemplateDecl>(PrevDecl))
15546     return NTK_Template;
15547   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15548     return NTK_TypeAliasTemplate;
15549   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15550     return NTK_TemplateTemplateArgument;
15551   switch (TTK) {
15552   case TTK_Struct:
15553   case TTK_Interface:
15554   case TTK_Class:
15555     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15556   case TTK_Union:
15557     return NTK_NonUnion;
15558   case TTK_Enum:
15559     return NTK_NonEnum;
15560   }
15561   llvm_unreachable("invalid TTK");
15562 }
15563 
15564 /// Determine whether a tag with a given kind is acceptable
15565 /// as a redeclaration of the given tag declaration.
15566 ///
15567 /// \returns true if the new tag kind is acceptable, false otherwise.
15568 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15569                                         TagTypeKind NewTag, bool isDefinition,
15570                                         SourceLocation NewTagLoc,
15571                                         const IdentifierInfo *Name) {
15572   // C++ [dcl.type.elab]p3:
15573   //   The class-key or enum keyword present in the
15574   //   elaborated-type-specifier shall agree in kind with the
15575   //   declaration to which the name in the elaborated-type-specifier
15576   //   refers. This rule also applies to the form of
15577   //   elaborated-type-specifier that declares a class-name or
15578   //   friend class since it can be construed as referring to the
15579   //   definition of the class. Thus, in any
15580   //   elaborated-type-specifier, the enum keyword shall be used to
15581   //   refer to an enumeration (7.2), the union class-key shall be
15582   //   used to refer to a union (clause 9), and either the class or
15583   //   struct class-key shall be used to refer to a class (clause 9)
15584   //   declared using the class or struct class-key.
15585   TagTypeKind OldTag = Previous->getTagKind();
15586   if (OldTag != NewTag &&
15587       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15588     return false;
15589 
15590   // Tags are compatible, but we might still want to warn on mismatched tags.
15591   // Non-class tags can't be mismatched at this point.
15592   if (!isClassCompatTagKind(NewTag))
15593     return true;
15594 
15595   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15596   // by our warning analysis. We don't want to warn about mismatches with (eg)
15597   // declarations in system headers that are designed to be specialized, but if
15598   // a user asks us to warn, we should warn if their code contains mismatched
15599   // declarations.
15600   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15601     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15602                                       Loc);
15603   };
15604   if (IsIgnoredLoc(NewTagLoc))
15605     return true;
15606 
15607   auto IsIgnored = [&](const TagDecl *Tag) {
15608     return IsIgnoredLoc(Tag->getLocation());
15609   };
15610   while (IsIgnored(Previous)) {
15611     Previous = Previous->getPreviousDecl();
15612     if (!Previous)
15613       return true;
15614     OldTag = Previous->getTagKind();
15615   }
15616 
15617   bool isTemplate = false;
15618   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15619     isTemplate = Record->getDescribedClassTemplate();
15620 
15621   if (inTemplateInstantiation()) {
15622     if (OldTag != NewTag) {
15623       // In a template instantiation, do not offer fix-its for tag mismatches
15624       // since they usually mess up the template instead of fixing the problem.
15625       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15626         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15627         << getRedeclDiagFromTagKind(OldTag);
15628       // FIXME: Note previous location?
15629     }
15630     return true;
15631   }
15632 
15633   if (isDefinition) {
15634     // On definitions, check all previous tags and issue a fix-it for each
15635     // one that doesn't match the current tag.
15636     if (Previous->getDefinition()) {
15637       // Don't suggest fix-its for redefinitions.
15638       return true;
15639     }
15640 
15641     bool previousMismatch = false;
15642     for (const TagDecl *I : Previous->redecls()) {
15643       if (I->getTagKind() != NewTag) {
15644         // Ignore previous declarations for which the warning was disabled.
15645         if (IsIgnored(I))
15646           continue;
15647 
15648         if (!previousMismatch) {
15649           previousMismatch = true;
15650           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15651             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15652             << getRedeclDiagFromTagKind(I->getTagKind());
15653         }
15654         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15655           << getRedeclDiagFromTagKind(NewTag)
15656           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15657                TypeWithKeyword::getTagTypeKindName(NewTag));
15658       }
15659     }
15660     return true;
15661   }
15662 
15663   // Identify the prevailing tag kind: this is the kind of the definition (if
15664   // there is a non-ignored definition), or otherwise the kind of the prior
15665   // (non-ignored) declaration.
15666   const TagDecl *PrevDef = Previous->getDefinition();
15667   if (PrevDef && IsIgnored(PrevDef))
15668     PrevDef = nullptr;
15669   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15670   if (Redecl->getTagKind() != NewTag) {
15671     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15672       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15673       << getRedeclDiagFromTagKind(OldTag);
15674     Diag(Redecl->getLocation(), diag::note_previous_use);
15675 
15676     // If there is a previous definition, suggest a fix-it.
15677     if (PrevDef) {
15678       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15679         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15680         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15681              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15682     }
15683   }
15684 
15685   return true;
15686 }
15687 
15688 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15689 /// from an outer enclosing namespace or file scope inside a friend declaration.
15690 /// This should provide the commented out code in the following snippet:
15691 ///   namespace N {
15692 ///     struct X;
15693 ///     namespace M {
15694 ///       struct Y { friend struct /*N::*/ X; };
15695 ///     }
15696 ///   }
15697 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15698                                          SourceLocation NameLoc) {
15699   // While the decl is in a namespace, do repeated lookup of that name and see
15700   // if we get the same namespace back.  If we do not, continue until
15701   // translation unit scope, at which point we have a fully qualified NNS.
15702   SmallVector<IdentifierInfo *, 4> Namespaces;
15703   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15704   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15705     // This tag should be declared in a namespace, which can only be enclosed by
15706     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15707     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15708     if (!Namespace || Namespace->isAnonymousNamespace())
15709       return FixItHint();
15710     IdentifierInfo *II = Namespace->getIdentifier();
15711     Namespaces.push_back(II);
15712     NamedDecl *Lookup = SemaRef.LookupSingleName(
15713         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15714     if (Lookup == Namespace)
15715       break;
15716   }
15717 
15718   // Once we have all the namespaces, reverse them to go outermost first, and
15719   // build an NNS.
15720   SmallString<64> Insertion;
15721   llvm::raw_svector_ostream OS(Insertion);
15722   if (DC->isTranslationUnit())
15723     OS << "::";
15724   std::reverse(Namespaces.begin(), Namespaces.end());
15725   for (auto *II : Namespaces)
15726     OS << II->getName() << "::";
15727   return FixItHint::CreateInsertion(NameLoc, Insertion);
15728 }
15729 
15730 /// Determine whether a tag originally declared in context \p OldDC can
15731 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15732 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15733 /// using-declaration).
15734 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15735                                          DeclContext *NewDC) {
15736   OldDC = OldDC->getRedeclContext();
15737   NewDC = NewDC->getRedeclContext();
15738 
15739   if (OldDC->Equals(NewDC))
15740     return true;
15741 
15742   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15743   // encloses the other).
15744   if (S.getLangOpts().MSVCCompat &&
15745       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15746     return true;
15747 
15748   return false;
15749 }
15750 
15751 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15752 /// former case, Name will be non-null.  In the later case, Name will be null.
15753 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15754 /// reference/declaration/definition of a tag.
15755 ///
15756 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15757 /// trailing-type-specifier) other than one in an alias-declaration.
15758 ///
15759 /// \param SkipBody If non-null, will be set to indicate if the caller should
15760 /// skip the definition of this tag and treat it as if it were a declaration.
15761 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15762                      SourceLocation KWLoc, CXXScopeSpec &SS,
15763                      IdentifierInfo *Name, SourceLocation NameLoc,
15764                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15765                      SourceLocation ModulePrivateLoc,
15766                      MultiTemplateParamsArg TemplateParameterLists,
15767                      bool &OwnedDecl, bool &IsDependent,
15768                      SourceLocation ScopedEnumKWLoc,
15769                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15770                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15771                      SkipBodyInfo *SkipBody) {
15772   // If this is not a definition, it must have a name.
15773   IdentifierInfo *OrigName = Name;
15774   assert((Name != nullptr || TUK == TUK_Definition) &&
15775          "Nameless record must be a definition!");
15776   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15777 
15778   OwnedDecl = false;
15779   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15780   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15781 
15782   // FIXME: Check member specializations more carefully.
15783   bool isMemberSpecialization = false;
15784   bool Invalid = false;
15785 
15786   // We only need to do this matching if we have template parameters
15787   // or a scope specifier, which also conveniently avoids this work
15788   // for non-C++ cases.
15789   if (TemplateParameterLists.size() > 0 ||
15790       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15791     if (TemplateParameterList *TemplateParams =
15792             MatchTemplateParametersToScopeSpecifier(
15793                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15794                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15795       if (Kind == TTK_Enum) {
15796         Diag(KWLoc, diag::err_enum_template);
15797         return nullptr;
15798       }
15799 
15800       if (TemplateParams->size() > 0) {
15801         // This is a declaration or definition of a class template (which may
15802         // be a member of another template).
15803 
15804         if (Invalid)
15805           return nullptr;
15806 
15807         OwnedDecl = false;
15808         DeclResult Result = CheckClassTemplate(
15809             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15810             AS, ModulePrivateLoc,
15811             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15812             TemplateParameterLists.data(), SkipBody);
15813         return Result.get();
15814       } else {
15815         // The "template<>" header is extraneous.
15816         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15817           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15818         isMemberSpecialization = true;
15819       }
15820     }
15821 
15822     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15823         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15824       return nullptr;
15825   }
15826 
15827   // Figure out the underlying type if this a enum declaration. We need to do
15828   // this early, because it's needed to detect if this is an incompatible
15829   // redeclaration.
15830   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15831   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15832 
15833   if (Kind == TTK_Enum) {
15834     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15835       // No underlying type explicitly specified, or we failed to parse the
15836       // type, default to int.
15837       EnumUnderlying = Context.IntTy.getTypePtr();
15838     } else if (UnderlyingType.get()) {
15839       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15840       // integral type; any cv-qualification is ignored.
15841       TypeSourceInfo *TI = nullptr;
15842       GetTypeFromParser(UnderlyingType.get(), &TI);
15843       EnumUnderlying = TI;
15844 
15845       if (CheckEnumUnderlyingType(TI))
15846         // Recover by falling back to int.
15847         EnumUnderlying = Context.IntTy.getTypePtr();
15848 
15849       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15850                                           UPPC_FixedUnderlyingType))
15851         EnumUnderlying = Context.IntTy.getTypePtr();
15852 
15853     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15854       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15855       // of 'int'. However, if this is an unfixed forward declaration, don't set
15856       // the underlying type unless the user enables -fms-compatibility. This
15857       // makes unfixed forward declared enums incomplete and is more conforming.
15858       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15859         EnumUnderlying = Context.IntTy.getTypePtr();
15860     }
15861   }
15862 
15863   DeclContext *SearchDC = CurContext;
15864   DeclContext *DC = CurContext;
15865   bool isStdBadAlloc = false;
15866   bool isStdAlignValT = false;
15867 
15868   RedeclarationKind Redecl = forRedeclarationInCurContext();
15869   if (TUK == TUK_Friend || TUK == TUK_Reference)
15870     Redecl = NotForRedeclaration;
15871 
15872   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15873   /// implemented asks for structural equivalence checking, the returned decl
15874   /// here is passed back to the parser, allowing the tag body to be parsed.
15875   auto createTagFromNewDecl = [&]() -> TagDecl * {
15876     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15877     // If there is an identifier, use the location of the identifier as the
15878     // location of the decl, otherwise use the location of the struct/union
15879     // keyword.
15880     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15881     TagDecl *New = nullptr;
15882 
15883     if (Kind == TTK_Enum) {
15884       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15885                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15886       // If this is an undefined enum, bail.
15887       if (TUK != TUK_Definition && !Invalid)
15888         return nullptr;
15889       if (EnumUnderlying) {
15890         EnumDecl *ED = cast<EnumDecl>(New);
15891         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15892           ED->setIntegerTypeSourceInfo(TI);
15893         else
15894           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15895         ED->setPromotionType(ED->getIntegerType());
15896       }
15897     } else { // struct/union
15898       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15899                                nullptr);
15900     }
15901 
15902     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15903       // Add alignment attributes if necessary; these attributes are checked
15904       // when the ASTContext lays out the structure.
15905       //
15906       // It is important for implementing the correct semantics that this
15907       // happen here (in ActOnTag). The #pragma pack stack is
15908       // maintained as a result of parser callbacks which can occur at
15909       // many points during the parsing of a struct declaration (because
15910       // the #pragma tokens are effectively skipped over during the
15911       // parsing of the struct).
15912       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15913         AddAlignmentAttributesForRecord(RD);
15914         AddMsStructLayoutForRecord(RD);
15915       }
15916     }
15917     New->setLexicalDeclContext(CurContext);
15918     return New;
15919   };
15920 
15921   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15922   if (Name && SS.isNotEmpty()) {
15923     // We have a nested-name tag ('struct foo::bar').
15924 
15925     // Check for invalid 'foo::'.
15926     if (SS.isInvalid()) {
15927       Name = nullptr;
15928       goto CreateNewDecl;
15929     }
15930 
15931     // If this is a friend or a reference to a class in a dependent
15932     // context, don't try to make a decl for it.
15933     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15934       DC = computeDeclContext(SS, false);
15935       if (!DC) {
15936         IsDependent = true;
15937         return nullptr;
15938       }
15939     } else {
15940       DC = computeDeclContext(SS, true);
15941       if (!DC) {
15942         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15943           << SS.getRange();
15944         return nullptr;
15945       }
15946     }
15947 
15948     if (RequireCompleteDeclContext(SS, DC))
15949       return nullptr;
15950 
15951     SearchDC = DC;
15952     // Look-up name inside 'foo::'.
15953     LookupQualifiedName(Previous, DC);
15954 
15955     if (Previous.isAmbiguous())
15956       return nullptr;
15957 
15958     if (Previous.empty()) {
15959       // Name lookup did not find anything. However, if the
15960       // nested-name-specifier refers to the current instantiation,
15961       // and that current instantiation has any dependent base
15962       // classes, we might find something at instantiation time: treat
15963       // this as a dependent elaborated-type-specifier.
15964       // But this only makes any sense for reference-like lookups.
15965       if (Previous.wasNotFoundInCurrentInstantiation() &&
15966           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15967         IsDependent = true;
15968         return nullptr;
15969       }
15970 
15971       // A tag 'foo::bar' must already exist.
15972       Diag(NameLoc, diag::err_not_tag_in_scope)
15973         << Kind << Name << DC << SS.getRange();
15974       Name = nullptr;
15975       Invalid = true;
15976       goto CreateNewDecl;
15977     }
15978   } else if (Name) {
15979     // C++14 [class.mem]p14:
15980     //   If T is the name of a class, then each of the following shall have a
15981     //   name different from T:
15982     //    -- every member of class T that is itself a type
15983     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15984         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15985       return nullptr;
15986 
15987     // If this is a named struct, check to see if there was a previous forward
15988     // declaration or definition.
15989     // FIXME: We're looking into outer scopes here, even when we
15990     // shouldn't be. Doing so can result in ambiguities that we
15991     // shouldn't be diagnosing.
15992     LookupName(Previous, S);
15993 
15994     // When declaring or defining a tag, ignore ambiguities introduced
15995     // by types using'ed into this scope.
15996     if (Previous.isAmbiguous() &&
15997         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15998       LookupResult::Filter F = Previous.makeFilter();
15999       while (F.hasNext()) {
16000         NamedDecl *ND = F.next();
16001         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16002                 SearchDC->getRedeclContext()))
16003           F.erase();
16004       }
16005       F.done();
16006     }
16007 
16008     // C++11 [namespace.memdef]p3:
16009     //   If the name in a friend declaration is neither qualified nor
16010     //   a template-id and the declaration is a function or an
16011     //   elaborated-type-specifier, the lookup to determine whether
16012     //   the entity has been previously declared shall not consider
16013     //   any scopes outside the innermost enclosing namespace.
16014     //
16015     // MSVC doesn't implement the above rule for types, so a friend tag
16016     // declaration may be a redeclaration of a type declared in an enclosing
16017     // scope.  They do implement this rule for friend functions.
16018     //
16019     // Does it matter that this should be by scope instead of by
16020     // semantic context?
16021     if (!Previous.empty() && TUK == TUK_Friend) {
16022       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16023       LookupResult::Filter F = Previous.makeFilter();
16024       bool FriendSawTagOutsideEnclosingNamespace = false;
16025       while (F.hasNext()) {
16026         NamedDecl *ND = F.next();
16027         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16028         if (DC->isFileContext() &&
16029             !EnclosingNS->Encloses(ND->getDeclContext())) {
16030           if (getLangOpts().MSVCCompat)
16031             FriendSawTagOutsideEnclosingNamespace = true;
16032           else
16033             F.erase();
16034         }
16035       }
16036       F.done();
16037 
16038       // Diagnose this MSVC extension in the easy case where lookup would have
16039       // unambiguously found something outside the enclosing namespace.
16040       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16041         NamedDecl *ND = Previous.getFoundDecl();
16042         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16043             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16044       }
16045     }
16046 
16047     // Note:  there used to be some attempt at recovery here.
16048     if (Previous.isAmbiguous())
16049       return nullptr;
16050 
16051     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16052       // FIXME: This makes sure that we ignore the contexts associated
16053       // with C structs, unions, and enums when looking for a matching
16054       // tag declaration or definition. See the similar lookup tweak
16055       // in Sema::LookupName; is there a better way to deal with this?
16056       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
16057         SearchDC = SearchDC->getParent();
16058     }
16059   }
16060 
16061   if (Previous.isSingleResult() &&
16062       Previous.getFoundDecl()->isTemplateParameter()) {
16063     // Maybe we will complain about the shadowed template parameter.
16064     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16065     // Just pretend that we didn't see the previous declaration.
16066     Previous.clear();
16067   }
16068 
16069   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16070       DC->Equals(getStdNamespace())) {
16071     if (Name->isStr("bad_alloc")) {
16072       // This is a declaration of or a reference to "std::bad_alloc".
16073       isStdBadAlloc = true;
16074 
16075       // If std::bad_alloc has been implicitly declared (but made invisible to
16076       // name lookup), fill in this implicit declaration as the previous
16077       // declaration, so that the declarations get chained appropriately.
16078       if (Previous.empty() && StdBadAlloc)
16079         Previous.addDecl(getStdBadAlloc());
16080     } else if (Name->isStr("align_val_t")) {
16081       isStdAlignValT = true;
16082       if (Previous.empty() && StdAlignValT)
16083         Previous.addDecl(getStdAlignValT());
16084     }
16085   }
16086 
16087   // If we didn't find a previous declaration, and this is a reference
16088   // (or friend reference), move to the correct scope.  In C++, we
16089   // also need to do a redeclaration lookup there, just in case
16090   // there's a shadow friend decl.
16091   if (Name && Previous.empty() &&
16092       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16093     if (Invalid) goto CreateNewDecl;
16094     assert(SS.isEmpty());
16095 
16096     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16097       // C++ [basic.scope.pdecl]p5:
16098       //   -- for an elaborated-type-specifier of the form
16099       //
16100       //          class-key identifier
16101       //
16102       //      if the elaborated-type-specifier is used in the
16103       //      decl-specifier-seq or parameter-declaration-clause of a
16104       //      function defined in namespace scope, the identifier is
16105       //      declared as a class-name in the namespace that contains
16106       //      the declaration; otherwise, except as a friend
16107       //      declaration, the identifier is declared in the smallest
16108       //      non-class, non-function-prototype scope that contains the
16109       //      declaration.
16110       //
16111       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16112       // C structs and unions.
16113       //
16114       // It is an error in C++ to declare (rather than define) an enum
16115       // type, including via an elaborated type specifier.  We'll
16116       // diagnose that later; for now, declare the enum in the same
16117       // scope as we would have picked for any other tag type.
16118       //
16119       // GNU C also supports this behavior as part of its incomplete
16120       // enum types extension, while GNU C++ does not.
16121       //
16122       // Find the context where we'll be declaring the tag.
16123       // FIXME: We would like to maintain the current DeclContext as the
16124       // lexical context,
16125       SearchDC = getTagInjectionContext(SearchDC);
16126 
16127       // Find the scope where we'll be declaring the tag.
16128       S = getTagInjectionScope(S, getLangOpts());
16129     } else {
16130       assert(TUK == TUK_Friend);
16131       // C++ [namespace.memdef]p3:
16132       //   If a friend declaration in a non-local class first declares a
16133       //   class or function, the friend class or function is a member of
16134       //   the innermost enclosing namespace.
16135       SearchDC = SearchDC->getEnclosingNamespaceContext();
16136     }
16137 
16138     // In C++, we need to do a redeclaration lookup to properly
16139     // diagnose some problems.
16140     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16141     // hidden declaration so that we don't get ambiguity errors when using a
16142     // type declared by an elaborated-type-specifier.  In C that is not correct
16143     // and we should instead merge compatible types found by lookup.
16144     if (getLangOpts().CPlusPlus) {
16145       // FIXME: This can perform qualified lookups into function contexts,
16146       // which are meaningless.
16147       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16148       LookupQualifiedName(Previous, SearchDC);
16149     } else {
16150       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16151       LookupName(Previous, S);
16152     }
16153   }
16154 
16155   // If we have a known previous declaration to use, then use it.
16156   if (Previous.empty() && SkipBody && SkipBody->Previous)
16157     Previous.addDecl(SkipBody->Previous);
16158 
16159   if (!Previous.empty()) {
16160     NamedDecl *PrevDecl = Previous.getFoundDecl();
16161     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16162 
16163     // It's okay to have a tag decl in the same scope as a typedef
16164     // which hides a tag decl in the same scope.  Finding this
16165     // with a redeclaration lookup can only actually happen in C++.
16166     //
16167     // This is also okay for elaborated-type-specifiers, which is
16168     // technically forbidden by the current standard but which is
16169     // okay according to the likely resolution of an open issue;
16170     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16171     if (getLangOpts().CPlusPlus) {
16172       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16173         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16174           TagDecl *Tag = TT->getDecl();
16175           if (Tag->getDeclName() == Name &&
16176               Tag->getDeclContext()->getRedeclContext()
16177                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16178             PrevDecl = Tag;
16179             Previous.clear();
16180             Previous.addDecl(Tag);
16181             Previous.resolveKind();
16182           }
16183         }
16184       }
16185     }
16186 
16187     // If this is a redeclaration of a using shadow declaration, it must
16188     // declare a tag in the same context. In MSVC mode, we allow a
16189     // redefinition if either context is within the other.
16190     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16191       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16192       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16193           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16194           !(OldTag && isAcceptableTagRedeclContext(
16195                           *this, OldTag->getDeclContext(), SearchDC))) {
16196         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16197         Diag(Shadow->getTargetDecl()->getLocation(),
16198              diag::note_using_decl_target);
16199         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16200             << 0;
16201         // Recover by ignoring the old declaration.
16202         Previous.clear();
16203         goto CreateNewDecl;
16204       }
16205     }
16206 
16207     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16208       // If this is a use of a previous tag, or if the tag is already declared
16209       // in the same scope (so that the definition/declaration completes or
16210       // rementions the tag), reuse the decl.
16211       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16212           isDeclInScope(DirectPrevDecl, SearchDC, S,
16213                         SS.isNotEmpty() || isMemberSpecialization)) {
16214         // Make sure that this wasn't declared as an enum and now used as a
16215         // struct or something similar.
16216         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16217                                           TUK == TUK_Definition, KWLoc,
16218                                           Name)) {
16219           bool SafeToContinue
16220             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16221                Kind != TTK_Enum);
16222           if (SafeToContinue)
16223             Diag(KWLoc, diag::err_use_with_wrong_tag)
16224               << Name
16225               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16226                                               PrevTagDecl->getKindName());
16227           else
16228             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16229           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16230 
16231           if (SafeToContinue)
16232             Kind = PrevTagDecl->getTagKind();
16233           else {
16234             // Recover by making this an anonymous redefinition.
16235             Name = nullptr;
16236             Previous.clear();
16237             Invalid = true;
16238           }
16239         }
16240 
16241         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16242           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16243           if (TUK == TUK_Reference || TUK == TUK_Friend)
16244             return PrevTagDecl;
16245 
16246           QualType EnumUnderlyingTy;
16247           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16248             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16249           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16250             EnumUnderlyingTy = QualType(T, 0);
16251 
16252           // All conflicts with previous declarations are recovered by
16253           // returning the previous declaration, unless this is a definition,
16254           // in which case we want the caller to bail out.
16255           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16256                                      ScopedEnum, EnumUnderlyingTy,
16257                                      IsFixed, PrevEnum))
16258             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16259         }
16260 
16261         // C++11 [class.mem]p1:
16262         //   A member shall not be declared twice in the member-specification,
16263         //   except that a nested class or member class template can be declared
16264         //   and then later defined.
16265         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16266             S->isDeclScope(PrevDecl)) {
16267           Diag(NameLoc, diag::ext_member_redeclared);
16268           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16269         }
16270 
16271         if (!Invalid) {
16272           // If this is a use, just return the declaration we found, unless
16273           // we have attributes.
16274           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16275             if (!Attrs.empty()) {
16276               // FIXME: Diagnose these attributes. For now, we create a new
16277               // declaration to hold them.
16278             } else if (TUK == TUK_Reference &&
16279                        (PrevTagDecl->getFriendObjectKind() ==
16280                             Decl::FOK_Undeclared ||
16281                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16282                        SS.isEmpty()) {
16283               // This declaration is a reference to an existing entity, but
16284               // has different visibility from that entity: it either makes
16285               // a friend visible or it makes a type visible in a new module.
16286               // In either case, create a new declaration. We only do this if
16287               // the declaration would have meant the same thing if no prior
16288               // declaration were found, that is, if it was found in the same
16289               // scope where we would have injected a declaration.
16290               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16291                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16292                 return PrevTagDecl;
16293               // This is in the injected scope, create a new declaration in
16294               // that scope.
16295               S = getTagInjectionScope(S, getLangOpts());
16296             } else {
16297               return PrevTagDecl;
16298             }
16299           }
16300 
16301           // Diagnose attempts to redefine a tag.
16302           if (TUK == TUK_Definition) {
16303             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16304               // If we're defining a specialization and the previous definition
16305               // is from an implicit instantiation, don't emit an error
16306               // here; we'll catch this in the general case below.
16307               bool IsExplicitSpecializationAfterInstantiation = false;
16308               if (isMemberSpecialization) {
16309                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16310                   IsExplicitSpecializationAfterInstantiation =
16311                     RD->getTemplateSpecializationKind() !=
16312                     TSK_ExplicitSpecialization;
16313                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16314                   IsExplicitSpecializationAfterInstantiation =
16315                     ED->getTemplateSpecializationKind() !=
16316                     TSK_ExplicitSpecialization;
16317               }
16318 
16319               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16320               // not keep more that one definition around (merge them). However,
16321               // ensure the decl passes the structural compatibility check in
16322               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16323               NamedDecl *Hidden = nullptr;
16324               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16325                 // There is a definition of this tag, but it is not visible. We
16326                 // explicitly make use of C++'s one definition rule here, and
16327                 // assume that this definition is identical to the hidden one
16328                 // we already have. Make the existing definition visible and
16329                 // use it in place of this one.
16330                 if (!getLangOpts().CPlusPlus) {
16331                   // Postpone making the old definition visible until after we
16332                   // complete parsing the new one and do the structural
16333                   // comparison.
16334                   SkipBody->CheckSameAsPrevious = true;
16335                   SkipBody->New = createTagFromNewDecl();
16336                   SkipBody->Previous = Def;
16337                   return Def;
16338                 } else {
16339                   SkipBody->ShouldSkip = true;
16340                   SkipBody->Previous = Def;
16341                   makeMergedDefinitionVisible(Hidden);
16342                   // Carry on and handle it like a normal definition. We'll
16343                   // skip starting the definitiion later.
16344                 }
16345               } else if (!IsExplicitSpecializationAfterInstantiation) {
16346                 // A redeclaration in function prototype scope in C isn't
16347                 // visible elsewhere, so merely issue a warning.
16348                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16349                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16350                 else
16351                   Diag(NameLoc, diag::err_redefinition) << Name;
16352                 notePreviousDefinition(Def,
16353                                        NameLoc.isValid() ? NameLoc : KWLoc);
16354                 // If this is a redefinition, recover by making this
16355                 // struct be anonymous, which will make any later
16356                 // references get the previous definition.
16357                 Name = nullptr;
16358                 Previous.clear();
16359                 Invalid = true;
16360               }
16361             } else {
16362               // If the type is currently being defined, complain
16363               // about a nested redefinition.
16364               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16365               if (TD->isBeingDefined()) {
16366                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16367                 Diag(PrevTagDecl->getLocation(),
16368                      diag::note_previous_definition);
16369                 Name = nullptr;
16370                 Previous.clear();
16371                 Invalid = true;
16372               }
16373             }
16374 
16375             // Okay, this is definition of a previously declared or referenced
16376             // tag. We're going to create a new Decl for it.
16377           }
16378 
16379           // Okay, we're going to make a redeclaration.  If this is some kind
16380           // of reference, make sure we build the redeclaration in the same DC
16381           // as the original, and ignore the current access specifier.
16382           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16383             SearchDC = PrevTagDecl->getDeclContext();
16384             AS = AS_none;
16385           }
16386         }
16387         // If we get here we have (another) forward declaration or we
16388         // have a definition.  Just create a new decl.
16389 
16390       } else {
16391         // If we get here, this is a definition of a new tag type in a nested
16392         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16393         // new decl/type.  We set PrevDecl to NULL so that the entities
16394         // have distinct types.
16395         Previous.clear();
16396       }
16397       // If we get here, we're going to create a new Decl. If PrevDecl
16398       // is non-NULL, it's a definition of the tag declared by
16399       // PrevDecl. If it's NULL, we have a new definition.
16400 
16401     // Otherwise, PrevDecl is not a tag, but was found with tag
16402     // lookup.  This is only actually possible in C++, where a few
16403     // things like templates still live in the tag namespace.
16404     } else {
16405       // Use a better diagnostic if an elaborated-type-specifier
16406       // found the wrong kind of type on the first
16407       // (non-redeclaration) lookup.
16408       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16409           !Previous.isForRedeclaration()) {
16410         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16411         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16412                                                        << Kind;
16413         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16414         Invalid = true;
16415 
16416       // Otherwise, only diagnose if the declaration is in scope.
16417       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16418                                 SS.isNotEmpty() || isMemberSpecialization)) {
16419         // do nothing
16420 
16421       // Diagnose implicit declarations introduced by elaborated types.
16422       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16423         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16424         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16425         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16426         Invalid = true;
16427 
16428       // Otherwise it's a declaration.  Call out a particularly common
16429       // case here.
16430       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16431         unsigned Kind = 0;
16432         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16433         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16434           << Name << Kind << TND->getUnderlyingType();
16435         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16436         Invalid = true;
16437 
16438       // Otherwise, diagnose.
16439       } else {
16440         // The tag name clashes with something else in the target scope,
16441         // issue an error and recover by making this tag be anonymous.
16442         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16443         notePreviousDefinition(PrevDecl, NameLoc);
16444         Name = nullptr;
16445         Invalid = true;
16446       }
16447 
16448       // The existing declaration isn't relevant to us; we're in a
16449       // new scope, so clear out the previous declaration.
16450       Previous.clear();
16451     }
16452   }
16453 
16454 CreateNewDecl:
16455 
16456   TagDecl *PrevDecl = nullptr;
16457   if (Previous.isSingleResult())
16458     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16459 
16460   // If there is an identifier, use the location of the identifier as the
16461   // location of the decl, otherwise use the location of the struct/union
16462   // keyword.
16463   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16464 
16465   // Otherwise, create a new declaration. If there is a previous
16466   // declaration of the same entity, the two will be linked via
16467   // PrevDecl.
16468   TagDecl *New;
16469 
16470   if (Kind == TTK_Enum) {
16471     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16472     // enum X { A, B, C } D;    D should chain to X.
16473     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16474                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16475                            ScopedEnumUsesClassTag, IsFixed);
16476 
16477     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16478       StdAlignValT = cast<EnumDecl>(New);
16479 
16480     // If this is an undefined enum, warn.
16481     if (TUK != TUK_Definition && !Invalid) {
16482       TagDecl *Def;
16483       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16484         // C++0x: 7.2p2: opaque-enum-declaration.
16485         // Conflicts are diagnosed above. Do nothing.
16486       }
16487       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16488         Diag(Loc, diag::ext_forward_ref_enum_def)
16489           << New;
16490         Diag(Def->getLocation(), diag::note_previous_definition);
16491       } else {
16492         unsigned DiagID = diag::ext_forward_ref_enum;
16493         if (getLangOpts().MSVCCompat)
16494           DiagID = diag::ext_ms_forward_ref_enum;
16495         else if (getLangOpts().CPlusPlus)
16496           DiagID = diag::err_forward_ref_enum;
16497         Diag(Loc, DiagID);
16498       }
16499     }
16500 
16501     if (EnumUnderlying) {
16502       EnumDecl *ED = cast<EnumDecl>(New);
16503       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16504         ED->setIntegerTypeSourceInfo(TI);
16505       else
16506         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16507       ED->setPromotionType(ED->getIntegerType());
16508       assert(ED->isComplete() && "enum with type should be complete");
16509     }
16510   } else {
16511     // struct/union/class
16512 
16513     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16514     // struct X { int A; } D;    D should chain to X.
16515     if (getLangOpts().CPlusPlus) {
16516       // FIXME: Look for a way to use RecordDecl for simple structs.
16517       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16518                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16519 
16520       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16521         StdBadAlloc = cast<CXXRecordDecl>(New);
16522     } else
16523       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16524                                cast_or_null<RecordDecl>(PrevDecl));
16525   }
16526 
16527   // C++11 [dcl.type]p3:
16528   //   A type-specifier-seq shall not define a class or enumeration [...].
16529   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16530       TUK == TUK_Definition) {
16531     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16532       << Context.getTagDeclType(New);
16533     Invalid = true;
16534   }
16535 
16536   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16537       DC->getDeclKind() == Decl::Enum) {
16538     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16539       << Context.getTagDeclType(New);
16540     Invalid = true;
16541   }
16542 
16543   // Maybe add qualifier info.
16544   if (SS.isNotEmpty()) {
16545     if (SS.isSet()) {
16546       // If this is either a declaration or a definition, check the
16547       // nested-name-specifier against the current context.
16548       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16549           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16550                                        isMemberSpecialization))
16551         Invalid = true;
16552 
16553       New->setQualifierInfo(SS.getWithLocInContext(Context));
16554       if (TemplateParameterLists.size() > 0) {
16555         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16556       }
16557     }
16558     else
16559       Invalid = true;
16560   }
16561 
16562   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16563     // Add alignment attributes if necessary; these attributes are checked when
16564     // the ASTContext lays out the structure.
16565     //
16566     // It is important for implementing the correct semantics that this
16567     // happen here (in ActOnTag). The #pragma pack stack is
16568     // maintained as a result of parser callbacks which can occur at
16569     // many points during the parsing of a struct declaration (because
16570     // the #pragma tokens are effectively skipped over during the
16571     // parsing of the struct).
16572     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16573       AddAlignmentAttributesForRecord(RD);
16574       AddMsStructLayoutForRecord(RD);
16575     }
16576   }
16577 
16578   if (ModulePrivateLoc.isValid()) {
16579     if (isMemberSpecialization)
16580       Diag(New->getLocation(), diag::err_module_private_specialization)
16581         << 2
16582         << FixItHint::CreateRemoval(ModulePrivateLoc);
16583     // __module_private__ does not apply to local classes. However, we only
16584     // diagnose this as an error when the declaration specifiers are
16585     // freestanding. Here, we just ignore the __module_private__.
16586     else if (!SearchDC->isFunctionOrMethod())
16587       New->setModulePrivate();
16588   }
16589 
16590   // If this is a specialization of a member class (of a class template),
16591   // check the specialization.
16592   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16593     Invalid = true;
16594 
16595   // If we're declaring or defining a tag in function prototype scope in C,
16596   // note that this type can only be used within the function and add it to
16597   // the list of decls to inject into the function definition scope.
16598   if ((Name || Kind == TTK_Enum) &&
16599       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16600     if (getLangOpts().CPlusPlus) {
16601       // C++ [dcl.fct]p6:
16602       //   Types shall not be defined in return or parameter types.
16603       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16604         Diag(Loc, diag::err_type_defined_in_param_type)
16605             << Name;
16606         Invalid = true;
16607       }
16608     } else if (!PrevDecl) {
16609       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16610     }
16611   }
16612 
16613   if (Invalid)
16614     New->setInvalidDecl();
16615 
16616   // Set the lexical context. If the tag has a C++ scope specifier, the
16617   // lexical context will be different from the semantic context.
16618   New->setLexicalDeclContext(CurContext);
16619 
16620   // Mark this as a friend decl if applicable.
16621   // In Microsoft mode, a friend declaration also acts as a forward
16622   // declaration so we always pass true to setObjectOfFriendDecl to make
16623   // the tag name visible.
16624   if (TUK == TUK_Friend)
16625     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16626 
16627   // Set the access specifier.
16628   if (!Invalid && SearchDC->isRecord())
16629     SetMemberAccessSpecifier(New, PrevDecl, AS);
16630 
16631   if (PrevDecl)
16632     CheckRedeclarationInModule(New, PrevDecl);
16633 
16634   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16635     New->startDefinition();
16636 
16637   ProcessDeclAttributeList(S, New, Attrs);
16638   AddPragmaAttributes(S, New);
16639 
16640   // If this has an identifier, add it to the scope stack.
16641   if (TUK == TUK_Friend) {
16642     // We might be replacing an existing declaration in the lookup tables;
16643     // if so, borrow its access specifier.
16644     if (PrevDecl)
16645       New->setAccess(PrevDecl->getAccess());
16646 
16647     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16648     DC->makeDeclVisibleInContext(New);
16649     if (Name) // can be null along some error paths
16650       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16651         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16652   } else if (Name) {
16653     S = getNonFieldDeclScope(S);
16654     PushOnScopeChains(New, S, true);
16655   } else {
16656     CurContext->addDecl(New);
16657   }
16658 
16659   // If this is the C FILE type, notify the AST context.
16660   if (IdentifierInfo *II = New->getIdentifier())
16661     if (!New->isInvalidDecl() &&
16662         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16663         II->isStr("FILE"))
16664       Context.setFILEDecl(New);
16665 
16666   if (PrevDecl)
16667     mergeDeclAttributes(New, PrevDecl);
16668 
16669   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16670     inferGslOwnerPointerAttribute(CXXRD);
16671 
16672   // If there's a #pragma GCC visibility in scope, set the visibility of this
16673   // record.
16674   AddPushedVisibilityAttribute(New);
16675 
16676   if (isMemberSpecialization && !New->isInvalidDecl())
16677     CompleteMemberSpecialization(New, Previous);
16678 
16679   OwnedDecl = true;
16680   // In C++, don't return an invalid declaration. We can't recover well from
16681   // the cases where we make the type anonymous.
16682   if (Invalid && getLangOpts().CPlusPlus) {
16683     if (New->isBeingDefined())
16684       if (auto RD = dyn_cast<RecordDecl>(New))
16685         RD->completeDefinition();
16686     return nullptr;
16687   } else if (SkipBody && SkipBody->ShouldSkip) {
16688     return SkipBody->Previous;
16689   } else {
16690     return New;
16691   }
16692 }
16693 
16694 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16695   AdjustDeclIfTemplate(TagD);
16696   TagDecl *Tag = cast<TagDecl>(TagD);
16697 
16698   // Enter the tag context.
16699   PushDeclContext(S, Tag);
16700 
16701   ActOnDocumentableDecl(TagD);
16702 
16703   // If there's a #pragma GCC visibility in scope, set the visibility of this
16704   // record.
16705   AddPushedVisibilityAttribute(Tag);
16706 }
16707 
16708 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16709                                     SkipBodyInfo &SkipBody) {
16710   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16711     return false;
16712 
16713   // Make the previous decl visible.
16714   makeMergedDefinitionVisible(SkipBody.Previous);
16715   return true;
16716 }
16717 
16718 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16719   assert(isa<ObjCContainerDecl>(IDecl) &&
16720          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16721   DeclContext *OCD = cast<DeclContext>(IDecl);
16722   assert(OCD->getLexicalParent() == CurContext &&
16723       "The next DeclContext should be lexically contained in the current one.");
16724   CurContext = OCD;
16725   return IDecl;
16726 }
16727 
16728 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16729                                            SourceLocation FinalLoc,
16730                                            bool IsFinalSpelledSealed,
16731                                            bool IsAbstract,
16732                                            SourceLocation LBraceLoc) {
16733   AdjustDeclIfTemplate(TagD);
16734   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16735 
16736   FieldCollector->StartClass();
16737 
16738   if (!Record->getIdentifier())
16739     return;
16740 
16741   if (IsAbstract)
16742     Record->markAbstract();
16743 
16744   if (FinalLoc.isValid()) {
16745     Record->addAttr(FinalAttr::Create(
16746         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16747         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16748   }
16749   // C++ [class]p2:
16750   //   [...] The class-name is also inserted into the scope of the
16751   //   class itself; this is known as the injected-class-name. For
16752   //   purposes of access checking, the injected-class-name is treated
16753   //   as if it were a public member name.
16754   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16755       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16756       Record->getLocation(), Record->getIdentifier(),
16757       /*PrevDecl=*/nullptr,
16758       /*DelayTypeCreation=*/true);
16759   Context.getTypeDeclType(InjectedClassName, Record);
16760   InjectedClassName->setImplicit();
16761   InjectedClassName->setAccess(AS_public);
16762   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16763       InjectedClassName->setDescribedClassTemplate(Template);
16764   PushOnScopeChains(InjectedClassName, S);
16765   assert(InjectedClassName->isInjectedClassName() &&
16766          "Broken injected-class-name");
16767 }
16768 
16769 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16770                                     SourceRange BraceRange) {
16771   AdjustDeclIfTemplate(TagD);
16772   TagDecl *Tag = cast<TagDecl>(TagD);
16773   Tag->setBraceRange(BraceRange);
16774 
16775   // Make sure we "complete" the definition even it is invalid.
16776   if (Tag->isBeingDefined()) {
16777     assert(Tag->isInvalidDecl() && "We should already have completed it");
16778     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16779       RD->completeDefinition();
16780   }
16781 
16782   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16783     FieldCollector->FinishClass();
16784     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
16785       auto *Def = RD->getDefinition();
16786       assert(Def && "The record is expected to have a completed definition");
16787       unsigned NumInitMethods = 0;
16788       for (auto *Method : Def->methods()) {
16789         if (!Method->getIdentifier())
16790             continue;
16791         if (Method->getName() == "__init")
16792           NumInitMethods++;
16793       }
16794       if (NumInitMethods > 1 || !Def->hasInitMethod())
16795         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16796     }
16797   }
16798 
16799   // Exit this scope of this tag's definition.
16800   PopDeclContext();
16801 
16802   if (getCurLexicalContext()->isObjCContainer() &&
16803       Tag->getDeclContext()->isFileContext())
16804     Tag->setTopLevelDeclInObjCContainer();
16805 
16806   // Notify the consumer that we've defined a tag.
16807   if (!Tag->isInvalidDecl())
16808     Consumer.HandleTagDeclDefinition(Tag);
16809 
16810   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16811   // from XLs and instead matches the XL #pragma pack(1) behavior.
16812   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16813       AlignPackStack.hasValue()) {
16814     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16815     // Only diagnose #pragma align(packed).
16816     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16817       return;
16818     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16819     if (!RD)
16820       return;
16821     // Only warn if there is at least 1 bitfield member.
16822     if (llvm::any_of(RD->fields(),
16823                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16824       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16825   }
16826 }
16827 
16828 void Sema::ActOnObjCContainerFinishDefinition() {
16829   // Exit this scope of this interface definition.
16830   PopDeclContext();
16831 }
16832 
16833 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16834   assert(DC == CurContext && "Mismatch of container contexts");
16835   OriginalLexicalContext = DC;
16836   ActOnObjCContainerFinishDefinition();
16837 }
16838 
16839 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16840   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16841   OriginalLexicalContext = nullptr;
16842 }
16843 
16844 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16845   AdjustDeclIfTemplate(TagD);
16846   TagDecl *Tag = cast<TagDecl>(TagD);
16847   Tag->setInvalidDecl();
16848 
16849   // Make sure we "complete" the definition even it is invalid.
16850   if (Tag->isBeingDefined()) {
16851     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16852       RD->completeDefinition();
16853   }
16854 
16855   // We're undoing ActOnTagStartDefinition here, not
16856   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16857   // the FieldCollector.
16858 
16859   PopDeclContext();
16860 }
16861 
16862 // Note that FieldName may be null for anonymous bitfields.
16863 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16864                                 IdentifierInfo *FieldName,
16865                                 QualType FieldTy, bool IsMsStruct,
16866                                 Expr *BitWidth, bool *ZeroWidth) {
16867   assert(BitWidth);
16868   if (BitWidth->containsErrors())
16869     return ExprError();
16870 
16871   // Default to true; that shouldn't confuse checks for emptiness
16872   if (ZeroWidth)
16873     *ZeroWidth = true;
16874 
16875   // C99 6.7.2.1p4 - verify the field type.
16876   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16877   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16878     // Handle incomplete and sizeless types with a specific error.
16879     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16880                                  diag::err_field_incomplete_or_sizeless))
16881       return ExprError();
16882     if (FieldName)
16883       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16884         << FieldName << FieldTy << BitWidth->getSourceRange();
16885     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16886       << FieldTy << BitWidth->getSourceRange();
16887   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16888                                              UPPC_BitFieldWidth))
16889     return ExprError();
16890 
16891   // If the bit-width is type- or value-dependent, don't try to check
16892   // it now.
16893   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16894     return BitWidth;
16895 
16896   llvm::APSInt Value;
16897   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16898   if (ICE.isInvalid())
16899     return ICE;
16900   BitWidth = ICE.get();
16901 
16902   if (Value != 0 && ZeroWidth)
16903     *ZeroWidth = false;
16904 
16905   // Zero-width bitfield is ok for anonymous field.
16906   if (Value == 0 && FieldName)
16907     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16908 
16909   if (Value.isSigned() && Value.isNegative()) {
16910     if (FieldName)
16911       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16912                << FieldName << toString(Value, 10);
16913     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16914       << toString(Value, 10);
16915   }
16916 
16917   // The size of the bit-field must not exceed our maximum permitted object
16918   // size.
16919   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16920     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16921            << !FieldName << FieldName << toString(Value, 10);
16922   }
16923 
16924   if (!FieldTy->isDependentType()) {
16925     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16926     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16927     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16928 
16929     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16930     // ABI.
16931     bool CStdConstraintViolation =
16932         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16933     bool MSBitfieldViolation =
16934         Value.ugt(TypeStorageSize) &&
16935         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16936     if (CStdConstraintViolation || MSBitfieldViolation) {
16937       unsigned DiagWidth =
16938           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16939       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16940              << (bool)FieldName << FieldName << toString(Value, 10)
16941              << !CStdConstraintViolation << DiagWidth;
16942     }
16943 
16944     // Warn on types where the user might conceivably expect to get all
16945     // specified bits as value bits: that's all integral types other than
16946     // 'bool'.
16947     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16948       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16949           << FieldName << toString(Value, 10)
16950           << (unsigned)TypeWidth;
16951     }
16952   }
16953 
16954   return BitWidth;
16955 }
16956 
16957 /// ActOnField - Each field of a C struct/union is passed into this in order
16958 /// to create a FieldDecl object for it.
16959 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16960                        Declarator &D, Expr *BitfieldWidth) {
16961   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16962                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16963                                /*InitStyle=*/ICIS_NoInit, AS_public);
16964   return Res;
16965 }
16966 
16967 /// HandleField - Analyze a field of a C struct or a C++ data member.
16968 ///
16969 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16970                              SourceLocation DeclStart,
16971                              Declarator &D, Expr *BitWidth,
16972                              InClassInitStyle InitStyle,
16973                              AccessSpecifier AS) {
16974   if (D.isDecompositionDeclarator()) {
16975     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16976     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16977       << Decomp.getSourceRange();
16978     return nullptr;
16979   }
16980 
16981   IdentifierInfo *II = D.getIdentifier();
16982   SourceLocation Loc = DeclStart;
16983   if (II) Loc = D.getIdentifierLoc();
16984 
16985   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16986   QualType T = TInfo->getType();
16987   if (getLangOpts().CPlusPlus) {
16988     CheckExtraCXXDefaultArguments(D);
16989 
16990     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16991                                         UPPC_DataMemberType)) {
16992       D.setInvalidType();
16993       T = Context.IntTy;
16994       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16995     }
16996   }
16997 
16998   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16999 
17000   if (D.getDeclSpec().isInlineSpecified())
17001     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17002         << getLangOpts().CPlusPlus17;
17003   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17004     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17005          diag::err_invalid_thread)
17006       << DeclSpec::getSpecifierName(TSCS);
17007 
17008   // Check to see if this name was declared as a member previously
17009   NamedDecl *PrevDecl = nullptr;
17010   LookupResult Previous(*this, II, Loc, LookupMemberName,
17011                         ForVisibleRedeclaration);
17012   LookupName(Previous, S);
17013   switch (Previous.getResultKind()) {
17014     case LookupResult::Found:
17015     case LookupResult::FoundUnresolvedValue:
17016       PrevDecl = Previous.getAsSingle<NamedDecl>();
17017       break;
17018 
17019     case LookupResult::FoundOverloaded:
17020       PrevDecl = Previous.getRepresentativeDecl();
17021       break;
17022 
17023     case LookupResult::NotFound:
17024     case LookupResult::NotFoundInCurrentInstantiation:
17025     case LookupResult::Ambiguous:
17026       break;
17027   }
17028   Previous.suppressDiagnostics();
17029 
17030   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17031     // Maybe we will complain about the shadowed template parameter.
17032     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17033     // Just pretend that we didn't see the previous declaration.
17034     PrevDecl = nullptr;
17035   }
17036 
17037   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17038     PrevDecl = nullptr;
17039 
17040   bool Mutable
17041     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17042   SourceLocation TSSL = D.getBeginLoc();
17043   FieldDecl *NewFD
17044     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17045                      TSSL, AS, PrevDecl, &D);
17046 
17047   if (NewFD->isInvalidDecl())
17048     Record->setInvalidDecl();
17049 
17050   if (D.getDeclSpec().isModulePrivateSpecified())
17051     NewFD->setModulePrivate();
17052 
17053   if (NewFD->isInvalidDecl() && PrevDecl) {
17054     // Don't introduce NewFD into scope; there's already something
17055     // with the same name in the same scope.
17056   } else if (II) {
17057     PushOnScopeChains(NewFD, S);
17058   } else
17059     Record->addDecl(NewFD);
17060 
17061   return NewFD;
17062 }
17063 
17064 /// Build a new FieldDecl and check its well-formedness.
17065 ///
17066 /// This routine builds a new FieldDecl given the fields name, type,
17067 /// record, etc. \p PrevDecl should refer to any previous declaration
17068 /// with the same name and in the same scope as the field to be
17069 /// created.
17070 ///
17071 /// \returns a new FieldDecl.
17072 ///
17073 /// \todo The Declarator argument is a hack. It will be removed once
17074 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17075                                 TypeSourceInfo *TInfo,
17076                                 RecordDecl *Record, SourceLocation Loc,
17077                                 bool Mutable, Expr *BitWidth,
17078                                 InClassInitStyle InitStyle,
17079                                 SourceLocation TSSL,
17080                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17081                                 Declarator *D) {
17082   IdentifierInfo *II = Name.getAsIdentifierInfo();
17083   bool InvalidDecl = false;
17084   if (D) InvalidDecl = D->isInvalidType();
17085 
17086   // If we receive a broken type, recover by assuming 'int' and
17087   // marking this declaration as invalid.
17088   if (T.isNull() || T->containsErrors()) {
17089     InvalidDecl = true;
17090     T = Context.IntTy;
17091   }
17092 
17093   QualType EltTy = Context.getBaseElementType(T);
17094   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17095     if (RequireCompleteSizedType(Loc, EltTy,
17096                                  diag::err_field_incomplete_or_sizeless)) {
17097       // Fields of incomplete type force their record to be invalid.
17098       Record->setInvalidDecl();
17099       InvalidDecl = true;
17100     } else {
17101       NamedDecl *Def;
17102       EltTy->isIncompleteType(&Def);
17103       if (Def && Def->isInvalidDecl()) {
17104         Record->setInvalidDecl();
17105         InvalidDecl = true;
17106       }
17107     }
17108   }
17109 
17110   // TR 18037 does not allow fields to be declared with address space
17111   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17112       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17113     Diag(Loc, diag::err_field_with_address_space);
17114     Record->setInvalidDecl();
17115     InvalidDecl = true;
17116   }
17117 
17118   if (LangOpts.OpenCL) {
17119     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17120     // used as structure or union field: image, sampler, event or block types.
17121     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17122         T->isBlockPointerType()) {
17123       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17124       Record->setInvalidDecl();
17125       InvalidDecl = true;
17126     }
17127     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17128     // is enabled.
17129     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17130                         "__cl_clang_bitfields", LangOpts)) {
17131       Diag(Loc, diag::err_opencl_bitfields);
17132       InvalidDecl = true;
17133     }
17134   }
17135 
17136   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17137   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17138       T.hasQualifiers()) {
17139     InvalidDecl = true;
17140     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17141   }
17142 
17143   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17144   // than a variably modified type.
17145   if (!InvalidDecl && T->isVariablyModifiedType()) {
17146     if (!tryToFixVariablyModifiedVarType(
17147             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17148       InvalidDecl = true;
17149   }
17150 
17151   // Fields can not have abstract class types
17152   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17153                                              diag::err_abstract_type_in_decl,
17154                                              AbstractFieldType))
17155     InvalidDecl = true;
17156 
17157   bool ZeroWidth = false;
17158   if (InvalidDecl)
17159     BitWidth = nullptr;
17160   // If this is declared as a bit-field, check the bit-field.
17161   if (BitWidth) {
17162     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17163                               &ZeroWidth).get();
17164     if (!BitWidth) {
17165       InvalidDecl = true;
17166       BitWidth = nullptr;
17167       ZeroWidth = false;
17168     }
17169   }
17170 
17171   // Check that 'mutable' is consistent with the type of the declaration.
17172   if (!InvalidDecl && Mutable) {
17173     unsigned DiagID = 0;
17174     if (T->isReferenceType())
17175       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17176                                         : diag::err_mutable_reference;
17177     else if (T.isConstQualified())
17178       DiagID = diag::err_mutable_const;
17179 
17180     if (DiagID) {
17181       SourceLocation ErrLoc = Loc;
17182       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17183         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17184       Diag(ErrLoc, DiagID);
17185       if (DiagID != diag::ext_mutable_reference) {
17186         Mutable = false;
17187         InvalidDecl = true;
17188       }
17189     }
17190   }
17191 
17192   // C++11 [class.union]p8 (DR1460):
17193   //   At most one variant member of a union may have a
17194   //   brace-or-equal-initializer.
17195   if (InitStyle != ICIS_NoInit)
17196     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17197 
17198   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17199                                        BitWidth, Mutable, InitStyle);
17200   if (InvalidDecl)
17201     NewFD->setInvalidDecl();
17202 
17203   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17204     Diag(Loc, diag::err_duplicate_member) << II;
17205     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17206     NewFD->setInvalidDecl();
17207   }
17208 
17209   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17210     if (Record->isUnion()) {
17211       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17212         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17213         if (RDecl->getDefinition()) {
17214           // C++ [class.union]p1: An object of a class with a non-trivial
17215           // constructor, a non-trivial copy constructor, a non-trivial
17216           // destructor, or a non-trivial copy assignment operator
17217           // cannot be a member of a union, nor can an array of such
17218           // objects.
17219           if (CheckNontrivialField(NewFD))
17220             NewFD->setInvalidDecl();
17221         }
17222       }
17223 
17224       // C++ [class.union]p1: If a union contains a member of reference type,
17225       // the program is ill-formed, except when compiling with MSVC extensions
17226       // enabled.
17227       if (EltTy->isReferenceType()) {
17228         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17229                                     diag::ext_union_member_of_reference_type :
17230                                     diag::err_union_member_of_reference_type)
17231           << NewFD->getDeclName() << EltTy;
17232         if (!getLangOpts().MicrosoftExt)
17233           NewFD->setInvalidDecl();
17234       }
17235     }
17236   }
17237 
17238   // FIXME: We need to pass in the attributes given an AST
17239   // representation, not a parser representation.
17240   if (D) {
17241     // FIXME: The current scope is almost... but not entirely... correct here.
17242     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17243 
17244     if (NewFD->hasAttrs())
17245       CheckAlignasUnderalignment(NewFD);
17246   }
17247 
17248   // In auto-retain/release, infer strong retension for fields of
17249   // retainable type.
17250   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17251     NewFD->setInvalidDecl();
17252 
17253   if (T.isObjCGCWeak())
17254     Diag(Loc, diag::warn_attribute_weak_on_field);
17255 
17256   // PPC MMA non-pointer types are not allowed as field types.
17257   if (Context.getTargetInfo().getTriple().isPPC64() &&
17258       CheckPPCMMAType(T, NewFD->getLocation()))
17259     NewFD->setInvalidDecl();
17260 
17261   NewFD->setAccess(AS);
17262   return NewFD;
17263 }
17264 
17265 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17266   assert(FD);
17267   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17268 
17269   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17270     return false;
17271 
17272   QualType EltTy = Context.getBaseElementType(FD->getType());
17273   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17274     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17275     if (RDecl->getDefinition()) {
17276       // We check for copy constructors before constructors
17277       // because otherwise we'll never get complaints about
17278       // copy constructors.
17279 
17280       CXXSpecialMember member = CXXInvalid;
17281       // We're required to check for any non-trivial constructors. Since the
17282       // implicit default constructor is suppressed if there are any
17283       // user-declared constructors, we just need to check that there is a
17284       // trivial default constructor and a trivial copy constructor. (We don't
17285       // worry about move constructors here, since this is a C++98 check.)
17286       if (RDecl->hasNonTrivialCopyConstructor())
17287         member = CXXCopyConstructor;
17288       else if (!RDecl->hasTrivialDefaultConstructor())
17289         member = CXXDefaultConstructor;
17290       else if (RDecl->hasNonTrivialCopyAssignment())
17291         member = CXXCopyAssignment;
17292       else if (RDecl->hasNonTrivialDestructor())
17293         member = CXXDestructor;
17294 
17295       if (member != CXXInvalid) {
17296         if (!getLangOpts().CPlusPlus11 &&
17297             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17298           // Objective-C++ ARC: it is an error to have a non-trivial field of
17299           // a union. However, system headers in Objective-C programs
17300           // occasionally have Objective-C lifetime objects within unions,
17301           // and rather than cause the program to fail, we make those
17302           // members unavailable.
17303           SourceLocation Loc = FD->getLocation();
17304           if (getSourceManager().isInSystemHeader(Loc)) {
17305             if (!FD->hasAttr<UnavailableAttr>())
17306               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17307                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17308             return false;
17309           }
17310         }
17311 
17312         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17313                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17314                diag::err_illegal_union_or_anon_struct_member)
17315           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17316         DiagnoseNontrivial(RDecl, member);
17317         return !getLangOpts().CPlusPlus11;
17318       }
17319     }
17320   }
17321 
17322   return false;
17323 }
17324 
17325 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17326 ///  AST enum value.
17327 static ObjCIvarDecl::AccessControl
17328 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17329   switch (ivarVisibility) {
17330   default: llvm_unreachable("Unknown visitibility kind");
17331   case tok::objc_private: return ObjCIvarDecl::Private;
17332   case tok::objc_public: return ObjCIvarDecl::Public;
17333   case tok::objc_protected: return ObjCIvarDecl::Protected;
17334   case tok::objc_package: return ObjCIvarDecl::Package;
17335   }
17336 }
17337 
17338 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17339 /// in order to create an IvarDecl object for it.
17340 Decl *Sema::ActOnIvar(Scope *S,
17341                                 SourceLocation DeclStart,
17342                                 Declarator &D, Expr *BitfieldWidth,
17343                                 tok::ObjCKeywordKind Visibility) {
17344 
17345   IdentifierInfo *II = D.getIdentifier();
17346   Expr *BitWidth = (Expr*)BitfieldWidth;
17347   SourceLocation Loc = DeclStart;
17348   if (II) Loc = D.getIdentifierLoc();
17349 
17350   // FIXME: Unnamed fields can be handled in various different ways, for
17351   // example, unnamed unions inject all members into the struct namespace!
17352 
17353   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17354   QualType T = TInfo->getType();
17355 
17356   if (BitWidth) {
17357     // 6.7.2.1p3, 6.7.2.1p4
17358     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17359     if (!BitWidth)
17360       D.setInvalidType();
17361   } else {
17362     // Not a bitfield.
17363 
17364     // validate II.
17365 
17366   }
17367   if (T->isReferenceType()) {
17368     Diag(Loc, diag::err_ivar_reference_type);
17369     D.setInvalidType();
17370   }
17371   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17372   // than a variably modified type.
17373   else if (T->isVariablyModifiedType()) {
17374     if (!tryToFixVariablyModifiedVarType(
17375             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17376       D.setInvalidType();
17377   }
17378 
17379   // Get the visibility (access control) for this ivar.
17380   ObjCIvarDecl::AccessControl ac =
17381     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17382                                         : ObjCIvarDecl::None;
17383   // Must set ivar's DeclContext to its enclosing interface.
17384   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17385   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17386     return nullptr;
17387   ObjCContainerDecl *EnclosingContext;
17388   if (ObjCImplementationDecl *IMPDecl =
17389       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17390     if (LangOpts.ObjCRuntime.isFragile()) {
17391     // Case of ivar declared in an implementation. Context is that of its class.
17392       EnclosingContext = IMPDecl->getClassInterface();
17393       assert(EnclosingContext && "Implementation has no class interface!");
17394     }
17395     else
17396       EnclosingContext = EnclosingDecl;
17397   } else {
17398     if (ObjCCategoryDecl *CDecl =
17399         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17400       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17401         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17402         return nullptr;
17403       }
17404     }
17405     EnclosingContext = EnclosingDecl;
17406   }
17407 
17408   // Construct the decl.
17409   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17410                                              DeclStart, Loc, II, T,
17411                                              TInfo, ac, (Expr *)BitfieldWidth);
17412 
17413   if (II) {
17414     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17415                                            ForVisibleRedeclaration);
17416     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17417         && !isa<TagDecl>(PrevDecl)) {
17418       Diag(Loc, diag::err_duplicate_member) << II;
17419       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17420       NewID->setInvalidDecl();
17421     }
17422   }
17423 
17424   // Process attributes attached to the ivar.
17425   ProcessDeclAttributes(S, NewID, D);
17426 
17427   if (D.isInvalidType())
17428     NewID->setInvalidDecl();
17429 
17430   // In ARC, infer 'retaining' for ivars of retainable type.
17431   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17432     NewID->setInvalidDecl();
17433 
17434   if (D.getDeclSpec().isModulePrivateSpecified())
17435     NewID->setModulePrivate();
17436 
17437   if (II) {
17438     // FIXME: When interfaces are DeclContexts, we'll need to add
17439     // these to the interface.
17440     S->AddDecl(NewID);
17441     IdResolver.AddDecl(NewID);
17442   }
17443 
17444   if (LangOpts.ObjCRuntime.isNonFragile() &&
17445       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17446     Diag(Loc, diag::warn_ivars_in_interface);
17447 
17448   return NewID;
17449 }
17450 
17451 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17452 /// class and class extensions. For every class \@interface and class
17453 /// extension \@interface, if the last ivar is a bitfield of any type,
17454 /// then add an implicit `char :0` ivar to the end of that interface.
17455 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17456                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17457   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17458     return;
17459 
17460   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17461   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17462 
17463   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17464     return;
17465   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17466   if (!ID) {
17467     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17468       if (!CD->IsClassExtension())
17469         return;
17470     }
17471     // No need to add this to end of @implementation.
17472     else
17473       return;
17474   }
17475   // All conditions are met. Add a new bitfield to the tail end of ivars.
17476   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17477   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17478 
17479   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17480                               DeclLoc, DeclLoc, nullptr,
17481                               Context.CharTy,
17482                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17483                                                                DeclLoc),
17484                               ObjCIvarDecl::Private, BW,
17485                               true);
17486   AllIvarDecls.push_back(Ivar);
17487 }
17488 
17489 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17490                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17491                        SourceLocation RBrac,
17492                        const ParsedAttributesView &Attrs) {
17493   assert(EnclosingDecl && "missing record or interface decl");
17494 
17495   // If this is an Objective-C @implementation or category and we have
17496   // new fields here we should reset the layout of the interface since
17497   // it will now change.
17498   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17499     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17500     switch (DC->getKind()) {
17501     default: break;
17502     case Decl::ObjCCategory:
17503       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17504       break;
17505     case Decl::ObjCImplementation:
17506       Context.
17507         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17508       break;
17509     }
17510   }
17511 
17512   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17513   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17514 
17515   // Start counting up the number of named members; make sure to include
17516   // members of anonymous structs and unions in the total.
17517   unsigned NumNamedMembers = 0;
17518   if (Record) {
17519     for (const auto *I : Record->decls()) {
17520       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17521         if (IFD->getDeclName())
17522           ++NumNamedMembers;
17523     }
17524   }
17525 
17526   // Verify that all the fields are okay.
17527   SmallVector<FieldDecl*, 32> RecFields;
17528 
17529   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17530        i != end; ++i) {
17531     FieldDecl *FD = cast<FieldDecl>(*i);
17532 
17533     // Get the type for the field.
17534     const Type *FDTy = FD->getType().getTypePtr();
17535 
17536     if (!FD->isAnonymousStructOrUnion()) {
17537       // Remember all fields written by the user.
17538       RecFields.push_back(FD);
17539     }
17540 
17541     // If the field is already invalid for some reason, don't emit more
17542     // diagnostics about it.
17543     if (FD->isInvalidDecl()) {
17544       EnclosingDecl->setInvalidDecl();
17545       continue;
17546     }
17547 
17548     // C99 6.7.2.1p2:
17549     //   A structure or union shall not contain a member with
17550     //   incomplete or function type (hence, a structure shall not
17551     //   contain an instance of itself, but may contain a pointer to
17552     //   an instance of itself), except that the last member of a
17553     //   structure with more than one named member may have incomplete
17554     //   array type; such a structure (and any union containing,
17555     //   possibly recursively, a member that is such a structure)
17556     //   shall not be a member of a structure or an element of an
17557     //   array.
17558     bool IsLastField = (i + 1 == Fields.end());
17559     if (FDTy->isFunctionType()) {
17560       // Field declared as a function.
17561       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17562         << FD->getDeclName();
17563       FD->setInvalidDecl();
17564       EnclosingDecl->setInvalidDecl();
17565       continue;
17566     } else if (FDTy->isIncompleteArrayType() &&
17567                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17568       if (Record) {
17569         // Flexible array member.
17570         // Microsoft and g++ is more permissive regarding flexible array.
17571         // It will accept flexible array in union and also
17572         // as the sole element of a struct/class.
17573         unsigned DiagID = 0;
17574         if (!Record->isUnion() && !IsLastField) {
17575           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17576             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17577           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17578           FD->setInvalidDecl();
17579           EnclosingDecl->setInvalidDecl();
17580           continue;
17581         } else if (Record->isUnion())
17582           DiagID = getLangOpts().MicrosoftExt
17583                        ? diag::ext_flexible_array_union_ms
17584                        : getLangOpts().CPlusPlus
17585                              ? diag::ext_flexible_array_union_gnu
17586                              : diag::err_flexible_array_union;
17587         else if (NumNamedMembers < 1)
17588           DiagID = getLangOpts().MicrosoftExt
17589                        ? diag::ext_flexible_array_empty_aggregate_ms
17590                        : getLangOpts().CPlusPlus
17591                              ? diag::ext_flexible_array_empty_aggregate_gnu
17592                              : diag::err_flexible_array_empty_aggregate;
17593 
17594         if (DiagID)
17595           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17596                                           << Record->getTagKind();
17597         // While the layout of types that contain virtual bases is not specified
17598         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17599         // virtual bases after the derived members.  This would make a flexible
17600         // array member declared at the end of an object not adjacent to the end
17601         // of the type.
17602         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17603           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17604               << FD->getDeclName() << Record->getTagKind();
17605         if (!getLangOpts().C99)
17606           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17607             << FD->getDeclName() << Record->getTagKind();
17608 
17609         // If the element type has a non-trivial destructor, we would not
17610         // implicitly destroy the elements, so disallow it for now.
17611         //
17612         // FIXME: GCC allows this. We should probably either implicitly delete
17613         // the destructor of the containing class, or just allow this.
17614         QualType BaseElem = Context.getBaseElementType(FD->getType());
17615         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17616           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17617             << FD->getDeclName() << FD->getType();
17618           FD->setInvalidDecl();
17619           EnclosingDecl->setInvalidDecl();
17620           continue;
17621         }
17622         // Okay, we have a legal flexible array member at the end of the struct.
17623         Record->setHasFlexibleArrayMember(true);
17624       } else {
17625         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17626         // unless they are followed by another ivar. That check is done
17627         // elsewhere, after synthesized ivars are known.
17628       }
17629     } else if (!FDTy->isDependentType() &&
17630                RequireCompleteSizedType(
17631                    FD->getLocation(), FD->getType(),
17632                    diag::err_field_incomplete_or_sizeless)) {
17633       // Incomplete type
17634       FD->setInvalidDecl();
17635       EnclosingDecl->setInvalidDecl();
17636       continue;
17637     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17638       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17639         // A type which contains a flexible array member is considered to be a
17640         // flexible array member.
17641         Record->setHasFlexibleArrayMember(true);
17642         if (!Record->isUnion()) {
17643           // If this is a struct/class and this is not the last element, reject
17644           // it.  Note that GCC supports variable sized arrays in the middle of
17645           // structures.
17646           if (!IsLastField)
17647             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17648               << FD->getDeclName() << FD->getType();
17649           else {
17650             // We support flexible arrays at the end of structs in
17651             // other structs as an extension.
17652             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17653               << FD->getDeclName();
17654           }
17655         }
17656       }
17657       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17658           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17659                                  diag::err_abstract_type_in_decl,
17660                                  AbstractIvarType)) {
17661         // Ivars can not have abstract class types
17662         FD->setInvalidDecl();
17663       }
17664       if (Record && FDTTy->getDecl()->hasObjectMember())
17665         Record->setHasObjectMember(true);
17666       if (Record && FDTTy->getDecl()->hasVolatileMember())
17667         Record->setHasVolatileMember(true);
17668     } else if (FDTy->isObjCObjectType()) {
17669       /// A field cannot be an Objective-c object
17670       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17671         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17672       QualType T = Context.getObjCObjectPointerType(FD->getType());
17673       FD->setType(T);
17674     } else if (Record && Record->isUnion() &&
17675                FD->getType().hasNonTrivialObjCLifetime() &&
17676                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17677                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17678                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17679                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17680       // For backward compatibility, fields of C unions declared in system
17681       // headers that have non-trivial ObjC ownership qualifications are marked
17682       // as unavailable unless the qualifier is explicit and __strong. This can
17683       // break ABI compatibility between programs compiled with ARC and MRR, but
17684       // is a better option than rejecting programs using those unions under
17685       // ARC.
17686       FD->addAttr(UnavailableAttr::CreateImplicit(
17687           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17688           FD->getLocation()));
17689     } else if (getLangOpts().ObjC &&
17690                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17691                !Record->hasObjectMember()) {
17692       if (FD->getType()->isObjCObjectPointerType() ||
17693           FD->getType().isObjCGCStrong())
17694         Record->setHasObjectMember(true);
17695       else if (Context.getAsArrayType(FD->getType())) {
17696         QualType BaseType = Context.getBaseElementType(FD->getType());
17697         if (BaseType->isRecordType() &&
17698             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17699           Record->setHasObjectMember(true);
17700         else if (BaseType->isObjCObjectPointerType() ||
17701                  BaseType.isObjCGCStrong())
17702                Record->setHasObjectMember(true);
17703       }
17704     }
17705 
17706     if (Record && !getLangOpts().CPlusPlus &&
17707         !shouldIgnoreForRecordTriviality(FD)) {
17708       QualType FT = FD->getType();
17709       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17710         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17711         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17712             Record->isUnion())
17713           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17714       }
17715       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17716       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17717         Record->setNonTrivialToPrimitiveCopy(true);
17718         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17719           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17720       }
17721       if (FT.isDestructedType()) {
17722         Record->setNonTrivialToPrimitiveDestroy(true);
17723         Record->setParamDestroyedInCallee(true);
17724         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17725           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17726       }
17727 
17728       if (const auto *RT = FT->getAs<RecordType>()) {
17729         if (RT->getDecl()->getArgPassingRestrictions() ==
17730             RecordDecl::APK_CanNeverPassInRegs)
17731           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17732       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17733         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17734     }
17735 
17736     if (Record && FD->getType().isVolatileQualified())
17737       Record->setHasVolatileMember(true);
17738     // Keep track of the number of named members.
17739     if (FD->getIdentifier())
17740       ++NumNamedMembers;
17741   }
17742 
17743   // Okay, we successfully defined 'Record'.
17744   if (Record) {
17745     bool Completed = false;
17746     if (CXXRecord) {
17747       if (!CXXRecord->isInvalidDecl()) {
17748         // Set access bits correctly on the directly-declared conversions.
17749         for (CXXRecordDecl::conversion_iterator
17750                I = CXXRecord->conversion_begin(),
17751                E = CXXRecord->conversion_end(); I != E; ++I)
17752           I.setAccess((*I)->getAccess());
17753       }
17754 
17755       // Add any implicitly-declared members to this class.
17756       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17757 
17758       if (!CXXRecord->isDependentType()) {
17759         if (!CXXRecord->isInvalidDecl()) {
17760           // If we have virtual base classes, we may end up finding multiple
17761           // final overriders for a given virtual function. Check for this
17762           // problem now.
17763           if (CXXRecord->getNumVBases()) {
17764             CXXFinalOverriderMap FinalOverriders;
17765             CXXRecord->getFinalOverriders(FinalOverriders);
17766 
17767             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17768                                              MEnd = FinalOverriders.end();
17769                  M != MEnd; ++M) {
17770               for (OverridingMethods::iterator SO = M->second.begin(),
17771                                             SOEnd = M->second.end();
17772                    SO != SOEnd; ++SO) {
17773                 assert(SO->second.size() > 0 &&
17774                        "Virtual function without overriding functions?");
17775                 if (SO->second.size() == 1)
17776                   continue;
17777 
17778                 // C++ [class.virtual]p2:
17779                 //   In a derived class, if a virtual member function of a base
17780                 //   class subobject has more than one final overrider the
17781                 //   program is ill-formed.
17782                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17783                   << (const NamedDecl *)M->first << Record;
17784                 Diag(M->first->getLocation(),
17785                      diag::note_overridden_virtual_function);
17786                 for (OverridingMethods::overriding_iterator
17787                           OM = SO->second.begin(),
17788                        OMEnd = SO->second.end();
17789                      OM != OMEnd; ++OM)
17790                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17791                     << (const NamedDecl *)M->first << OM->Method->getParent();
17792 
17793                 Record->setInvalidDecl();
17794               }
17795             }
17796             CXXRecord->completeDefinition(&FinalOverriders);
17797             Completed = true;
17798           }
17799         }
17800       }
17801     }
17802 
17803     if (!Completed)
17804       Record->completeDefinition();
17805 
17806     // Handle attributes before checking the layout.
17807     ProcessDeclAttributeList(S, Record, Attrs);
17808 
17809     // We may have deferred checking for a deleted destructor. Check now.
17810     if (CXXRecord) {
17811       auto *Dtor = CXXRecord->getDestructor();
17812       if (Dtor && Dtor->isImplicit() &&
17813           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17814         CXXRecord->setImplicitDestructorIsDeleted();
17815         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17816       }
17817     }
17818 
17819     if (Record->hasAttrs()) {
17820       CheckAlignasUnderalignment(Record);
17821 
17822       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17823         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17824                                            IA->getRange(), IA->getBestCase(),
17825                                            IA->getInheritanceModel());
17826     }
17827 
17828     // Check if the structure/union declaration is a type that can have zero
17829     // size in C. For C this is a language extension, for C++ it may cause
17830     // compatibility problems.
17831     bool CheckForZeroSize;
17832     if (!getLangOpts().CPlusPlus) {
17833       CheckForZeroSize = true;
17834     } else {
17835       // For C++ filter out types that cannot be referenced in C code.
17836       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17837       CheckForZeroSize =
17838           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17839           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17840           CXXRecord->isCLike();
17841     }
17842     if (CheckForZeroSize) {
17843       bool ZeroSize = true;
17844       bool IsEmpty = true;
17845       unsigned NonBitFields = 0;
17846       for (RecordDecl::field_iterator I = Record->field_begin(),
17847                                       E = Record->field_end();
17848            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17849         IsEmpty = false;
17850         if (I->isUnnamedBitfield()) {
17851           if (!I->isZeroLengthBitField(Context))
17852             ZeroSize = false;
17853         } else {
17854           ++NonBitFields;
17855           QualType FieldType = I->getType();
17856           if (FieldType->isIncompleteType() ||
17857               !Context.getTypeSizeInChars(FieldType).isZero())
17858             ZeroSize = false;
17859         }
17860       }
17861 
17862       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17863       // allowed in C++, but warn if its declaration is inside
17864       // extern "C" block.
17865       if (ZeroSize) {
17866         Diag(RecLoc, getLangOpts().CPlusPlus ?
17867                          diag::warn_zero_size_struct_union_in_extern_c :
17868                          diag::warn_zero_size_struct_union_compat)
17869           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17870       }
17871 
17872       // Structs without named members are extension in C (C99 6.7.2.1p7),
17873       // but are accepted by GCC.
17874       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17875         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17876                                diag::ext_no_named_members_in_struct_union)
17877           << Record->isUnion();
17878       }
17879     }
17880   } else {
17881     ObjCIvarDecl **ClsFields =
17882       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17883     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17884       ID->setEndOfDefinitionLoc(RBrac);
17885       // Add ivar's to class's DeclContext.
17886       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17887         ClsFields[i]->setLexicalDeclContext(ID);
17888         ID->addDecl(ClsFields[i]);
17889       }
17890       // Must enforce the rule that ivars in the base classes may not be
17891       // duplicates.
17892       if (ID->getSuperClass())
17893         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17894     } else if (ObjCImplementationDecl *IMPDecl =
17895                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17896       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17897       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17898         // Ivar declared in @implementation never belongs to the implementation.
17899         // Only it is in implementation's lexical context.
17900         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17901       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17902       IMPDecl->setIvarLBraceLoc(LBrac);
17903       IMPDecl->setIvarRBraceLoc(RBrac);
17904     } else if (ObjCCategoryDecl *CDecl =
17905                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17906       // case of ivars in class extension; all other cases have been
17907       // reported as errors elsewhere.
17908       // FIXME. Class extension does not have a LocEnd field.
17909       // CDecl->setLocEnd(RBrac);
17910       // Add ivar's to class extension's DeclContext.
17911       // Diagnose redeclaration of private ivars.
17912       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17913       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17914         if (IDecl) {
17915           if (const ObjCIvarDecl *ClsIvar =
17916               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17917             Diag(ClsFields[i]->getLocation(),
17918                  diag::err_duplicate_ivar_declaration);
17919             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17920             continue;
17921           }
17922           for (const auto *Ext : IDecl->known_extensions()) {
17923             if (const ObjCIvarDecl *ClsExtIvar
17924                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17925               Diag(ClsFields[i]->getLocation(),
17926                    diag::err_duplicate_ivar_declaration);
17927               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17928               continue;
17929             }
17930           }
17931         }
17932         ClsFields[i]->setLexicalDeclContext(CDecl);
17933         CDecl->addDecl(ClsFields[i]);
17934       }
17935       CDecl->setIvarLBraceLoc(LBrac);
17936       CDecl->setIvarRBraceLoc(RBrac);
17937     }
17938   }
17939 }
17940 
17941 /// Determine whether the given integral value is representable within
17942 /// the given type T.
17943 static bool isRepresentableIntegerValue(ASTContext &Context,
17944                                         llvm::APSInt &Value,
17945                                         QualType T) {
17946   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17947          "Integral type required!");
17948   unsigned BitWidth = Context.getIntWidth(T);
17949 
17950   if (Value.isUnsigned() || Value.isNonNegative()) {
17951     if (T->isSignedIntegerOrEnumerationType())
17952       --BitWidth;
17953     return Value.getActiveBits() <= BitWidth;
17954   }
17955   return Value.getMinSignedBits() <= BitWidth;
17956 }
17957 
17958 // Given an integral type, return the next larger integral type
17959 // (or a NULL type of no such type exists).
17960 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17961   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17962   // enum checking below.
17963   assert((T->isIntegralType(Context) ||
17964          T->isEnumeralType()) && "Integral type required!");
17965   const unsigned NumTypes = 4;
17966   QualType SignedIntegralTypes[NumTypes] = {
17967     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17968   };
17969   QualType UnsignedIntegralTypes[NumTypes] = {
17970     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17971     Context.UnsignedLongLongTy
17972   };
17973 
17974   unsigned BitWidth = Context.getTypeSize(T);
17975   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17976                                                         : UnsignedIntegralTypes;
17977   for (unsigned I = 0; I != NumTypes; ++I)
17978     if (Context.getTypeSize(Types[I]) > BitWidth)
17979       return Types[I];
17980 
17981   return QualType();
17982 }
17983 
17984 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17985                                           EnumConstantDecl *LastEnumConst,
17986                                           SourceLocation IdLoc,
17987                                           IdentifierInfo *Id,
17988                                           Expr *Val) {
17989   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17990   llvm::APSInt EnumVal(IntWidth);
17991   QualType EltTy;
17992 
17993   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17994     Val = nullptr;
17995 
17996   if (Val)
17997     Val = DefaultLvalueConversion(Val).get();
17998 
17999   if (Val) {
18000     if (Enum->isDependentType() || Val->isTypeDependent() ||
18001         Val->containsErrors())
18002       EltTy = Context.DependentTy;
18003     else {
18004       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18005       // underlying type, but do allow it in all other contexts.
18006       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18007         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18008         // constant-expression in the enumerator-definition shall be a converted
18009         // constant expression of the underlying type.
18010         EltTy = Enum->getIntegerType();
18011         ExprResult Converted =
18012           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18013                                            CCEK_Enumerator);
18014         if (Converted.isInvalid())
18015           Val = nullptr;
18016         else
18017           Val = Converted.get();
18018       } else if (!Val->isValueDependent() &&
18019                  !(Val =
18020                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18021                            .get())) {
18022         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18023       } else {
18024         if (Enum->isComplete()) {
18025           EltTy = Enum->getIntegerType();
18026 
18027           // In Obj-C and Microsoft mode, require the enumeration value to be
18028           // representable in the underlying type of the enumeration. In C++11,
18029           // we perform a non-narrowing conversion as part of converted constant
18030           // expression checking.
18031           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18032             if (Context.getTargetInfo()
18033                     .getTriple()
18034                     .isWindowsMSVCEnvironment()) {
18035               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18036             } else {
18037               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18038             }
18039           }
18040 
18041           // Cast to the underlying type.
18042           Val = ImpCastExprToType(Val, EltTy,
18043                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18044                                                          : CK_IntegralCast)
18045                     .get();
18046         } else if (getLangOpts().CPlusPlus) {
18047           // C++11 [dcl.enum]p5:
18048           //   If the underlying type is not fixed, the type of each enumerator
18049           //   is the type of its initializing value:
18050           //     - If an initializer is specified for an enumerator, the
18051           //       initializing value has the same type as the expression.
18052           EltTy = Val->getType();
18053         } else {
18054           // C99 6.7.2.2p2:
18055           //   The expression that defines the value of an enumeration constant
18056           //   shall be an integer constant expression that has a value
18057           //   representable as an int.
18058 
18059           // Complain if the value is not representable in an int.
18060           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18061             Diag(IdLoc, diag::ext_enum_value_not_int)
18062               << toString(EnumVal, 10) << Val->getSourceRange()
18063               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18064           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18065             // Force the type of the expression to 'int'.
18066             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18067           }
18068           EltTy = Val->getType();
18069         }
18070       }
18071     }
18072   }
18073 
18074   if (!Val) {
18075     if (Enum->isDependentType())
18076       EltTy = Context.DependentTy;
18077     else if (!LastEnumConst) {
18078       // C++0x [dcl.enum]p5:
18079       //   If the underlying type is not fixed, the type of each enumerator
18080       //   is the type of its initializing value:
18081       //     - If no initializer is specified for the first enumerator, the
18082       //       initializing value has an unspecified integral type.
18083       //
18084       // GCC uses 'int' for its unspecified integral type, as does
18085       // C99 6.7.2.2p3.
18086       if (Enum->isFixed()) {
18087         EltTy = Enum->getIntegerType();
18088       }
18089       else {
18090         EltTy = Context.IntTy;
18091       }
18092     } else {
18093       // Assign the last value + 1.
18094       EnumVal = LastEnumConst->getInitVal();
18095       ++EnumVal;
18096       EltTy = LastEnumConst->getType();
18097 
18098       // Check for overflow on increment.
18099       if (EnumVal < LastEnumConst->getInitVal()) {
18100         // C++0x [dcl.enum]p5:
18101         //   If the underlying type is not fixed, the type of each enumerator
18102         //   is the type of its initializing value:
18103         //
18104         //     - Otherwise the type of the initializing value is the same as
18105         //       the type of the initializing value of the preceding enumerator
18106         //       unless the incremented value is not representable in that type,
18107         //       in which case the type is an unspecified integral type
18108         //       sufficient to contain the incremented value. If no such type
18109         //       exists, the program is ill-formed.
18110         QualType T = getNextLargerIntegralType(Context, EltTy);
18111         if (T.isNull() || Enum->isFixed()) {
18112           // There is no integral type larger enough to represent this
18113           // value. Complain, then allow the value to wrap around.
18114           EnumVal = LastEnumConst->getInitVal();
18115           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18116           ++EnumVal;
18117           if (Enum->isFixed())
18118             // When the underlying type is fixed, this is ill-formed.
18119             Diag(IdLoc, diag::err_enumerator_wrapped)
18120               << toString(EnumVal, 10)
18121               << EltTy;
18122           else
18123             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18124               << toString(EnumVal, 10);
18125         } else {
18126           EltTy = T;
18127         }
18128 
18129         // Retrieve the last enumerator's value, extent that type to the
18130         // type that is supposed to be large enough to represent the incremented
18131         // value, then increment.
18132         EnumVal = LastEnumConst->getInitVal();
18133         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18134         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18135         ++EnumVal;
18136 
18137         // If we're not in C++, diagnose the overflow of enumerator values,
18138         // which in C99 means that the enumerator value is not representable in
18139         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18140         // permits enumerator values that are representable in some larger
18141         // integral type.
18142         if (!getLangOpts().CPlusPlus && !T.isNull())
18143           Diag(IdLoc, diag::warn_enum_value_overflow);
18144       } else if (!getLangOpts().CPlusPlus &&
18145                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18146         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18147         Diag(IdLoc, diag::ext_enum_value_not_int)
18148           << toString(EnumVal, 10) << 1;
18149       }
18150     }
18151   }
18152 
18153   if (!EltTy->isDependentType()) {
18154     // Make the enumerator value match the signedness and size of the
18155     // enumerator's type.
18156     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18157     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18158   }
18159 
18160   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18161                                   Val, EnumVal);
18162 }
18163 
18164 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18165                                                 SourceLocation IILoc) {
18166   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18167       !getLangOpts().CPlusPlus)
18168     return SkipBodyInfo();
18169 
18170   // We have an anonymous enum definition. Look up the first enumerator to
18171   // determine if we should merge the definition with an existing one and
18172   // skip the body.
18173   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18174                                          forRedeclarationInCurContext());
18175   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18176   if (!PrevECD)
18177     return SkipBodyInfo();
18178 
18179   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18180   NamedDecl *Hidden;
18181   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18182     SkipBodyInfo Skip;
18183     Skip.Previous = Hidden;
18184     return Skip;
18185   }
18186 
18187   return SkipBodyInfo();
18188 }
18189 
18190 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18191                               SourceLocation IdLoc, IdentifierInfo *Id,
18192                               const ParsedAttributesView &Attrs,
18193                               SourceLocation EqualLoc, Expr *Val) {
18194   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18195   EnumConstantDecl *LastEnumConst =
18196     cast_or_null<EnumConstantDecl>(lastEnumConst);
18197 
18198   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18199   // we find one that is.
18200   S = getNonFieldDeclScope(S);
18201 
18202   // Verify that there isn't already something declared with this name in this
18203   // scope.
18204   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18205   LookupName(R, S);
18206   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18207 
18208   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18209     // Maybe we will complain about the shadowed template parameter.
18210     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18211     // Just pretend that we didn't see the previous declaration.
18212     PrevDecl = nullptr;
18213   }
18214 
18215   // C++ [class.mem]p15:
18216   // If T is the name of a class, then each of the following shall have a name
18217   // different from T:
18218   // - every enumerator of every member of class T that is an unscoped
18219   // enumerated type
18220   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18221     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18222                             DeclarationNameInfo(Id, IdLoc));
18223 
18224   EnumConstantDecl *New =
18225     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18226   if (!New)
18227     return nullptr;
18228 
18229   if (PrevDecl) {
18230     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18231       // Check for other kinds of shadowing not already handled.
18232       CheckShadow(New, PrevDecl, R);
18233     }
18234 
18235     // When in C++, we may get a TagDecl with the same name; in this case the
18236     // enum constant will 'hide' the tag.
18237     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18238            "Received TagDecl when not in C++!");
18239     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18240       if (isa<EnumConstantDecl>(PrevDecl))
18241         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18242       else
18243         Diag(IdLoc, diag::err_redefinition) << Id;
18244       notePreviousDefinition(PrevDecl, IdLoc);
18245       return nullptr;
18246     }
18247   }
18248 
18249   // Process attributes.
18250   ProcessDeclAttributeList(S, New, Attrs);
18251   AddPragmaAttributes(S, New);
18252 
18253   // Register this decl in the current scope stack.
18254   New->setAccess(TheEnumDecl->getAccess());
18255   PushOnScopeChains(New, S);
18256 
18257   ActOnDocumentableDecl(New);
18258 
18259   return New;
18260 }
18261 
18262 // Returns true when the enum initial expression does not trigger the
18263 // duplicate enum warning.  A few common cases are exempted as follows:
18264 // Element2 = Element1
18265 // Element2 = Element1 + 1
18266 // Element2 = Element1 - 1
18267 // Where Element2 and Element1 are from the same enum.
18268 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18269   Expr *InitExpr = ECD->getInitExpr();
18270   if (!InitExpr)
18271     return true;
18272   InitExpr = InitExpr->IgnoreImpCasts();
18273 
18274   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18275     if (!BO->isAdditiveOp())
18276       return true;
18277     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18278     if (!IL)
18279       return true;
18280     if (IL->getValue() != 1)
18281       return true;
18282 
18283     InitExpr = BO->getLHS();
18284   }
18285 
18286   // This checks if the elements are from the same enum.
18287   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18288   if (!DRE)
18289     return true;
18290 
18291   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18292   if (!EnumConstant)
18293     return true;
18294 
18295   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18296       Enum)
18297     return true;
18298 
18299   return false;
18300 }
18301 
18302 // Emits a warning when an element is implicitly set a value that
18303 // a previous element has already been set to.
18304 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18305                                         EnumDecl *Enum, QualType EnumType) {
18306   // Avoid anonymous enums
18307   if (!Enum->getIdentifier())
18308     return;
18309 
18310   // Only check for small enums.
18311   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18312     return;
18313 
18314   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18315     return;
18316 
18317   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18318   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18319 
18320   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18321 
18322   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18323   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18324 
18325   // Use int64_t as a key to avoid needing special handling for map keys.
18326   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18327     llvm::APSInt Val = D->getInitVal();
18328     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18329   };
18330 
18331   DuplicatesVector DupVector;
18332   ValueToVectorMap EnumMap;
18333 
18334   // Populate the EnumMap with all values represented by enum constants without
18335   // an initializer.
18336   for (auto *Element : Elements) {
18337     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18338 
18339     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18340     // this constant.  Skip this enum since it may be ill-formed.
18341     if (!ECD) {
18342       return;
18343     }
18344 
18345     // Constants with initalizers are handled in the next loop.
18346     if (ECD->getInitExpr())
18347       continue;
18348 
18349     // Duplicate values are handled in the next loop.
18350     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18351   }
18352 
18353   if (EnumMap.size() == 0)
18354     return;
18355 
18356   // Create vectors for any values that has duplicates.
18357   for (auto *Element : Elements) {
18358     // The last loop returned if any constant was null.
18359     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18360     if (!ValidDuplicateEnum(ECD, Enum))
18361       continue;
18362 
18363     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18364     if (Iter == EnumMap.end())
18365       continue;
18366 
18367     DeclOrVector& Entry = Iter->second;
18368     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18369       // Ensure constants are different.
18370       if (D == ECD)
18371         continue;
18372 
18373       // Create new vector and push values onto it.
18374       auto Vec = std::make_unique<ECDVector>();
18375       Vec->push_back(D);
18376       Vec->push_back(ECD);
18377 
18378       // Update entry to point to the duplicates vector.
18379       Entry = Vec.get();
18380 
18381       // Store the vector somewhere we can consult later for quick emission of
18382       // diagnostics.
18383       DupVector.emplace_back(std::move(Vec));
18384       continue;
18385     }
18386 
18387     ECDVector *Vec = Entry.get<ECDVector*>();
18388     // Make sure constants are not added more than once.
18389     if (*Vec->begin() == ECD)
18390       continue;
18391 
18392     Vec->push_back(ECD);
18393   }
18394 
18395   // Emit diagnostics.
18396   for (const auto &Vec : DupVector) {
18397     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18398 
18399     // Emit warning for one enum constant.
18400     auto *FirstECD = Vec->front();
18401     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18402       << FirstECD << toString(FirstECD->getInitVal(), 10)
18403       << FirstECD->getSourceRange();
18404 
18405     // Emit one note for each of the remaining enum constants with
18406     // the same value.
18407     for (auto *ECD : llvm::drop_begin(*Vec))
18408       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18409         << ECD << toString(ECD->getInitVal(), 10)
18410         << ECD->getSourceRange();
18411   }
18412 }
18413 
18414 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18415                              bool AllowMask) const {
18416   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18417   assert(ED->isCompleteDefinition() && "expected enum definition");
18418 
18419   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18420   llvm::APInt &FlagBits = R.first->second;
18421 
18422   if (R.second) {
18423     for (auto *E : ED->enumerators()) {
18424       const auto &EVal = E->getInitVal();
18425       // Only single-bit enumerators introduce new flag values.
18426       if (EVal.isPowerOf2())
18427         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18428     }
18429   }
18430 
18431   // A value is in a flag enum if either its bits are a subset of the enum's
18432   // flag bits (the first condition) or we are allowing masks and the same is
18433   // true of its complement (the second condition). When masks are allowed, we
18434   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18435   //
18436   // While it's true that any value could be used as a mask, the assumption is
18437   // that a mask will have all of the insignificant bits set. Anything else is
18438   // likely a logic error.
18439   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18440   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18441 }
18442 
18443 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18444                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18445                          const ParsedAttributesView &Attrs) {
18446   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18447   QualType EnumType = Context.getTypeDeclType(Enum);
18448 
18449   ProcessDeclAttributeList(S, Enum, Attrs);
18450 
18451   if (Enum->isDependentType()) {
18452     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18453       EnumConstantDecl *ECD =
18454         cast_or_null<EnumConstantDecl>(Elements[i]);
18455       if (!ECD) continue;
18456 
18457       ECD->setType(EnumType);
18458     }
18459 
18460     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18461     return;
18462   }
18463 
18464   // TODO: If the result value doesn't fit in an int, it must be a long or long
18465   // long value.  ISO C does not support this, but GCC does as an extension,
18466   // emit a warning.
18467   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18468   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18469   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18470 
18471   // Verify that all the values are okay, compute the size of the values, and
18472   // reverse the list.
18473   unsigned NumNegativeBits = 0;
18474   unsigned NumPositiveBits = 0;
18475 
18476   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18477     EnumConstantDecl *ECD =
18478       cast_or_null<EnumConstantDecl>(Elements[i]);
18479     if (!ECD) continue;  // Already issued a diagnostic.
18480 
18481     const llvm::APSInt &InitVal = ECD->getInitVal();
18482 
18483     // Keep track of the size of positive and negative values.
18484     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18485       NumPositiveBits = std::max(NumPositiveBits,
18486                                  (unsigned)InitVal.getActiveBits());
18487     else
18488       NumNegativeBits = std::max(NumNegativeBits,
18489                                  (unsigned)InitVal.getMinSignedBits());
18490   }
18491 
18492   // Figure out the type that should be used for this enum.
18493   QualType BestType;
18494   unsigned BestWidth;
18495 
18496   // C++0x N3000 [conv.prom]p3:
18497   //   An rvalue of an unscoped enumeration type whose underlying
18498   //   type is not fixed can be converted to an rvalue of the first
18499   //   of the following types that can represent all the values of
18500   //   the enumeration: int, unsigned int, long int, unsigned long
18501   //   int, long long int, or unsigned long long int.
18502   // C99 6.4.4.3p2:
18503   //   An identifier declared as an enumeration constant has type int.
18504   // The C99 rule is modified by a gcc extension
18505   QualType BestPromotionType;
18506 
18507   bool Packed = Enum->hasAttr<PackedAttr>();
18508   // -fshort-enums is the equivalent to specifying the packed attribute on all
18509   // enum definitions.
18510   if (LangOpts.ShortEnums)
18511     Packed = true;
18512 
18513   // If the enum already has a type because it is fixed or dictated by the
18514   // target, promote that type instead of analyzing the enumerators.
18515   if (Enum->isComplete()) {
18516     BestType = Enum->getIntegerType();
18517     if (BestType->isPromotableIntegerType())
18518       BestPromotionType = Context.getPromotedIntegerType(BestType);
18519     else
18520       BestPromotionType = BestType;
18521 
18522     BestWidth = Context.getIntWidth(BestType);
18523   }
18524   else if (NumNegativeBits) {
18525     // If there is a negative value, figure out the smallest integer type (of
18526     // int/long/longlong) that fits.
18527     // If it's packed, check also if it fits a char or a short.
18528     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18529       BestType = Context.SignedCharTy;
18530       BestWidth = CharWidth;
18531     } else if (Packed && NumNegativeBits <= ShortWidth &&
18532                NumPositiveBits < ShortWidth) {
18533       BestType = Context.ShortTy;
18534       BestWidth = ShortWidth;
18535     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18536       BestType = Context.IntTy;
18537       BestWidth = IntWidth;
18538     } else {
18539       BestWidth = Context.getTargetInfo().getLongWidth();
18540 
18541       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18542         BestType = Context.LongTy;
18543       } else {
18544         BestWidth = Context.getTargetInfo().getLongLongWidth();
18545 
18546         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18547           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18548         BestType = Context.LongLongTy;
18549       }
18550     }
18551     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18552   } else {
18553     // If there is no negative value, figure out the smallest type that fits
18554     // all of the enumerator values.
18555     // If it's packed, check also if it fits a char or a short.
18556     if (Packed && NumPositiveBits <= CharWidth) {
18557       BestType = Context.UnsignedCharTy;
18558       BestPromotionType = Context.IntTy;
18559       BestWidth = CharWidth;
18560     } else if (Packed && NumPositiveBits <= ShortWidth) {
18561       BestType = Context.UnsignedShortTy;
18562       BestPromotionType = Context.IntTy;
18563       BestWidth = ShortWidth;
18564     } else if (NumPositiveBits <= IntWidth) {
18565       BestType = Context.UnsignedIntTy;
18566       BestWidth = IntWidth;
18567       BestPromotionType
18568         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18569                            ? Context.UnsignedIntTy : Context.IntTy;
18570     } else if (NumPositiveBits <=
18571                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18572       BestType = Context.UnsignedLongTy;
18573       BestPromotionType
18574         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18575                            ? Context.UnsignedLongTy : Context.LongTy;
18576     } else {
18577       BestWidth = Context.getTargetInfo().getLongLongWidth();
18578       assert(NumPositiveBits <= BestWidth &&
18579              "How could an initializer get larger than ULL?");
18580       BestType = Context.UnsignedLongLongTy;
18581       BestPromotionType
18582         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18583                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18584     }
18585   }
18586 
18587   // Loop over all of the enumerator constants, changing their types to match
18588   // the type of the enum if needed.
18589   for (auto *D : Elements) {
18590     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18591     if (!ECD) continue;  // Already issued a diagnostic.
18592 
18593     // Standard C says the enumerators have int type, but we allow, as an
18594     // extension, the enumerators to be larger than int size.  If each
18595     // enumerator value fits in an int, type it as an int, otherwise type it the
18596     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18597     // that X has type 'int', not 'unsigned'.
18598 
18599     // Determine whether the value fits into an int.
18600     llvm::APSInt InitVal = ECD->getInitVal();
18601 
18602     // If it fits into an integer type, force it.  Otherwise force it to match
18603     // the enum decl type.
18604     QualType NewTy;
18605     unsigned NewWidth;
18606     bool NewSign;
18607     if (!getLangOpts().CPlusPlus &&
18608         !Enum->isFixed() &&
18609         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18610       NewTy = Context.IntTy;
18611       NewWidth = IntWidth;
18612       NewSign = true;
18613     } else if (ECD->getType() == BestType) {
18614       // Already the right type!
18615       if (getLangOpts().CPlusPlus)
18616         // C++ [dcl.enum]p4: Following the closing brace of an
18617         // enum-specifier, each enumerator has the type of its
18618         // enumeration.
18619         ECD->setType(EnumType);
18620       continue;
18621     } else {
18622       NewTy = BestType;
18623       NewWidth = BestWidth;
18624       NewSign = BestType->isSignedIntegerOrEnumerationType();
18625     }
18626 
18627     // Adjust the APSInt value.
18628     InitVal = InitVal.extOrTrunc(NewWidth);
18629     InitVal.setIsSigned(NewSign);
18630     ECD->setInitVal(InitVal);
18631 
18632     // Adjust the Expr initializer and type.
18633     if (ECD->getInitExpr() &&
18634         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18635       ECD->setInitExpr(ImplicitCastExpr::Create(
18636           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18637           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18638     if (getLangOpts().CPlusPlus)
18639       // C++ [dcl.enum]p4: Following the closing brace of an
18640       // enum-specifier, each enumerator has the type of its
18641       // enumeration.
18642       ECD->setType(EnumType);
18643     else
18644       ECD->setType(NewTy);
18645   }
18646 
18647   Enum->completeDefinition(BestType, BestPromotionType,
18648                            NumPositiveBits, NumNegativeBits);
18649 
18650   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18651 
18652   if (Enum->isClosedFlag()) {
18653     for (Decl *D : Elements) {
18654       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18655       if (!ECD) continue;  // Already issued a diagnostic.
18656 
18657       llvm::APSInt InitVal = ECD->getInitVal();
18658       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18659           !IsValueInFlagEnum(Enum, InitVal, true))
18660         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18661           << ECD << Enum;
18662     }
18663   }
18664 
18665   // Now that the enum type is defined, ensure it's not been underaligned.
18666   if (Enum->hasAttrs())
18667     CheckAlignasUnderalignment(Enum);
18668 }
18669 
18670 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18671                                   SourceLocation StartLoc,
18672                                   SourceLocation EndLoc) {
18673   StringLiteral *AsmString = cast<StringLiteral>(expr);
18674 
18675   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18676                                                    AsmString, StartLoc,
18677                                                    EndLoc);
18678   CurContext->addDecl(New);
18679   return New;
18680 }
18681 
18682 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18683                                       IdentifierInfo* AliasName,
18684                                       SourceLocation PragmaLoc,
18685                                       SourceLocation NameLoc,
18686                                       SourceLocation AliasNameLoc) {
18687   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18688                                          LookupOrdinaryName);
18689   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18690                            AttributeCommonInfo::AS_Pragma);
18691   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18692       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18693 
18694   // If a declaration that:
18695   // 1) declares a function or a variable
18696   // 2) has external linkage
18697   // already exists, add a label attribute to it.
18698   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18699     if (isDeclExternC(PrevDecl))
18700       PrevDecl->addAttr(Attr);
18701     else
18702       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18703           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18704   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18705   } else
18706     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18707 }
18708 
18709 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18710                              SourceLocation PragmaLoc,
18711                              SourceLocation NameLoc) {
18712   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18713 
18714   if (PrevDecl) {
18715     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18716   } else {
18717     (void)WeakUndeclaredIdentifiers.insert(
18718       std::pair<IdentifierInfo*,WeakInfo>
18719         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18720   }
18721 }
18722 
18723 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18724                                 IdentifierInfo* AliasName,
18725                                 SourceLocation PragmaLoc,
18726                                 SourceLocation NameLoc,
18727                                 SourceLocation AliasNameLoc) {
18728   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18729                                     LookupOrdinaryName);
18730   WeakInfo W = WeakInfo(Name, NameLoc);
18731 
18732   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18733     if (!PrevDecl->hasAttr<AliasAttr>())
18734       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18735         DeclApplyPragmaWeak(TUScope, ND, W);
18736   } else {
18737     (void)WeakUndeclaredIdentifiers.insert(
18738       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18739   }
18740 }
18741 
18742 Decl *Sema::getObjCDeclContext() const {
18743   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18744 }
18745 
18746 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18747                                                      bool Final) {
18748   assert(FD && "Expected non-null FunctionDecl");
18749 
18750   // SYCL functions can be template, so we check if they have appropriate
18751   // attribute prior to checking if it is a template.
18752   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18753     return FunctionEmissionStatus::Emitted;
18754 
18755   // Templates are emitted when they're instantiated.
18756   if (FD->isDependentContext())
18757     return FunctionEmissionStatus::TemplateDiscarded;
18758 
18759   // Check whether this function is an externally visible definition.
18760   auto IsEmittedForExternalSymbol = [this, FD]() {
18761     // We have to check the GVA linkage of the function's *definition* -- if we
18762     // only have a declaration, we don't know whether or not the function will
18763     // be emitted, because (say) the definition could include "inline".
18764     FunctionDecl *Def = FD->getDefinition();
18765 
18766     return Def && !isDiscardableGVALinkage(
18767                       getASTContext().GetGVALinkageForFunction(Def));
18768   };
18769 
18770   if (LangOpts.OpenMPIsDevice) {
18771     // In OpenMP device mode we will not emit host only functions, or functions
18772     // we don't need due to their linkage.
18773     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18774         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18775     // DevTy may be changed later by
18776     //  #pragma omp declare target to(*) device_type(*).
18777     // Therefore DevTy having no value does not imply host. The emission status
18778     // will be checked again at the end of compilation unit with Final = true.
18779     if (DevTy.hasValue())
18780       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18781         return FunctionEmissionStatus::OMPDiscarded;
18782     // If we have an explicit value for the device type, or we are in a target
18783     // declare context, we need to emit all extern and used symbols.
18784     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18785       if (IsEmittedForExternalSymbol())
18786         return FunctionEmissionStatus::Emitted;
18787     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18788     // we'll omit it.
18789     if (Final)
18790       return FunctionEmissionStatus::OMPDiscarded;
18791   } else if (LangOpts.OpenMP > 45) {
18792     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18793     // function. In 5.0, no_host was introduced which might cause a function to
18794     // be ommitted.
18795     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18796         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18797     if (DevTy.hasValue())
18798       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18799         return FunctionEmissionStatus::OMPDiscarded;
18800   }
18801 
18802   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18803     return FunctionEmissionStatus::Emitted;
18804 
18805   if (LangOpts.CUDA) {
18806     // When compiling for device, host functions are never emitted.  Similarly,
18807     // when compiling for host, device and global functions are never emitted.
18808     // (Technically, we do emit a host-side stub for global functions, but this
18809     // doesn't count for our purposes here.)
18810     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18811     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18812       return FunctionEmissionStatus::CUDADiscarded;
18813     if (!LangOpts.CUDAIsDevice &&
18814         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18815       return FunctionEmissionStatus::CUDADiscarded;
18816 
18817     if (IsEmittedForExternalSymbol())
18818       return FunctionEmissionStatus::Emitted;
18819   }
18820 
18821   // Otherwise, the function is known-emitted if it's in our set of
18822   // known-emitted functions.
18823   return FunctionEmissionStatus::Unknown;
18824 }
18825 
18826 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18827   // Host-side references to a __global__ function refer to the stub, so the
18828   // function itself is never emitted and therefore should not be marked.
18829   // If we have host fn calls kernel fn calls host+device, the HD function
18830   // does not get instantiated on the host. We model this by omitting at the
18831   // call to the kernel from the callgraph. This ensures that, when compiling
18832   // for host, only HD functions actually called from the host get marked as
18833   // known-emitted.
18834   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18835          IdentifyCUDATarget(Callee) == CFT_Global;
18836 }
18837