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/ExprCXX.h"
25 #include "clang/AST/NonTrivialTypeVisitor.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109   std::unique_ptr<CorrectionCandidateCallback> clone() override {
110     return std::make_unique<TypeNameValidatorCCC>(*this);
111   }
112 
113  private:
114   bool AllowInvalidDecl;
115   bool WantClassName;
116   bool AllowTemplates;
117   bool AllowNonTemplates;
118 };
119 
120 } // end anonymous namespace
121 
122 /// Determine whether the token kind starts a simple-type-specifier.
123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124   switch (Kind) {
125   // FIXME: Take into account the current language when deciding whether a
126   // token kind is a valid type specifier
127   case tok::kw_short:
128   case tok::kw_long:
129   case tok::kw___int64:
130   case tok::kw___int128:
131   case tok::kw_signed:
132   case tok::kw_unsigned:
133   case tok::kw_void:
134   case tok::kw_char:
135   case tok::kw_int:
136   case tok::kw_half:
137   case tok::kw_float:
138   case tok::kw_double:
139   case tok::kw__Float16:
140   case tok::kw___float128:
141   case tok::kw_wchar_t:
142   case tok::kw_bool:
143   case tok::kw___underlying_type:
144   case tok::kw___auto_type:
145     return true;
146 
147   case tok::annot_typename:
148   case tok::kw_char16_t:
149   case tok::kw_char32_t:
150   case tok::kw_typeof:
151   case tok::annot_decltype:
152   case tok::kw_decltype:
153     return getLangOpts().CPlusPlus;
154 
155   case tok::kw_char8_t:
156     return getLangOpts().Char8;
157 
158   default:
159     break;
160   }
161 
162   return false;
163 }
164 
165 namespace {
166 enum class UnqualifiedTypeNameLookupResult {
167   NotFound,
168   FoundNonType,
169   FoundType
170 };
171 } // end anonymous namespace
172 
173 /// Tries to perform unqualified lookup of the type decls in bases for
174 /// dependent class.
175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176 /// type decl, \a FoundType if only type decls are found.
177 static UnqualifiedTypeNameLookupResult
178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179                                 SourceLocation NameLoc,
180                                 const CXXRecordDecl *RD) {
181   if (!RD->hasDefinition())
182     return UnqualifiedTypeNameLookupResult::NotFound;
183   // Look for type decls in base classes.
184   UnqualifiedTypeNameLookupResult FoundTypeDecl =
185       UnqualifiedTypeNameLookupResult::NotFound;
186   for (const auto &Base : RD->bases()) {
187     const CXXRecordDecl *BaseRD = nullptr;
188     if (auto *BaseTT = Base.getType()->getAs<TagType>())
189       BaseRD = BaseTT->getAsCXXRecordDecl();
190     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191       // Look for type decls in dependent base classes that have known primary
192       // templates.
193       if (!TST || !TST->isDependentType())
194         continue;
195       auto *TD = TST->getTemplateName().getAsTemplateDecl();
196       if (!TD)
197         continue;
198       if (auto *BasePrimaryTemplate =
199           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201           BaseRD = BasePrimaryTemplate;
202         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203           if (const ClassTemplatePartialSpecializationDecl *PS =
204                   CTD->findPartialSpecialization(Base.getType()))
205             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206               BaseRD = PS;
207         }
208       }
209     }
210     if (BaseRD) {
211       for (NamedDecl *ND : BaseRD->lookup(&II)) {
212         if (!isa<TypeDecl>(ND))
213           return UnqualifiedTypeNameLookupResult::FoundNonType;
214         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215       }
216       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218         case UnqualifiedTypeNameLookupResult::FoundNonType:
219           return UnqualifiedTypeNameLookupResult::FoundNonType;
220         case UnqualifiedTypeNameLookupResult::FoundType:
221           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222           break;
223         case UnqualifiedTypeNameLookupResult::NotFound:
224           break;
225         }
226       }
227     }
228   }
229 
230   return FoundTypeDecl;
231 }
232 
233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234                                                       const IdentifierInfo &II,
235                                                       SourceLocation NameLoc) {
236   // Lookup in the parent class template context, if any.
237   const CXXRecordDecl *RD = nullptr;
238   UnqualifiedTypeNameLookupResult FoundTypeDecl =
239       UnqualifiedTypeNameLookupResult::NotFound;
240   for (DeclContext *DC = S.CurContext;
241        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242        DC = DC->getParent()) {
243     // Look for type decls in dependent base classes that have known primary
244     // templates.
245     RD = dyn_cast<CXXRecordDecl>(DC);
246     if (RD && RD->getDescribedClassTemplate())
247       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248   }
249   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250     return nullptr;
251 
252   // We found some types in dependent base classes.  Recover as if the user
253   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
254   // lookup during template instantiation.
255   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256 
257   ASTContext &Context = S.Context;
258   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259                                           cast<Type>(Context.getRecordType(RD)));
260   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261 
262   CXXScopeSpec SS;
263   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264 
265   TypeLocBuilder Builder;
266   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267   DepTL.setNameLoc(NameLoc);
268   DepTL.setElaboratedKeywordLoc(SourceLocation());
269   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271 }
272 
273 /// If the identifier refers to a type name within this scope,
274 /// return the declaration of that type.
275 ///
276 /// This routine performs ordinary name lookup of the identifier II
277 /// within the given scope, with optional C++ scope specifier SS, to
278 /// determine whether the name refers to a type. If so, returns an
279 /// opaque pointer (actually a QualType) corresponding to that
280 /// type. Otherwise, returns NULL.
281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282                              Scope *S, CXXScopeSpec *SS,
283                              bool isClassName, bool HasTrailingDot,
284                              ParsedType ObjectTypePtr,
285                              bool IsCtorOrDtorName,
286                              bool WantNontrivialTypeSourceInfo,
287                              bool IsClassTemplateDeductionContext,
288                              IdentifierInfo **CorrectedII) {
289   // FIXME: Consider allowing this outside C++1z mode as an extension.
290   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292                               !isClassName && !HasTrailingDot;
293 
294   // Determine where we will perform name lookup.
295   DeclContext *LookupCtx = nullptr;
296   if (ObjectTypePtr) {
297     QualType ObjectType = ObjectTypePtr.get();
298     if (ObjectType->isRecordType())
299       LookupCtx = computeDeclContext(ObjectType);
300   } else if (SS && SS->isNotEmpty()) {
301     LookupCtx = computeDeclContext(*SS, false);
302 
303     if (!LookupCtx) {
304       if (isDependentScopeSpecifier(*SS)) {
305         // C++ [temp.res]p3:
306         //   A qualified-id that refers to a type and in which the
307         //   nested-name-specifier depends on a template-parameter (14.6.2)
308         //   shall be prefixed by the keyword typename to indicate that the
309         //   qualified-id denotes a type, forming an
310         //   elaborated-type-specifier (7.1.5.3).
311         //
312         // We therefore do not perform any name lookup if the result would
313         // refer to a member of an unknown specialization.
314         if (!isClassName && !IsCtorOrDtorName)
315           return nullptr;
316 
317         // We know from the grammar that this name refers to a type,
318         // so build a dependent node to describe the type.
319         if (WantNontrivialTypeSourceInfo)
320           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321 
322         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324                                        II, NameLoc);
325         return ParsedType::make(T);
326       }
327 
328       return nullptr;
329     }
330 
331     if (!LookupCtx->isDependentContext() &&
332         RequireCompleteDeclContext(*SS, LookupCtx))
333       return nullptr;
334   }
335 
336   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337   // lookup for class-names.
338   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339                                       LookupOrdinaryName;
340   LookupResult Result(*this, &II, NameLoc, Kind);
341   if (LookupCtx) {
342     // Perform "qualified" name lookup into the declaration context we
343     // computed, which is either the type of the base of a member access
344     // expression or the declaration context associated with a prior
345     // nested-name-specifier.
346     LookupQualifiedName(Result, LookupCtx);
347 
348     if (ObjectTypePtr && Result.empty()) {
349       // C++ [basic.lookup.classref]p3:
350       //   If the unqualified-id is ~type-name, the type-name is looked up
351       //   in the context of the entire postfix-expression. If the type T of
352       //   the object expression is of a class type C, the type-name is also
353       //   looked up in the scope of class C. At least one of the lookups shall
354       //   find a name that refers to (possibly cv-qualified) T.
355       LookupName(Result, S);
356     }
357   } else {
358     // Perform unqualified name lookup.
359     LookupName(Result, S);
360 
361     // For unqualified lookup in a class template in MSVC mode, look into
362     // dependent base classes where the primary class template is known.
363     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364       if (ParsedType TypeInBase =
365               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366         return TypeInBase;
367     }
368   }
369 
370   NamedDecl *IIDecl = nullptr;
371   switch (Result.getResultKind()) {
372   case LookupResult::NotFound:
373   case LookupResult::NotFoundInCurrentInstantiation:
374     if (CorrectedII) {
375       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376                                AllowDeducedTemplate);
377       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378                                               S, SS, CCC, CTK_ErrorRecovery);
379       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380       TemplateTy Template;
381       bool MemberOfUnknownSpecialization;
382       UnqualifiedId TemplateName;
383       TemplateName.setIdentifier(NewII, NameLoc);
384       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385       CXXScopeSpec NewSS, *NewSSPtr = SS;
386       if (SS && NNS) {
387         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388         NewSSPtr = &NewSS;
389       }
390       if (Correction && (NNS || NewII != &II) &&
391           // Ignore a correction to a template type as the to-be-corrected
392           // identifier is not a template (typo correction for template names
393           // is handled elsewhere).
394           !(getLangOpts().CPlusPlus && NewSSPtr &&
395             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396                            Template, MemberOfUnknownSpecialization))) {
397         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398                                     isClassName, HasTrailingDot, ObjectTypePtr,
399                                     IsCtorOrDtorName,
400                                     WantNontrivialTypeSourceInfo,
401                                     IsClassTemplateDeductionContext);
402         if (Ty) {
403           diagnoseTypo(Correction,
404                        PDiag(diag::err_unknown_type_or_class_name_suggest)
405                          << Result.getLookupName() << isClassName);
406           if (SS && NNS)
407             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408           *CorrectedII = NewII;
409           return Ty;
410         }
411       }
412     }
413     // If typo correction failed or was not performed, fall through
414     LLVM_FALLTHROUGH;
415   case LookupResult::FoundOverloaded:
416   case LookupResult::FoundUnresolvedValue:
417     Result.suppressDiagnostics();
418     return nullptr;
419 
420   case LookupResult::Ambiguous:
421     // Recover from type-hiding ambiguities by hiding the type.  We'll
422     // do the lookup again when looking for an object, and we can
423     // diagnose the error then.  If we don't do this, then the error
424     // about hiding the type will be immediately followed by an error
425     // that only makes sense if the identifier was treated like a type.
426     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427       Result.suppressDiagnostics();
428       return nullptr;
429     }
430 
431     // Look to see if we have a type anywhere in the list of results.
432     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433          Res != ResEnd; ++Res) {
434       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436         if (!IIDecl ||
437             (*Res)->getLocation().getRawEncoding() <
438               IIDecl->getLocation().getRawEncoding())
439           IIDecl = *Res;
440       }
441     }
442 
443     if (!IIDecl) {
444       // None of the entities we found is a type, so there is no way
445       // to even assume that the result is a type. In this case, don't
446       // complain about the ambiguity. The parser will either try to
447       // perform this lookup again (e.g., as an object name), which
448       // will produce the ambiguity, or will complain that it expected
449       // a type name.
450       Result.suppressDiagnostics();
451       return nullptr;
452     }
453 
454     // We found a type within the ambiguous lookup; diagnose the
455     // ambiguity and then return that type. This might be the right
456     // answer, or it might not be, but it suppresses any attempt to
457     // perform the name lookup again.
458     break;
459 
460   case LookupResult::Found:
461     IIDecl = Result.getFoundDecl();
462     break;
463   }
464 
465   assert(IIDecl && "Didn't find decl");
466 
467   QualType T;
468   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469     // C++ [class.qual]p2: A lookup that would find the injected-class-name
470     // instead names the constructors of the class, except when naming a class.
471     // This is ill-formed when we're not actually forming a ctor or dtor name.
472     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475         FoundRD->isInjectedClassName() &&
476         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478           << &II << /*Type*/1;
479 
480     DiagnoseUseOfDecl(IIDecl, NameLoc);
481 
482     T = Context.getTypeDeclType(TD);
483     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486     if (!HasTrailingDot)
487       T = Context.getObjCInterfaceType(IDecl);
488   } else if (AllowDeducedTemplate) {
489     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491                                                        QualType(), false);
492   }
493 
494   if (T.isNull()) {
495     // If it's not plausibly a type, suppress diagnostics.
496     Result.suppressDiagnostics();
497     return nullptr;
498   }
499 
500   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501   // constructor or destructor name (in such a case, the scope specifier
502   // will be attached to the enclosing Expr or Decl node).
503   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504       !isa<ObjCInterfaceDecl>(IIDecl)) {
505     if (WantNontrivialTypeSourceInfo) {
506       // Construct a type with type-source information.
507       TypeLocBuilder Builder;
508       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509 
510       T = getElaboratedType(ETK_None, *SS, T);
511       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512       ElabTL.setElaboratedKeywordLoc(SourceLocation());
513       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515     } else {
516       T = getElaboratedType(ETK_None, *SS, T);
517     }
518   }
519 
520   return ParsedType::make(T);
521 }
522 
523 // Builds a fake NNS for the given decl context.
524 static NestedNameSpecifier *
525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526   for (;; DC = DC->getLookupParent()) {
527     DC = DC->getPrimaryContext();
528     auto *ND = dyn_cast<NamespaceDecl>(DC);
529     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530       return NestedNameSpecifier::Create(Context, nullptr, ND);
531     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533                                          RD->getTypeForDecl());
534     else if (isa<TranslationUnitDecl>(DC))
535       return NestedNameSpecifier::GlobalSpecifier(Context);
536   }
537   llvm_unreachable("something isn't in TU scope?");
538 }
539 
540 /// Find the parent class with dependent bases of the innermost enclosing method
541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542 /// up allowing unqualified dependent type names at class-level, which MSVC
543 /// correctly rejects.
544 static const CXXRecordDecl *
545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547     DC = DC->getPrimaryContext();
548     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549       if (MD->getParent()->hasAnyDependentBases())
550         return MD->getParent();
551   }
552   return nullptr;
553 }
554 
555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556                                           SourceLocation NameLoc,
557                                           bool IsTemplateTypeArg) {
558   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559 
560   NestedNameSpecifier *NNS = nullptr;
561   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562     // If we weren't able to parse a default template argument, delay lookup
563     // until instantiation time by making a non-dependent DependentTypeName. We
564     // pretend we saw a NestedNameSpecifier referring to the current scope, and
565     // lookup is retried.
566     // FIXME: This hurts our diagnostic quality, since we get errors like "no
567     // type named 'Foo' in 'current_namespace'" when the user didn't write any
568     // name specifiers.
569     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571   } else if (const CXXRecordDecl *RD =
572                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573     // Build a DependentNameType that will perform lookup into RD at
574     // instantiation time.
575     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576                                       RD->getTypeForDecl());
577 
578     // Diagnose that this identifier was undeclared, and retry the lookup during
579     // template instantiation.
580     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581                                                                       << RD;
582   } else {
583     // This is not a situation that we should recover from.
584     return ParsedType();
585   }
586 
587   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588 
589   // Build type location information.  We synthesized the qualifier, so we have
590   // to build a fake NestedNameSpecifierLoc.
591   NestedNameSpecifierLocBuilder NNSLocBuilder;
592   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594 
595   TypeLocBuilder Builder;
596   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597   DepTL.setNameLoc(NameLoc);
598   DepTL.setElaboratedKeywordLoc(SourceLocation());
599   DepTL.setQualifierLoc(QualifierLoc);
600   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601 }
602 
603 /// isTagName() - This method is called *for error recovery purposes only*
604 /// to determine if the specified name is a valid tag name ("struct foo").  If
605 /// so, this returns the TST for the tag corresponding to it (TST_enum,
606 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
607 /// cases in C where the user forgot to specify the tag.
608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609   // Do a tag name lookup in this scope.
610   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611   LookupName(R, S, false);
612   R.suppressDiagnostics();
613   if (R.getResultKind() == LookupResult::Found)
614     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615       switch (TD->getTagKind()) {
616       case TTK_Struct: return DeclSpec::TST_struct;
617       case TTK_Interface: return DeclSpec::TST_interface;
618       case TTK_Union:  return DeclSpec::TST_union;
619       case TTK_Class:  return DeclSpec::TST_class;
620       case TTK_Enum:   return DeclSpec::TST_enum;
621       }
622     }
623 
624   return DeclSpec::TST_unspecified;
625 }
626 
627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
629 /// then downgrade the missing typename error to a warning.
630 /// This is needed for MSVC compatibility; Example:
631 /// @code
632 /// template<class T> class A {
633 /// public:
634 ///   typedef int TYPE;
635 /// };
636 /// template<class T> class B : public A<T> {
637 /// public:
638 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
639 /// };
640 /// @endcode
641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642   if (CurContext->isRecord()) {
643     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644       return true;
645 
646     const Type *Ty = SS->getScopeRep()->getAsType();
647 
648     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649     for (const auto &Base : RD->bases())
650       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651         return true;
652     return S->isFunctionPrototypeScope();
653   }
654   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655 }
656 
657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658                                    SourceLocation IILoc,
659                                    Scope *S,
660                                    CXXScopeSpec *SS,
661                                    ParsedType &SuggestedType,
662                                    bool IsTemplateName) {
663   // Don't report typename errors for editor placeholders.
664   if (II->isEditorPlaceholder())
665     return;
666   // We don't have anything to suggest (yet).
667   SuggestedType = nullptr;
668 
669   // There may have been a typo in the name of the type. Look up typo
670   // results, in case we have something that we can suggest.
671   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672                            /*AllowTemplates=*/IsTemplateName,
673                            /*AllowNonTemplates=*/!IsTemplateName);
674   if (TypoCorrection Corrected =
675           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676                       CCC, CTK_ErrorRecovery)) {
677     // FIXME: Support error recovery for the template-name case.
678     bool CanRecover = !IsTemplateName;
679     if (Corrected.isKeyword()) {
680       // We corrected to a keyword.
681       diagnoseTypo(Corrected,
682                    PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                         : diag::err_unknown_typename_suggest)
684                        << II);
685       II = Corrected.getCorrectionAsIdentifierInfo();
686     } else {
687       // We found a similarly-named type or interface; suggest that.
688       if (!SS || !SS->isSet()) {
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName ? diag::err_no_template_suggest
691                                           : diag::err_unknown_typename_suggest)
692                          << II, CanRecover);
693       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696                                 II->getName().equals(CorrectedStr);
697         diagnoseTypo(Corrected,
698                      PDiag(IsTemplateName
699                                ? diag::err_no_member_template_suggest
700                                : diag::err_unknown_nested_typename_suggest)
701                          << II << DC << DroppedSpecifier << SS->getRange(),
702                      CanRecover);
703       } else {
704         llvm_unreachable("could not have corrected a typo here");
705       }
706 
707       if (!CanRecover)
708         return;
709 
710       CXXScopeSpec tmpSS;
711       if (Corrected.getCorrectionSpecifier())
712         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713                           SourceRange(IILoc));
714       // FIXME: Support class template argument deduction here.
715       SuggestedType =
716           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718                       /*IsCtorOrDtorName=*/false,
719                       /*WantNontrivialTypeSourceInfo=*/true);
720     }
721     return;
722   }
723 
724   if (getLangOpts().CPlusPlus && !IsTemplateName) {
725     // See if II is a class template that the user forgot to pass arguments to.
726     UnqualifiedId Name;
727     Name.setIdentifier(II, IILoc);
728     CXXScopeSpec EmptySS;
729     TemplateTy TemplateResult;
730     bool MemberOfUnknownSpecialization;
731     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732                        Name, nullptr, true, TemplateResult,
733                        MemberOfUnknownSpecialization) == TNK_Type_template) {
734       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735       return;
736     }
737   }
738 
739   // FIXME: Should we move the logic that tries to recover from a missing tag
740   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741 
742   if (!SS || (!SS->isSet() && !SS->isInvalid()))
743     Diag(IILoc, IsTemplateName ? diag::err_no_template
744                                : diag::err_unknown_typename)
745         << II;
746   else if (DeclContext *DC = computeDeclContext(*SS, false))
747     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748                                : diag::err_typename_nested_not_found)
749         << II << DC << SS->getRange();
750   else if (isDependentScopeSpecifier(*SS)) {
751     unsigned DiagID = diag::err_typename_missing;
752     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753       DiagID = diag::ext_typename_missing;
754 
755     Diag(SS->getRange().getBegin(), DiagID)
756       << SS->getScopeRep() << II->getName()
757       << SourceRange(SS->getRange().getBegin(), IILoc)
758       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759     SuggestedType = ActOnTypenameType(S, SourceLocation(),
760                                       *SS, *II, IILoc).get();
761   } else {
762     assert(SS && SS->isInvalid() &&
763            "Invalid scope specifier has already been diagnosed");
764   }
765 }
766 
767 /// Determine whether the given result set contains either a type name
768 /// or
769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771                        NextToken.is(tok::less);
772 
773   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775       return true;
776 
777     if (CheckTemplate && isa<TemplateDecl>(*I))
778       return true;
779   }
780 
781   return false;
782 }
783 
784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785                                     Scope *S, CXXScopeSpec &SS,
786                                     IdentifierInfo *&Name,
787                                     SourceLocation NameLoc) {
788   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789   SemaRef.LookupParsedName(R, S, &SS);
790   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791     StringRef FixItTagName;
792     switch (Tag->getTagKind()) {
793       case TTK_Class:
794         FixItTagName = "class ";
795         break;
796 
797       case TTK_Enum:
798         FixItTagName = "enum ";
799         break;
800 
801       case TTK_Struct:
802         FixItTagName = "struct ";
803         break;
804 
805       case TTK_Interface:
806         FixItTagName = "__interface ";
807         break;
808 
809       case TTK_Union:
810         FixItTagName = "union ";
811         break;
812     }
813 
814     StringRef TagName = FixItTagName.drop_back();
815     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818 
819     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820          I != IEnd; ++I)
821       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822         << Name << TagName;
823 
824     // Replace lookup results with just the tag decl.
825     Result.clear(Sema::LookupTagName);
826     SemaRef.LookupParsedName(Result, S, &SS);
827     return true;
828   }
829 
830   return false;
831 }
832 
833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835                                   QualType T, SourceLocation NameLoc) {
836   ASTContext &Context = S.Context;
837 
838   TypeLocBuilder Builder;
839   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840 
841   T = S.getElaboratedType(ETK_None, SS, T);
842   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843   ElabTL.setElaboratedKeywordLoc(SourceLocation());
844   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 }
847 
848 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
849                                             IdentifierInfo *&Name,
850                                             SourceLocation NameLoc,
851                                             const Token &NextToken,
852                                             CorrectionCandidateCallback *CCC) {
853   DeclarationNameInfo NameInfo(Name, NameLoc);
854   ObjCMethodDecl *CurMethod = getCurMethodDecl();
855 
856   assert(NextToken.isNot(tok::coloncolon) &&
857          "parse nested name specifiers before calling ClassifyName");
858   if (getLangOpts().CPlusPlus && SS.isSet() &&
859       isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877 
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
884     if (Ivar.isInvalid())
885       return NameClassification::Error();
886     if (Ivar.isUsable())
887       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
888 
889     // We defer builtin creation until after ivar lookup inside ObjC methods.
890     if (Result.empty())
891       LookupBuiltin(Result);
892   }
893 
894   bool SecondTry = false;
895   bool IsFilteredTemplateName = false;
896 
897 Corrected:
898   switch (Result.getResultKind()) {
899   case LookupResult::NotFound:
900     // If an unqualified-id is followed by a '(', then we have a function
901     // call.
902     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
903       // In C++, this is an ADL-only call.
904       // FIXME: Reference?
905       if (getLangOpts().CPlusPlus)
906         return NameClassification::UndeclaredNonType();
907 
908       // C90 6.3.2.2:
909       //   If the expression that precedes the parenthesized argument list in a
910       //   function call consists solely of an identifier, and if no
911       //   declaration is visible for this identifier, the identifier is
912       //   implicitly declared exactly as if, in the innermost block containing
913       //   the function call, the declaration
914       //
915       //     extern int identifier ();
916       //
917       //   appeared.
918       //
919       // We also allow this in C99 as an extension.
920       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
921         return NameClassification::NonType(D);
922     }
923 
924     if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
925       // In C++20 onwards, this could be an ADL-only call to a function
926       // template, and we're required to assume that this is a template name.
927       //
928       // FIXME: Find a way to still do typo correction in this case.
929       TemplateName Template =
930           Context.getAssumedTemplateName(NameInfo.getName());
931       return NameClassification::UndeclaredTemplate(Template);
932     }
933 
934     // In C, we first see whether there is a tag type by the same name, in
935     // which case it's likely that the user just forgot to write "enum",
936     // "struct", or "union".
937     if (!getLangOpts().CPlusPlus && !SecondTry &&
938         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
939       break;
940     }
941 
942     // Perform typo correction to determine if there is another name that is
943     // close to this name.
944     if (!SecondTry && CCC) {
945       SecondTry = true;
946       if (TypoCorrection Corrected =
947               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
948                           &SS, *CCC, CTK_ErrorRecovery)) {
949         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
950         unsigned QualifiedDiag = diag::err_no_member_suggest;
951 
952         NamedDecl *FirstDecl = Corrected.getFoundDecl();
953         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
954         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
955             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
956           UnqualifiedDiag = diag::err_no_template_suggest;
957           QualifiedDiag = diag::err_no_member_template_suggest;
958         } else if (UnderlyingFirstDecl &&
959                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
960                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
961                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
962           UnqualifiedDiag = diag::err_unknown_typename_suggest;
963           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
964         }
965 
966         if (SS.isEmpty()) {
967           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
968         } else {// FIXME: is this even reachable? Test it.
969           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
970           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
971                                   Name->getName().equals(CorrectedStr);
972           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
973                                     << Name << computeDeclContext(SS, false)
974                                     << DroppedSpecifier << SS.getRange());
975         }
976 
977         // Update the name, so that the caller has the new name.
978         Name = Corrected.getCorrectionAsIdentifierInfo();
979 
980         // Typo correction corrected to a keyword.
981         if (Corrected.isKeyword())
982           return Name;
983 
984         // Also update the LookupResult...
985         // FIXME: This should probably go away at some point
986         Result.clear();
987         Result.setLookupName(Corrected.getCorrection());
988         if (FirstDecl)
989           Result.addDecl(FirstDecl);
990 
991         // If we found an Objective-C instance variable, let
992         // LookupInObjCMethod build the appropriate expression to
993         // reference the ivar.
994         // FIXME: This is a gross hack.
995         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
996           DeclResult R =
997               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
998           if (R.isInvalid())
999             return NameClassification::Error();
1000           if (R.isUsable())
1001             return NameClassification::NonType(Ivar);
1002         }
1003 
1004         goto Corrected;
1005       }
1006     }
1007 
1008     // We failed to correct; just fall through and let the parser deal with it.
1009     Result.suppressDiagnostics();
1010     return NameClassification::Unknown();
1011 
1012   case LookupResult::NotFoundInCurrentInstantiation: {
1013     // We performed name lookup into the current instantiation, and there were
1014     // dependent bases, so we treat this result the same way as any other
1015     // dependent nested-name-specifier.
1016 
1017     // C++ [temp.res]p2:
1018     //   A name used in a template declaration or definition and that is
1019     //   dependent on a template-parameter is assumed not to name a type
1020     //   unless the applicable name lookup finds a type name or the name is
1021     //   qualified by the keyword typename.
1022     //
1023     // FIXME: If the next token is '<', we might want to ask the parser to
1024     // perform some heroics to see if we actually have a
1025     // template-argument-list, which would indicate a missing 'template'
1026     // keyword here.
1027     return NameClassification::DependentNonType();
1028   }
1029 
1030   case LookupResult::Found:
1031   case LookupResult::FoundOverloaded:
1032   case LookupResult::FoundUnresolvedValue:
1033     break;
1034 
1035   case LookupResult::Ambiguous:
1036     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1037         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1038                                       /*AllowDependent=*/false)) {
1039       // C++ [temp.local]p3:
1040       //   A lookup that finds an injected-class-name (10.2) can result in an
1041       //   ambiguity in certain cases (for example, if it is found in more than
1042       //   one base class). If all of the injected-class-names that are found
1043       //   refer to specializations of the same class template, and if the name
1044       //   is followed by a template-argument-list, the reference refers to the
1045       //   class template itself and not a specialization thereof, and is not
1046       //   ambiguous.
1047       //
1048       // This filtering can make an ambiguous result into an unambiguous one,
1049       // so try again after filtering out template names.
1050       FilterAcceptableTemplateNames(Result);
1051       if (!Result.isAmbiguous()) {
1052         IsFilteredTemplateName = true;
1053         break;
1054       }
1055     }
1056 
1057     // Diagnose the ambiguity and return an error.
1058     return NameClassification::Error();
1059   }
1060 
1061   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1062       (IsFilteredTemplateName ||
1063        hasAnyAcceptableTemplateNames(
1064            Result, /*AllowFunctionTemplates=*/true,
1065            /*AllowDependent=*/false,
1066            /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1067                getLangOpts().CPlusPlus2a))) {
1068     // C++ [temp.names]p3:
1069     //   After name lookup (3.4) finds that a name is a template-name or that
1070     //   an operator-function-id or a literal- operator-id refers to a set of
1071     //   overloaded functions any member of which is a function template if
1072     //   this is followed by a <, the < is always taken as the delimiter of a
1073     //   template-argument-list and never as the less-than operator.
1074     // C++2a [temp.names]p2:
1075     //   A name is also considered to refer to a template if it is an
1076     //   unqualified-id followed by a < and name lookup finds either one
1077     //   or more functions or finds nothing.
1078     if (!IsFilteredTemplateName)
1079       FilterAcceptableTemplateNames(Result);
1080 
1081     bool IsFunctionTemplate;
1082     bool IsVarTemplate;
1083     TemplateName Template;
1084     if (Result.end() - Result.begin() > 1) {
1085       IsFunctionTemplate = true;
1086       Template = Context.getOverloadedTemplateName(Result.begin(),
1087                                                    Result.end());
1088     } else if (!Result.empty()) {
1089       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1090           *Result.begin(), /*AllowFunctionTemplates=*/true,
1091           /*AllowDependent=*/false));
1092       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1093       IsVarTemplate = isa<VarTemplateDecl>(TD);
1094 
1095       if (SS.isSet() && !SS.isInvalid())
1096         Template =
1097             Context.getQualifiedTemplateName(SS.getScopeRep(),
1098                                              /*TemplateKeyword=*/false, TD);
1099       else
1100         Template = TemplateName(TD);
1101     } else {
1102       // All results were non-template functions. This is a function template
1103       // name.
1104       IsFunctionTemplate = true;
1105       Template = Context.getAssumedTemplateName(NameInfo.getName());
1106     }
1107 
1108     if (IsFunctionTemplate) {
1109       // Function templates always go through overload resolution, at which
1110       // point we'll perform the various checks (e.g., accessibility) we need
1111       // to based on which function we selected.
1112       Result.suppressDiagnostics();
1113 
1114       return NameClassification::FunctionTemplate(Template);
1115     }
1116 
1117     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1118                          : NameClassification::TypeTemplate(Template);
1119   }
1120 
1121   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1122   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1123     DiagnoseUseOfDecl(Type, NameLoc);
1124     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1125     QualType T = Context.getTypeDeclType(Type);
1126     if (SS.isNotEmpty())
1127       return buildNestedType(*this, SS, T, NameLoc);
1128     return ParsedType::make(T);
1129   }
1130 
1131   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1132   if (!Class) {
1133     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1134     if (ObjCCompatibleAliasDecl *Alias =
1135             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1136       Class = Alias->getClassInterface();
1137   }
1138 
1139   if (Class) {
1140     DiagnoseUseOfDecl(Class, NameLoc);
1141 
1142     if (NextToken.is(tok::period)) {
1143       // Interface. <something> is parsed as a property reference expression.
1144       // Just return "unknown" as a fall-through for now.
1145       Result.suppressDiagnostics();
1146       return NameClassification::Unknown();
1147     }
1148 
1149     QualType T = Context.getObjCInterfaceType(Class);
1150     return ParsedType::make(T);
1151   }
1152 
1153   // We can have a type template here if we're classifying a template argument.
1154   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1155       !isa<VarTemplateDecl>(FirstDecl))
1156     return NameClassification::TypeTemplate(
1157         TemplateName(cast<TemplateDecl>(FirstDecl)));
1158 
1159   // Check for a tag type hidden by a non-type decl in a few cases where it
1160   // seems likely a type is wanted instead of the non-type that was found.
1161   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1162   if ((NextToken.is(tok::identifier) ||
1163        (NextIsOp &&
1164         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1165       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1166     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1167     DiagnoseUseOfDecl(Type, NameLoc);
1168     QualType T = Context.getTypeDeclType(Type);
1169     if (SS.isNotEmpty())
1170       return buildNestedType(*this, SS, T, NameLoc);
1171     return ParsedType::make(T);
1172   }
1173 
1174   // FIXME: This is context-dependent. We need to defer building the member
1175   // expression until the classification is consumed.
1176   if (FirstDecl->isCXXClassMember())
1177     return NameClassification::ContextIndependentExpr(
1178         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1179                                         S));
1180 
1181   // If we already know which single declaration is referenced, just annotate
1182   // that declaration directly.
1183   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1184   if (Result.isSingleResult() && !ADL)
1185     return NameClassification::NonType(Result.getRepresentativeDecl());
1186 
1187   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1188   // context in which we performed classification, so it's safe to do now.
1189   return NameClassification::ContextIndependentExpr(
1190       BuildDeclarationNameExpr(SS, Result, ADL));
1191 }
1192 
1193 ExprResult
1194 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1195                                              SourceLocation NameLoc) {
1196   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1197   CXXScopeSpec SS;
1198   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1199   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1200 }
1201 
1202 ExprResult
1203 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1204                                             IdentifierInfo *Name,
1205                                             SourceLocation NameLoc,
1206                                             bool IsAddressOfOperand) {
1207   DeclarationNameInfo NameInfo(Name, NameLoc);
1208   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1209                                     NameInfo, IsAddressOfOperand,
1210                                     /*TemplateArgs=*/nullptr);
1211 }
1212 
1213 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1214                                               NamedDecl *Found,
1215                                               SourceLocation NameLoc,
1216                                               const Token &NextToken) {
1217   if (getCurMethodDecl() && SS.isEmpty())
1218     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1219       return BuildIvarRefExpr(S, NameLoc, Ivar);
1220 
1221   // Reconstruct the lookup result.
1222   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1223   Result.addDecl(Found);
1224   Result.resolveKind();
1225 
1226   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1227   return BuildDeclarationNameExpr(SS, Result, ADL);
1228 }
1229 
1230 Sema::TemplateNameKindForDiagnostics
1231 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1232   auto *TD = Name.getAsTemplateDecl();
1233   if (!TD)
1234     return TemplateNameKindForDiagnostics::DependentTemplate;
1235   if (isa<ClassTemplateDecl>(TD))
1236     return TemplateNameKindForDiagnostics::ClassTemplate;
1237   if (isa<FunctionTemplateDecl>(TD))
1238     return TemplateNameKindForDiagnostics::FunctionTemplate;
1239   if (isa<VarTemplateDecl>(TD))
1240     return TemplateNameKindForDiagnostics::VarTemplate;
1241   if (isa<TypeAliasTemplateDecl>(TD))
1242     return TemplateNameKindForDiagnostics::AliasTemplate;
1243   if (isa<TemplateTemplateParmDecl>(TD))
1244     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1245   if (isa<ConceptDecl>(TD))
1246     return TemplateNameKindForDiagnostics::Concept;
1247   return TemplateNameKindForDiagnostics::DependentTemplate;
1248 }
1249 
1250 // Determines the context to return to after temporarily entering a
1251 // context.  This depends in an unnecessarily complicated way on the
1252 // exact ordering of callbacks from the parser.
1253 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1254 
1255   // Functions defined inline within classes aren't parsed until we've
1256   // finished parsing the top-level class, so the top-level class is
1257   // the context we'll need to return to.
1258   // A Lambda call operator whose parent is a class must not be treated
1259   // as an inline member function.  A Lambda can be used legally
1260   // either as an in-class member initializer or a default argument.  These
1261   // are parsed once the class has been marked complete and so the containing
1262   // context would be the nested class (when the lambda is defined in one);
1263   // If the class is not complete, then the lambda is being used in an
1264   // ill-formed fashion (such as to specify the width of a bit-field, or
1265   // in an array-bound) - in which case we still want to return the
1266   // lexically containing DC (which could be a nested class).
1267   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1268     DC = DC->getLexicalParent();
1269 
1270     // A function not defined within a class will always return to its
1271     // lexical context.
1272     if (!isa<CXXRecordDecl>(DC))
1273       return DC;
1274 
1275     // A C++ inline method/friend is parsed *after* the topmost class
1276     // it was declared in is fully parsed ("complete");  the topmost
1277     // class is the context we need to return to.
1278     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1279       DC = RD;
1280 
1281     // Return the declaration context of the topmost class the inline method is
1282     // declared in.
1283     return DC;
1284   }
1285 
1286   return DC->getLexicalParent();
1287 }
1288 
1289 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1290   assert(getContainingDC(DC) == CurContext &&
1291       "The next DeclContext should be lexically contained in the current one.");
1292   CurContext = DC;
1293   S->setEntity(DC);
1294 }
1295 
1296 void Sema::PopDeclContext() {
1297   assert(CurContext && "DeclContext imbalance!");
1298 
1299   CurContext = getContainingDC(CurContext);
1300   assert(CurContext && "Popped translation unit!");
1301 }
1302 
1303 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1304                                                                     Decl *D) {
1305   // Unlike PushDeclContext, the context to which we return is not necessarily
1306   // the containing DC of TD, because the new context will be some pre-existing
1307   // TagDecl definition instead of a fresh one.
1308   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1309   CurContext = cast<TagDecl>(D)->getDefinition();
1310   assert(CurContext && "skipping definition of undefined tag");
1311   // Start lookups from the parent of the current context; we don't want to look
1312   // into the pre-existing complete definition.
1313   S->setEntity(CurContext->getLookupParent());
1314   return Result;
1315 }
1316 
1317 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1318   CurContext = static_cast<decltype(CurContext)>(Context);
1319 }
1320 
1321 /// EnterDeclaratorContext - Used when we must lookup names in the context
1322 /// of a declarator's nested name specifier.
1323 ///
1324 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1325   // C++0x [basic.lookup.unqual]p13:
1326   //   A name used in the definition of a static data member of class
1327   //   X (after the qualified-id of the static member) is looked up as
1328   //   if the name was used in a member function of X.
1329   // C++0x [basic.lookup.unqual]p14:
1330   //   If a variable member of a namespace is defined outside of the
1331   //   scope of its namespace then any name used in the definition of
1332   //   the variable member (after the declarator-id) is looked up as
1333   //   if the definition of the variable member occurred in its
1334   //   namespace.
1335   // Both of these imply that we should push a scope whose context
1336   // is the semantic context of the declaration.  We can't use
1337   // PushDeclContext here because that context is not necessarily
1338   // lexically contained in the current context.  Fortunately,
1339   // the containing scope should have the appropriate information.
1340 
1341   assert(!S->getEntity() && "scope already has entity");
1342 
1343 #ifndef NDEBUG
1344   Scope *Ancestor = S->getParent();
1345   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1346   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1347 #endif
1348 
1349   CurContext = DC;
1350   S->setEntity(DC);
1351 }
1352 
1353 void Sema::ExitDeclaratorContext(Scope *S) {
1354   assert(S->getEntity() == CurContext && "Context imbalance!");
1355 
1356   // Switch back to the lexical context.  The safety of this is
1357   // enforced by an assert in EnterDeclaratorContext.
1358   Scope *Ancestor = S->getParent();
1359   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1360   CurContext = Ancestor->getEntity();
1361 
1362   // We don't need to do anything with the scope, which is going to
1363   // disappear.
1364 }
1365 
1366 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1367   // We assume that the caller has already called
1368   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1369   FunctionDecl *FD = D->getAsFunction();
1370   if (!FD)
1371     return;
1372 
1373   // Same implementation as PushDeclContext, but enters the context
1374   // from the lexical parent, rather than the top-level class.
1375   assert(CurContext == FD->getLexicalParent() &&
1376     "The next DeclContext should be lexically contained in the current one.");
1377   CurContext = FD;
1378   S->setEntity(CurContext);
1379 
1380   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1381     ParmVarDecl *Param = FD->getParamDecl(P);
1382     // If the parameter has an identifier, then add it to the scope
1383     if (Param->getIdentifier()) {
1384       S->AddDecl(Param);
1385       IdResolver.AddDecl(Param);
1386     }
1387   }
1388 }
1389 
1390 void Sema::ActOnExitFunctionContext() {
1391   // Same implementation as PopDeclContext, but returns to the lexical parent,
1392   // rather than the top-level class.
1393   assert(CurContext && "DeclContext imbalance!");
1394   CurContext = CurContext->getLexicalParent();
1395   assert(CurContext && "Popped translation unit!");
1396 }
1397 
1398 /// Determine whether we allow overloading of the function
1399 /// PrevDecl with another declaration.
1400 ///
1401 /// This routine determines whether overloading is possible, not
1402 /// whether some new function is actually an overload. It will return
1403 /// true in C++ (where we can always provide overloads) or, as an
1404 /// extension, in C when the previous function is already an
1405 /// overloaded function declaration or has the "overloadable"
1406 /// attribute.
1407 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1408                                        ASTContext &Context,
1409                                        const FunctionDecl *New) {
1410   if (Context.getLangOpts().CPlusPlus)
1411     return true;
1412 
1413   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1414     return true;
1415 
1416   return Previous.getResultKind() == LookupResult::Found &&
1417          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1418           New->hasAttr<OverloadableAttr>());
1419 }
1420 
1421 /// Add this decl to the scope shadowed decl chains.
1422 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1423   // Move up the scope chain until we find the nearest enclosing
1424   // non-transparent context. The declaration will be introduced into this
1425   // scope.
1426   while (S->getEntity() && S->getEntity()->isTransparentContext())
1427     S = S->getParent();
1428 
1429   // Add scoped declarations into their context, so that they can be
1430   // found later. Declarations without a context won't be inserted
1431   // into any context.
1432   if (AddToContext)
1433     CurContext->addDecl(D);
1434 
1435   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1436   // are function-local declarations.
1437   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1438       !D->getDeclContext()->getRedeclContext()->Equals(
1439         D->getLexicalDeclContext()->getRedeclContext()) &&
1440       !D->getLexicalDeclContext()->isFunctionOrMethod())
1441     return;
1442 
1443   // Template instantiations should also not be pushed into scope.
1444   if (isa<FunctionDecl>(D) &&
1445       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1446     return;
1447 
1448   // If this replaces anything in the current scope,
1449   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1450                                IEnd = IdResolver.end();
1451   for (; I != IEnd; ++I) {
1452     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1453       S->RemoveDecl(*I);
1454       IdResolver.RemoveDecl(*I);
1455 
1456       // Should only need to replace one decl.
1457       break;
1458     }
1459   }
1460 
1461   S->AddDecl(D);
1462 
1463   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1464     // Implicitly-generated labels may end up getting generated in an order that
1465     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1466     // the label at the appropriate place in the identifier chain.
1467     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1468       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1469       if (IDC == CurContext) {
1470         if (!S->isDeclScope(*I))
1471           continue;
1472       } else if (IDC->Encloses(CurContext))
1473         break;
1474     }
1475 
1476     IdResolver.InsertDeclAfter(I, D);
1477   } else {
1478     IdResolver.AddDecl(D);
1479   }
1480 }
1481 
1482 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1483                          bool AllowInlineNamespace) {
1484   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1485 }
1486 
1487 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1488   DeclContext *TargetDC = DC->getPrimaryContext();
1489   do {
1490     if (DeclContext *ScopeDC = S->getEntity())
1491       if (ScopeDC->getPrimaryContext() == TargetDC)
1492         return S;
1493   } while ((S = S->getParent()));
1494 
1495   return nullptr;
1496 }
1497 
1498 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1499                                             DeclContext*,
1500                                             ASTContext&);
1501 
1502 /// Filters out lookup results that don't fall within the given scope
1503 /// as determined by isDeclInScope.
1504 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1505                                 bool ConsiderLinkage,
1506                                 bool AllowInlineNamespace) {
1507   LookupResult::Filter F = R.makeFilter();
1508   while (F.hasNext()) {
1509     NamedDecl *D = F.next();
1510 
1511     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1512       continue;
1513 
1514     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1515       continue;
1516 
1517     F.erase();
1518   }
1519 
1520   F.done();
1521 }
1522 
1523 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1524 /// have compatible owning modules.
1525 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1526   // FIXME: The Modules TS is not clear about how friend declarations are
1527   // to be treated. It's not meaningful to have different owning modules for
1528   // linkage in redeclarations of the same entity, so for now allow the
1529   // redeclaration and change the owning modules to match.
1530   if (New->getFriendObjectKind() &&
1531       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1532     New->setLocalOwningModule(Old->getOwningModule());
1533     makeMergedDefinitionVisible(New);
1534     return false;
1535   }
1536 
1537   Module *NewM = New->getOwningModule();
1538   Module *OldM = Old->getOwningModule();
1539 
1540   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1541     NewM = NewM->Parent;
1542   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1543     OldM = OldM->Parent;
1544 
1545   if (NewM == OldM)
1546     return false;
1547 
1548   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1549   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1550   if (NewIsModuleInterface || OldIsModuleInterface) {
1551     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1552     //   if a declaration of D [...] appears in the purview of a module, all
1553     //   other such declarations shall appear in the purview of the same module
1554     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1555       << New
1556       << NewIsModuleInterface
1557       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1558       << OldIsModuleInterface
1559       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1560     Diag(Old->getLocation(), diag::note_previous_declaration);
1561     New->setInvalidDecl();
1562     return true;
1563   }
1564 
1565   return false;
1566 }
1567 
1568 static bool isUsingDecl(NamedDecl *D) {
1569   return isa<UsingShadowDecl>(D) ||
1570          isa<UnresolvedUsingTypenameDecl>(D) ||
1571          isa<UnresolvedUsingValueDecl>(D);
1572 }
1573 
1574 /// Removes using shadow declarations from the lookup results.
1575 static void RemoveUsingDecls(LookupResult &R) {
1576   LookupResult::Filter F = R.makeFilter();
1577   while (F.hasNext())
1578     if (isUsingDecl(F.next()))
1579       F.erase();
1580 
1581   F.done();
1582 }
1583 
1584 /// Check for this common pattern:
1585 /// @code
1586 /// class S {
1587 ///   S(const S&); // DO NOT IMPLEMENT
1588 ///   void operator=(const S&); // DO NOT IMPLEMENT
1589 /// };
1590 /// @endcode
1591 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1592   // FIXME: Should check for private access too but access is set after we get
1593   // the decl here.
1594   if (D->doesThisDeclarationHaveABody())
1595     return false;
1596 
1597   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1598     return CD->isCopyConstructor();
1599   return D->isCopyAssignmentOperator();
1600 }
1601 
1602 // We need this to handle
1603 //
1604 // typedef struct {
1605 //   void *foo() { return 0; }
1606 // } A;
1607 //
1608 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1609 // for example. If 'A', foo will have external linkage. If we have '*A',
1610 // foo will have no linkage. Since we can't know until we get to the end
1611 // of the typedef, this function finds out if D might have non-external linkage.
1612 // Callers should verify at the end of the TU if it D has external linkage or
1613 // not.
1614 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1615   const DeclContext *DC = D->getDeclContext();
1616   while (!DC->isTranslationUnit()) {
1617     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1618       if (!RD->hasNameForLinkage())
1619         return true;
1620     }
1621     DC = DC->getParent();
1622   }
1623 
1624   return !D->isExternallyVisible();
1625 }
1626 
1627 // FIXME: This needs to be refactored; some other isInMainFile users want
1628 // these semantics.
1629 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1630   if (S.TUKind != TU_Complete)
1631     return false;
1632   return S.SourceMgr.isInMainFile(Loc);
1633 }
1634 
1635 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1636   assert(D);
1637 
1638   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1639     return false;
1640 
1641   // Ignore all entities declared within templates, and out-of-line definitions
1642   // of members of class templates.
1643   if (D->getDeclContext()->isDependentContext() ||
1644       D->getLexicalDeclContext()->isDependentContext())
1645     return false;
1646 
1647   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1648     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1649       return false;
1650     // A non-out-of-line declaration of a member specialization was implicitly
1651     // instantiated; it's the out-of-line declaration that we're interested in.
1652     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1653         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1654       return false;
1655 
1656     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1657       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1658         return false;
1659     } else {
1660       // 'static inline' functions are defined in headers; don't warn.
1661       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1662         return false;
1663     }
1664 
1665     if (FD->doesThisDeclarationHaveABody() &&
1666         Context.DeclMustBeEmitted(FD))
1667       return false;
1668   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1669     // Constants and utility variables are defined in headers with internal
1670     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1671     // like "inline".)
1672     if (!isMainFileLoc(*this, VD->getLocation()))
1673       return false;
1674 
1675     if (Context.DeclMustBeEmitted(VD))
1676       return false;
1677 
1678     if (VD->isStaticDataMember() &&
1679         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1680       return false;
1681     if (VD->isStaticDataMember() &&
1682         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1683         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1684       return false;
1685 
1686     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1687       return false;
1688   } else {
1689     return false;
1690   }
1691 
1692   // Only warn for unused decls internal to the translation unit.
1693   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1694   // for inline functions defined in the main source file, for instance.
1695   return mightHaveNonExternalLinkage(D);
1696 }
1697 
1698 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1699   if (!D)
1700     return;
1701 
1702   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1703     const FunctionDecl *First = FD->getFirstDecl();
1704     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1705       return; // First should already be in the vector.
1706   }
1707 
1708   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1709     const VarDecl *First = VD->getFirstDecl();
1710     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1711       return; // First should already be in the vector.
1712   }
1713 
1714   if (ShouldWarnIfUnusedFileScopedDecl(D))
1715     UnusedFileScopedDecls.push_back(D);
1716 }
1717 
1718 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1719   if (D->isInvalidDecl())
1720     return false;
1721 
1722   bool Referenced = false;
1723   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1724     // For a decomposition declaration, warn if none of the bindings are
1725     // referenced, instead of if the variable itself is referenced (which
1726     // it is, by the bindings' expressions).
1727     for (auto *BD : DD->bindings()) {
1728       if (BD->isReferenced()) {
1729         Referenced = true;
1730         break;
1731       }
1732     }
1733   } else if (!D->getDeclName()) {
1734     return false;
1735   } else if (D->isReferenced() || D->isUsed()) {
1736     Referenced = true;
1737   }
1738 
1739   if (Referenced || D->hasAttr<UnusedAttr>() ||
1740       D->hasAttr<ObjCPreciseLifetimeAttr>())
1741     return false;
1742 
1743   if (isa<LabelDecl>(D))
1744     return true;
1745 
1746   // Except for labels, we only care about unused decls that are local to
1747   // functions.
1748   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1749   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1750     // For dependent types, the diagnostic is deferred.
1751     WithinFunction =
1752         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1753   if (!WithinFunction)
1754     return false;
1755 
1756   if (isa<TypedefNameDecl>(D))
1757     return true;
1758 
1759   // White-list anything that isn't a local variable.
1760   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1761     return false;
1762 
1763   // Types of valid local variables should be complete, so this should succeed.
1764   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1765 
1766     // White-list anything with an __attribute__((unused)) type.
1767     const auto *Ty = VD->getType().getTypePtr();
1768 
1769     // Only look at the outermost level of typedef.
1770     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1771       if (TT->getDecl()->hasAttr<UnusedAttr>())
1772         return false;
1773     }
1774 
1775     // If we failed to complete the type for some reason, or if the type is
1776     // dependent, don't diagnose the variable.
1777     if (Ty->isIncompleteType() || Ty->isDependentType())
1778       return false;
1779 
1780     // Look at the element type to ensure that the warning behaviour is
1781     // consistent for both scalars and arrays.
1782     Ty = Ty->getBaseElementTypeUnsafe();
1783 
1784     if (const TagType *TT = Ty->getAs<TagType>()) {
1785       const TagDecl *Tag = TT->getDecl();
1786       if (Tag->hasAttr<UnusedAttr>())
1787         return false;
1788 
1789       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1790         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1791           return false;
1792 
1793         if (const Expr *Init = VD->getInit()) {
1794           if (const ExprWithCleanups *Cleanups =
1795                   dyn_cast<ExprWithCleanups>(Init))
1796             Init = Cleanups->getSubExpr();
1797           const CXXConstructExpr *Construct =
1798             dyn_cast<CXXConstructExpr>(Init);
1799           if (Construct && !Construct->isElidable()) {
1800             CXXConstructorDecl *CD = Construct->getConstructor();
1801             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1802                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1803               return false;
1804           }
1805         }
1806       }
1807     }
1808 
1809     // TODO: __attribute__((unused)) templates?
1810   }
1811 
1812   return true;
1813 }
1814 
1815 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1816                                      FixItHint &Hint) {
1817   if (isa<LabelDecl>(D)) {
1818     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1819         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1820         true);
1821     if (AfterColon.isInvalid())
1822       return;
1823     Hint = FixItHint::CreateRemoval(
1824         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1825   }
1826 }
1827 
1828 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1829   if (D->getTypeForDecl()->isDependentType())
1830     return;
1831 
1832   for (auto *TmpD : D->decls()) {
1833     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1834       DiagnoseUnusedDecl(T);
1835     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1836       DiagnoseUnusedNestedTypedefs(R);
1837   }
1838 }
1839 
1840 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1841 /// unless they are marked attr(unused).
1842 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1843   if (!ShouldDiagnoseUnusedDecl(D))
1844     return;
1845 
1846   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1847     // typedefs can be referenced later on, so the diagnostics are emitted
1848     // at end-of-translation-unit.
1849     UnusedLocalTypedefNameCandidates.insert(TD);
1850     return;
1851   }
1852 
1853   FixItHint Hint;
1854   GenerateFixForUnusedDecl(D, Context, Hint);
1855 
1856   unsigned DiagID;
1857   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1858     DiagID = diag::warn_unused_exception_param;
1859   else if (isa<LabelDecl>(D))
1860     DiagID = diag::warn_unused_label;
1861   else
1862     DiagID = diag::warn_unused_variable;
1863 
1864   Diag(D->getLocation(), DiagID) << D << Hint;
1865 }
1866 
1867 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1868   // Verify that we have no forward references left.  If so, there was a goto
1869   // or address of a label taken, but no definition of it.  Label fwd
1870   // definitions are indicated with a null substmt which is also not a resolved
1871   // MS inline assembly label name.
1872   bool Diagnose = false;
1873   if (L->isMSAsmLabel())
1874     Diagnose = !L->isResolvedMSAsmLabel();
1875   else
1876     Diagnose = L->getStmt() == nullptr;
1877   if (Diagnose)
1878     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1879 }
1880 
1881 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1882   S->mergeNRVOIntoParent();
1883 
1884   if (S->decl_empty()) return;
1885   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1886          "Scope shouldn't contain decls!");
1887 
1888   for (auto *TmpD : S->decls()) {
1889     assert(TmpD && "This decl didn't get pushed??");
1890 
1891     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1892     NamedDecl *D = cast<NamedDecl>(TmpD);
1893 
1894     // Diagnose unused variables in this scope.
1895     if (!S->hasUnrecoverableErrorOccurred()) {
1896       DiagnoseUnusedDecl(D);
1897       if (const auto *RD = dyn_cast<RecordDecl>(D))
1898         DiagnoseUnusedNestedTypedefs(RD);
1899     }
1900 
1901     if (!D->getDeclName()) continue;
1902 
1903     // If this was a forward reference to a label, verify it was defined.
1904     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1905       CheckPoppedLabel(LD, *this);
1906 
1907     // Remove this name from our lexical scope, and warn on it if we haven't
1908     // already.
1909     IdResolver.RemoveDecl(D);
1910     auto ShadowI = ShadowingDecls.find(D);
1911     if (ShadowI != ShadowingDecls.end()) {
1912       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1913         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1914             << D << FD << FD->getParent();
1915         Diag(FD->getLocation(), diag::note_previous_declaration);
1916       }
1917       ShadowingDecls.erase(ShadowI);
1918     }
1919   }
1920 }
1921 
1922 /// Look for an Objective-C class in the translation unit.
1923 ///
1924 /// \param Id The name of the Objective-C class we're looking for. If
1925 /// typo-correction fixes this name, the Id will be updated
1926 /// to the fixed name.
1927 ///
1928 /// \param IdLoc The location of the name in the translation unit.
1929 ///
1930 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1931 /// if there is no class with the given name.
1932 ///
1933 /// \returns The declaration of the named Objective-C class, or NULL if the
1934 /// class could not be found.
1935 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1936                                               SourceLocation IdLoc,
1937                                               bool DoTypoCorrection) {
1938   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1939   // creation from this context.
1940   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1941 
1942   if (!IDecl && DoTypoCorrection) {
1943     // Perform typo correction at the given location, but only if we
1944     // find an Objective-C class name.
1945     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1946     if (TypoCorrection C =
1947             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1948                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1949       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1950       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1951       Id = IDecl->getIdentifier();
1952     }
1953   }
1954   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1955   // This routine must always return a class definition, if any.
1956   if (Def && Def->getDefinition())
1957       Def = Def->getDefinition();
1958   return Def;
1959 }
1960 
1961 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1962 /// from S, where a non-field would be declared. This routine copes
1963 /// with the difference between C and C++ scoping rules in structs and
1964 /// unions. For example, the following code is well-formed in C but
1965 /// ill-formed in C++:
1966 /// @code
1967 /// struct S6 {
1968 ///   enum { BAR } e;
1969 /// };
1970 ///
1971 /// void test_S6() {
1972 ///   struct S6 a;
1973 ///   a.e = BAR;
1974 /// }
1975 /// @endcode
1976 /// For the declaration of BAR, this routine will return a different
1977 /// scope. The scope S will be the scope of the unnamed enumeration
1978 /// within S6. In C++, this routine will return the scope associated
1979 /// with S6, because the enumeration's scope is a transparent
1980 /// context but structures can contain non-field names. In C, this
1981 /// routine will return the translation unit scope, since the
1982 /// enumeration's scope is a transparent context and structures cannot
1983 /// contain non-field names.
1984 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1985   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1986          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1987          (S->isClassScope() && !getLangOpts().CPlusPlus))
1988     S = S->getParent();
1989   return S;
1990 }
1991 
1992 /// Looks up the declaration of "struct objc_super" and
1993 /// saves it for later use in building builtin declaration of
1994 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1995 /// pre-existing declaration exists no action takes place.
1996 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1997                                         IdentifierInfo *II) {
1998   if (!II->isStr("objc_msgSendSuper"))
1999     return;
2000   ASTContext &Context = ThisSema.Context;
2001 
2002   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2003                       SourceLocation(), Sema::LookupTagName);
2004   ThisSema.LookupName(Result, S);
2005   if (Result.getResultKind() == LookupResult::Found)
2006     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2007       Context.setObjCSuperType(Context.getTagDeclType(TD));
2008 }
2009 
2010 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2011                                ASTContext::GetBuiltinTypeError Error) {
2012   switch (Error) {
2013   case ASTContext::GE_None:
2014     return "";
2015   case ASTContext::GE_Missing_type:
2016     return BuiltinInfo.getHeaderName(ID);
2017   case ASTContext::GE_Missing_stdio:
2018     return "stdio.h";
2019   case ASTContext::GE_Missing_setjmp:
2020     return "setjmp.h";
2021   case ASTContext::GE_Missing_ucontext:
2022     return "ucontext.h";
2023   }
2024   llvm_unreachable("unhandled error kind");
2025 }
2026 
2027 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2028 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2029 /// if we're creating this built-in in anticipation of redeclaring the
2030 /// built-in.
2031 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2032                                      Scope *S, bool ForRedeclaration,
2033                                      SourceLocation Loc) {
2034   LookupPredefedObjCSuperType(*this, S, II);
2035 
2036   ASTContext::GetBuiltinTypeError Error;
2037   QualType R = Context.GetBuiltinType(ID, Error);
2038   if (Error) {
2039     if (!ForRedeclaration)
2040       return nullptr;
2041 
2042     // If we have a builtin without an associated type we should not emit a
2043     // warning when we were not able to find a type for it.
2044     if (Error == ASTContext::GE_Missing_type)
2045       return nullptr;
2046 
2047     // If we could not find a type for setjmp it is because the jmp_buf type was
2048     // not defined prior to the setjmp declaration.
2049     if (Error == ASTContext::GE_Missing_setjmp) {
2050       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2051           << Context.BuiltinInfo.getName(ID);
2052       return nullptr;
2053     }
2054 
2055     // Generally, we emit a warning that the declaration requires the
2056     // appropriate header.
2057     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2058         << getHeaderName(Context.BuiltinInfo, ID, Error)
2059         << Context.BuiltinInfo.getName(ID);
2060     return nullptr;
2061   }
2062 
2063   if (!ForRedeclaration &&
2064       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2065        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2066     Diag(Loc, diag::ext_implicit_lib_function_decl)
2067         << Context.BuiltinInfo.getName(ID) << R;
2068     if (Context.BuiltinInfo.getHeaderName(ID) &&
2069         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2070       Diag(Loc, diag::note_include_header_or_declare)
2071           << Context.BuiltinInfo.getHeaderName(ID)
2072           << Context.BuiltinInfo.getName(ID);
2073   }
2074 
2075   if (R.isNull())
2076     return nullptr;
2077 
2078   DeclContext *Parent = Context.getTranslationUnitDecl();
2079   if (getLangOpts().CPlusPlus) {
2080     LinkageSpecDecl *CLinkageDecl =
2081         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2082                                 LinkageSpecDecl::lang_c, false);
2083     CLinkageDecl->setImplicit();
2084     Parent->addDecl(CLinkageDecl);
2085     Parent = CLinkageDecl;
2086   }
2087 
2088   FunctionDecl *New = FunctionDecl::Create(Context,
2089                                            Parent,
2090                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2091                                            SC_Extern,
2092                                            false,
2093                                            R->isFunctionProtoType());
2094   New->setImplicit();
2095 
2096   // Create Decl objects for each parameter, adding them to the
2097   // FunctionDecl.
2098   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2099     SmallVector<ParmVarDecl*, 16> Params;
2100     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2101       ParmVarDecl *parm =
2102           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2103                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2104                               SC_None, nullptr);
2105       parm->setScopeInfo(0, i);
2106       Params.push_back(parm);
2107     }
2108     New->setParams(Params);
2109   }
2110 
2111   AddKnownFunctionAttributes(New);
2112   RegisterLocallyScopedExternCDecl(New, S);
2113 
2114   // TUScope is the translation-unit scope to insert this function into.
2115   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2116   // relate Scopes to DeclContexts, and probably eliminate CurContext
2117   // entirely, but we're not there yet.
2118   DeclContext *SavedContext = CurContext;
2119   CurContext = Parent;
2120   PushOnScopeChains(New, TUScope);
2121   CurContext = SavedContext;
2122   return New;
2123 }
2124 
2125 /// Typedef declarations don't have linkage, but they still denote the same
2126 /// entity if their types are the same.
2127 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2128 /// isSameEntity.
2129 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2130                                                      TypedefNameDecl *Decl,
2131                                                      LookupResult &Previous) {
2132   // This is only interesting when modules are enabled.
2133   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2134     return;
2135 
2136   // Empty sets are uninteresting.
2137   if (Previous.empty())
2138     return;
2139 
2140   LookupResult::Filter Filter = Previous.makeFilter();
2141   while (Filter.hasNext()) {
2142     NamedDecl *Old = Filter.next();
2143 
2144     // Non-hidden declarations are never ignored.
2145     if (S.isVisible(Old))
2146       continue;
2147 
2148     // Declarations of the same entity are not ignored, even if they have
2149     // different linkages.
2150     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2151       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2152                                 Decl->getUnderlyingType()))
2153         continue;
2154 
2155       // If both declarations give a tag declaration a typedef name for linkage
2156       // purposes, then they declare the same entity.
2157       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2158           Decl->getAnonDeclWithTypedefName())
2159         continue;
2160     }
2161 
2162     Filter.erase();
2163   }
2164 
2165   Filter.done();
2166 }
2167 
2168 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2169   QualType OldType;
2170   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2171     OldType = OldTypedef->getUnderlyingType();
2172   else
2173     OldType = Context.getTypeDeclType(Old);
2174   QualType NewType = New->getUnderlyingType();
2175 
2176   if (NewType->isVariablyModifiedType()) {
2177     // Must not redefine a typedef with a variably-modified type.
2178     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2179     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2180       << Kind << NewType;
2181     if (Old->getLocation().isValid())
2182       notePreviousDefinition(Old, New->getLocation());
2183     New->setInvalidDecl();
2184     return true;
2185   }
2186 
2187   if (OldType != NewType &&
2188       !OldType->isDependentType() &&
2189       !NewType->isDependentType() &&
2190       !Context.hasSameType(OldType, NewType)) {
2191     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2192     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2193       << Kind << NewType << OldType;
2194     if (Old->getLocation().isValid())
2195       notePreviousDefinition(Old, New->getLocation());
2196     New->setInvalidDecl();
2197     return true;
2198   }
2199   return false;
2200 }
2201 
2202 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2203 /// same name and scope as a previous declaration 'Old'.  Figure out
2204 /// how to resolve this situation, merging decls or emitting
2205 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2206 ///
2207 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2208                                 LookupResult &OldDecls) {
2209   // If the new decl is known invalid already, don't bother doing any
2210   // merging checks.
2211   if (New->isInvalidDecl()) return;
2212 
2213   // Allow multiple definitions for ObjC built-in typedefs.
2214   // FIXME: Verify the underlying types are equivalent!
2215   if (getLangOpts().ObjC) {
2216     const IdentifierInfo *TypeID = New->getIdentifier();
2217     switch (TypeID->getLength()) {
2218     default: break;
2219     case 2:
2220       {
2221         if (!TypeID->isStr("id"))
2222           break;
2223         QualType T = New->getUnderlyingType();
2224         if (!T->isPointerType())
2225           break;
2226         if (!T->isVoidPointerType()) {
2227           QualType PT = T->castAs<PointerType>()->getPointeeType();
2228           if (!PT->isStructureType())
2229             break;
2230         }
2231         Context.setObjCIdRedefinitionType(T);
2232         // Install the built-in type for 'id', ignoring the current definition.
2233         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2234         return;
2235       }
2236     case 5:
2237       if (!TypeID->isStr("Class"))
2238         break;
2239       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2240       // Install the built-in type for 'Class', ignoring the current definition.
2241       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2242       return;
2243     case 3:
2244       if (!TypeID->isStr("SEL"))
2245         break;
2246       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2247       // Install the built-in type for 'SEL', ignoring the current definition.
2248       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2249       return;
2250     }
2251     // Fall through - the typedef name was not a builtin type.
2252   }
2253 
2254   // Verify the old decl was also a type.
2255   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2256   if (!Old) {
2257     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2258       << New->getDeclName();
2259 
2260     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2261     if (OldD->getLocation().isValid())
2262       notePreviousDefinition(OldD, New->getLocation());
2263 
2264     return New->setInvalidDecl();
2265   }
2266 
2267   // If the old declaration is invalid, just give up here.
2268   if (Old->isInvalidDecl())
2269     return New->setInvalidDecl();
2270 
2271   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2272     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2273     auto *NewTag = New->getAnonDeclWithTypedefName();
2274     NamedDecl *Hidden = nullptr;
2275     if (OldTag && NewTag &&
2276         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2277         !hasVisibleDefinition(OldTag, &Hidden)) {
2278       // There is a definition of this tag, but it is not visible. Use it
2279       // instead of our tag.
2280       New->setTypeForDecl(OldTD->getTypeForDecl());
2281       if (OldTD->isModed())
2282         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2283                                     OldTD->getUnderlyingType());
2284       else
2285         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2286 
2287       // Make the old tag definition visible.
2288       makeMergedDefinitionVisible(Hidden);
2289 
2290       // If this was an unscoped enumeration, yank all of its enumerators
2291       // out of the scope.
2292       if (isa<EnumDecl>(NewTag)) {
2293         Scope *EnumScope = getNonFieldDeclScope(S);
2294         for (auto *D : NewTag->decls()) {
2295           auto *ED = cast<EnumConstantDecl>(D);
2296           assert(EnumScope->isDeclScope(ED));
2297           EnumScope->RemoveDecl(ED);
2298           IdResolver.RemoveDecl(ED);
2299           ED->getLexicalDeclContext()->removeDecl(ED);
2300         }
2301       }
2302     }
2303   }
2304 
2305   // If the typedef types are not identical, reject them in all languages and
2306   // with any extensions enabled.
2307   if (isIncompatibleTypedef(Old, New))
2308     return;
2309 
2310   // The types match.  Link up the redeclaration chain and merge attributes if
2311   // the old declaration was a typedef.
2312   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2313     New->setPreviousDecl(Typedef);
2314     mergeDeclAttributes(New, Old);
2315   }
2316 
2317   if (getLangOpts().MicrosoftExt)
2318     return;
2319 
2320   if (getLangOpts().CPlusPlus) {
2321     // C++ [dcl.typedef]p2:
2322     //   In a given non-class scope, a typedef specifier can be used to
2323     //   redefine the name of any type declared in that scope to refer
2324     //   to the type to which it already refers.
2325     if (!isa<CXXRecordDecl>(CurContext))
2326       return;
2327 
2328     // C++0x [dcl.typedef]p4:
2329     //   In a given class scope, a typedef specifier can be used to redefine
2330     //   any class-name declared in that scope that is not also a typedef-name
2331     //   to refer to the type to which it already refers.
2332     //
2333     // This wording came in via DR424, which was a correction to the
2334     // wording in DR56, which accidentally banned code like:
2335     //
2336     //   struct S {
2337     //     typedef struct A { } A;
2338     //   };
2339     //
2340     // in the C++03 standard. We implement the C++0x semantics, which
2341     // allow the above but disallow
2342     //
2343     //   struct S {
2344     //     typedef int I;
2345     //     typedef int I;
2346     //   };
2347     //
2348     // since that was the intent of DR56.
2349     if (!isa<TypedefNameDecl>(Old))
2350       return;
2351 
2352     Diag(New->getLocation(), diag::err_redefinition)
2353       << New->getDeclName();
2354     notePreviousDefinition(Old, New->getLocation());
2355     return New->setInvalidDecl();
2356   }
2357 
2358   // Modules always permit redefinition of typedefs, as does C11.
2359   if (getLangOpts().Modules || getLangOpts().C11)
2360     return;
2361 
2362   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2363   // is normally mapped to an error, but can be controlled with
2364   // -Wtypedef-redefinition.  If either the original or the redefinition is
2365   // in a system header, don't emit this for compatibility with GCC.
2366   if (getDiagnostics().getSuppressSystemWarnings() &&
2367       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2368       (Old->isImplicit() ||
2369        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2370        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2371     return;
2372 
2373   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2374     << New->getDeclName();
2375   notePreviousDefinition(Old, New->getLocation());
2376 }
2377 
2378 /// DeclhasAttr - returns true if decl Declaration already has the target
2379 /// attribute.
2380 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2381   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2382   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2383   for (const auto *i : D->attrs())
2384     if (i->getKind() == A->getKind()) {
2385       if (Ann) {
2386         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2387           return true;
2388         continue;
2389       }
2390       // FIXME: Don't hardcode this check
2391       if (OA && isa<OwnershipAttr>(i))
2392         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2393       return true;
2394     }
2395 
2396   return false;
2397 }
2398 
2399 static bool isAttributeTargetADefinition(Decl *D) {
2400   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2401     return VD->isThisDeclarationADefinition();
2402   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2403     return TD->isCompleteDefinition() || TD->isBeingDefined();
2404   return true;
2405 }
2406 
2407 /// Merge alignment attributes from \p Old to \p New, taking into account the
2408 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2409 ///
2410 /// \return \c true if any attributes were added to \p New.
2411 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2412   // Look for alignas attributes on Old, and pick out whichever attribute
2413   // specifies the strictest alignment requirement.
2414   AlignedAttr *OldAlignasAttr = nullptr;
2415   AlignedAttr *OldStrictestAlignAttr = nullptr;
2416   unsigned OldAlign = 0;
2417   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2418     // FIXME: We have no way of representing inherited dependent alignments
2419     // in a case like:
2420     //   template<int A, int B> struct alignas(A) X;
2421     //   template<int A, int B> struct alignas(B) X {};
2422     // For now, we just ignore any alignas attributes which are not on the
2423     // definition in such a case.
2424     if (I->isAlignmentDependent())
2425       return false;
2426 
2427     if (I->isAlignas())
2428       OldAlignasAttr = I;
2429 
2430     unsigned Align = I->getAlignment(S.Context);
2431     if (Align > OldAlign) {
2432       OldAlign = Align;
2433       OldStrictestAlignAttr = I;
2434     }
2435   }
2436 
2437   // Look for alignas attributes on New.
2438   AlignedAttr *NewAlignasAttr = nullptr;
2439   unsigned NewAlign = 0;
2440   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2441     if (I->isAlignmentDependent())
2442       return false;
2443 
2444     if (I->isAlignas())
2445       NewAlignasAttr = I;
2446 
2447     unsigned Align = I->getAlignment(S.Context);
2448     if (Align > NewAlign)
2449       NewAlign = Align;
2450   }
2451 
2452   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2453     // Both declarations have 'alignas' attributes. We require them to match.
2454     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2455     // fall short. (If two declarations both have alignas, they must both match
2456     // every definition, and so must match each other if there is a definition.)
2457 
2458     // If either declaration only contains 'alignas(0)' specifiers, then it
2459     // specifies the natural alignment for the type.
2460     if (OldAlign == 0 || NewAlign == 0) {
2461       QualType Ty;
2462       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2463         Ty = VD->getType();
2464       else
2465         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2466 
2467       if (OldAlign == 0)
2468         OldAlign = S.Context.getTypeAlign(Ty);
2469       if (NewAlign == 0)
2470         NewAlign = S.Context.getTypeAlign(Ty);
2471     }
2472 
2473     if (OldAlign != NewAlign) {
2474       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2475         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2476         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2477       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2478     }
2479   }
2480 
2481   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2482     // C++11 [dcl.align]p6:
2483     //   if any declaration of an entity has an alignment-specifier,
2484     //   every defining declaration of that entity shall specify an
2485     //   equivalent alignment.
2486     // C11 6.7.5/7:
2487     //   If the definition of an object does not have an alignment
2488     //   specifier, any other declaration of that object shall also
2489     //   have no alignment specifier.
2490     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2491       << OldAlignasAttr;
2492     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2493       << OldAlignasAttr;
2494   }
2495 
2496   bool AnyAdded = false;
2497 
2498   // Ensure we have an attribute representing the strictest alignment.
2499   if (OldAlign > NewAlign) {
2500     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2501     Clone->setInherited(true);
2502     New->addAttr(Clone);
2503     AnyAdded = true;
2504   }
2505 
2506   // Ensure we have an alignas attribute if the old declaration had one.
2507   if (OldAlignasAttr && !NewAlignasAttr &&
2508       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2509     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2510     Clone->setInherited(true);
2511     New->addAttr(Clone);
2512     AnyAdded = true;
2513   }
2514 
2515   return AnyAdded;
2516 }
2517 
2518 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2519                                const InheritableAttr *Attr,
2520                                Sema::AvailabilityMergeKind AMK) {
2521   // This function copies an attribute Attr from a previous declaration to the
2522   // new declaration D if the new declaration doesn't itself have that attribute
2523   // yet or if that attribute allows duplicates.
2524   // If you're adding a new attribute that requires logic different from
2525   // "use explicit attribute on decl if present, else use attribute from
2526   // previous decl", for example if the attribute needs to be consistent
2527   // between redeclarations, you need to call a custom merge function here.
2528   InheritableAttr *NewAttr = nullptr;
2529   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2530     NewAttr = S.mergeAvailabilityAttr(
2531         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2532         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2533         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2534         AA->getPriority());
2535   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2536     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2537   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2538     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2539   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2540     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2541   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2542     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2543   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2544     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2545                                 FA->getFirstArg());
2546   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2547     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2548   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2549     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2550   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2551     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2552                                        IA->getSemanticSpelling());
2553   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2554     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2555                                       &S.Context.Idents.get(AA->getSpelling()));
2556   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2557            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2558             isa<CUDAGlobalAttr>(Attr))) {
2559     // CUDA target attributes are part of function signature for
2560     // overloading purposes and must not be merged.
2561     return false;
2562   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2563     NewAttr = S.mergeMinSizeAttr(D, *MA);
2564   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2565     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2566   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2567     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2568   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2569     NewAttr = S.mergeCommonAttr(D, *CommonA);
2570   else if (isa<AlignedAttr>(Attr))
2571     // AlignedAttrs are handled separately, because we need to handle all
2572     // such attributes on a declaration at the same time.
2573     NewAttr = nullptr;
2574   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2575            (AMK == Sema::AMK_Override ||
2576             AMK == Sema::AMK_ProtocolImplementation))
2577     NewAttr = nullptr;
2578   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2579     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2580   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2581     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2582   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2583     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2584   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2585     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2586 
2587   if (NewAttr) {
2588     NewAttr->setInherited(true);
2589     D->addAttr(NewAttr);
2590     if (isa<MSInheritanceAttr>(NewAttr))
2591       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2592     return true;
2593   }
2594 
2595   return false;
2596 }
2597 
2598 static const NamedDecl *getDefinition(const Decl *D) {
2599   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2600     return TD->getDefinition();
2601   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2602     const VarDecl *Def = VD->getDefinition();
2603     if (Def)
2604       return Def;
2605     return VD->getActingDefinition();
2606   }
2607   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2608     return FD->getDefinition();
2609   return nullptr;
2610 }
2611 
2612 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2613   for (const auto *Attribute : D->attrs())
2614     if (Attribute->getKind() == Kind)
2615       return true;
2616   return false;
2617 }
2618 
2619 /// checkNewAttributesAfterDef - If we already have a definition, check that
2620 /// there are no new attributes in this declaration.
2621 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2622   if (!New->hasAttrs())
2623     return;
2624 
2625   const NamedDecl *Def = getDefinition(Old);
2626   if (!Def || Def == New)
2627     return;
2628 
2629   AttrVec &NewAttributes = New->getAttrs();
2630   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2631     const Attr *NewAttribute = NewAttributes[I];
2632 
2633     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2634       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2635         Sema::SkipBodyInfo SkipBody;
2636         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2637 
2638         // If we're skipping this definition, drop the "alias" attribute.
2639         if (SkipBody.ShouldSkip) {
2640           NewAttributes.erase(NewAttributes.begin() + I);
2641           --E;
2642           continue;
2643         }
2644       } else {
2645         VarDecl *VD = cast<VarDecl>(New);
2646         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2647                                 VarDecl::TentativeDefinition
2648                             ? diag::err_alias_after_tentative
2649                             : diag::err_redefinition;
2650         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2651         if (Diag == diag::err_redefinition)
2652           S.notePreviousDefinition(Def, VD->getLocation());
2653         else
2654           S.Diag(Def->getLocation(), diag::note_previous_definition);
2655         VD->setInvalidDecl();
2656       }
2657       ++I;
2658       continue;
2659     }
2660 
2661     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2662       // Tentative definitions are only interesting for the alias check above.
2663       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2664         ++I;
2665         continue;
2666       }
2667     }
2668 
2669     if (hasAttribute(Def, NewAttribute->getKind())) {
2670       ++I;
2671       continue; // regular attr merging will take care of validating this.
2672     }
2673 
2674     if (isa<C11NoReturnAttr>(NewAttribute)) {
2675       // C's _Noreturn is allowed to be added to a function after it is defined.
2676       ++I;
2677       continue;
2678     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2679       if (AA->isAlignas()) {
2680         // C++11 [dcl.align]p6:
2681         //   if any declaration of an entity has an alignment-specifier,
2682         //   every defining declaration of that entity shall specify an
2683         //   equivalent alignment.
2684         // C11 6.7.5/7:
2685         //   If the definition of an object does not have an alignment
2686         //   specifier, any other declaration of that object shall also
2687         //   have no alignment specifier.
2688         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2689           << AA;
2690         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2691           << AA;
2692         NewAttributes.erase(NewAttributes.begin() + I);
2693         --E;
2694         continue;
2695       }
2696     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2697                cast<VarDecl>(New)->isInline() &&
2698                !cast<VarDecl>(New)->isInlineSpecified()) {
2699       // Don't warn about applying selectany to implicitly inline variables.
2700       // Older compilers and language modes would require the use of selectany
2701       // to make such variables inline, and it would have no effect if we
2702       // honored it.
2703       ++I;
2704       continue;
2705     }
2706 
2707     S.Diag(NewAttribute->getLocation(),
2708            diag::warn_attribute_precede_definition);
2709     S.Diag(Def->getLocation(), diag::note_previous_definition);
2710     NewAttributes.erase(NewAttributes.begin() + I);
2711     --E;
2712   }
2713 }
2714 
2715 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2716                                      const ConstInitAttr *CIAttr,
2717                                      bool AttrBeforeInit) {
2718   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2719 
2720   // Figure out a good way to write this specifier on the old declaration.
2721   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2722   // enough of the attribute list spelling information to extract that without
2723   // heroics.
2724   std::string SuitableSpelling;
2725   if (S.getLangOpts().CPlusPlus2a)
2726     SuitableSpelling =
2727         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2728   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2729     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2730         InsertLoc,
2731         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2732          tok::coloncolon,
2733          S.PP.getIdentifierInfo("require_constant_initialization"),
2734          tok::r_square, tok::r_square});
2735   if (SuitableSpelling.empty())
2736     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2737         InsertLoc,
2738         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2739          S.PP.getIdentifierInfo("require_constant_initialization"),
2740          tok::r_paren, tok::r_paren});
2741   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2742     SuitableSpelling = "constinit";
2743   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2744     SuitableSpelling = "[[clang::require_constant_initialization]]";
2745   if (SuitableSpelling.empty())
2746     SuitableSpelling = "__attribute__((require_constant_initialization))";
2747   SuitableSpelling += " ";
2748 
2749   if (AttrBeforeInit) {
2750     // extern constinit int a;
2751     // int a = 0; // error (missing 'constinit'), accepted as extension
2752     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2753     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2754         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2755     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2756   } else {
2757     // int a = 0;
2758     // constinit extern int a; // error (missing 'constinit')
2759     S.Diag(CIAttr->getLocation(),
2760            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2761                                  : diag::warn_require_const_init_added_too_late)
2762         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2763     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2764         << CIAttr->isConstinit()
2765         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2766   }
2767 }
2768 
2769 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2770 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2771                                AvailabilityMergeKind AMK) {
2772   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2773     UsedAttr *NewAttr = OldAttr->clone(Context);
2774     NewAttr->setInherited(true);
2775     New->addAttr(NewAttr);
2776   }
2777 
2778   if (!Old->hasAttrs() && !New->hasAttrs())
2779     return;
2780 
2781   // [dcl.constinit]p1:
2782   //   If the [constinit] specifier is applied to any declaration of a
2783   //   variable, it shall be applied to the initializing declaration.
2784   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2785   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2786   if (bool(OldConstInit) != bool(NewConstInit)) {
2787     const auto *OldVD = cast<VarDecl>(Old);
2788     auto *NewVD = cast<VarDecl>(New);
2789 
2790     // Find the initializing declaration. Note that we might not have linked
2791     // the new declaration into the redeclaration chain yet.
2792     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2793     if (!InitDecl &&
2794         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2795       InitDecl = NewVD;
2796 
2797     if (InitDecl == NewVD) {
2798       // This is the initializing declaration. If it would inherit 'constinit',
2799       // that's ill-formed. (Note that we do not apply this to the attribute
2800       // form).
2801       if (OldConstInit && OldConstInit->isConstinit())
2802         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2803                                  /*AttrBeforeInit=*/true);
2804     } else if (NewConstInit) {
2805       // This is the first time we've been told that this declaration should
2806       // have a constant initializer. If we already saw the initializing
2807       // declaration, this is too late.
2808       if (InitDecl && InitDecl != NewVD) {
2809         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2810                                  /*AttrBeforeInit=*/false);
2811         NewVD->dropAttr<ConstInitAttr>();
2812       }
2813     }
2814   }
2815 
2816   // Attributes declared post-definition are currently ignored.
2817   checkNewAttributesAfterDef(*this, New, Old);
2818 
2819   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2820     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2821       if (!OldA->isEquivalent(NewA)) {
2822         // This redeclaration changes __asm__ label.
2823         Diag(New->getLocation(), diag::err_different_asm_label);
2824         Diag(OldA->getLocation(), diag::note_previous_declaration);
2825       }
2826     } else if (Old->isUsed()) {
2827       // This redeclaration adds an __asm__ label to a declaration that has
2828       // already been ODR-used.
2829       Diag(New->getLocation(), diag::err_late_asm_label_name)
2830         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2831     }
2832   }
2833 
2834   // Re-declaration cannot add abi_tag's.
2835   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2836     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2837       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2838         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2839                       NewTag) == OldAbiTagAttr->tags_end()) {
2840           Diag(NewAbiTagAttr->getLocation(),
2841                diag::err_new_abi_tag_on_redeclaration)
2842               << NewTag;
2843           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2844         }
2845       }
2846     } else {
2847       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2848       Diag(Old->getLocation(), diag::note_previous_declaration);
2849     }
2850   }
2851 
2852   // This redeclaration adds a section attribute.
2853   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2854     if (auto *VD = dyn_cast<VarDecl>(New)) {
2855       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2856         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2857         Diag(Old->getLocation(), diag::note_previous_declaration);
2858       }
2859     }
2860   }
2861 
2862   // Redeclaration adds code-seg attribute.
2863   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2864   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2865       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2866     Diag(New->getLocation(), diag::warn_mismatched_section)
2867          << 0 /*codeseg*/;
2868     Diag(Old->getLocation(), diag::note_previous_declaration);
2869   }
2870 
2871   if (!Old->hasAttrs())
2872     return;
2873 
2874   bool foundAny = New->hasAttrs();
2875 
2876   // Ensure that any moving of objects within the allocated map is done before
2877   // we process them.
2878   if (!foundAny) New->setAttrs(AttrVec());
2879 
2880   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2881     // Ignore deprecated/unavailable/availability attributes if requested.
2882     AvailabilityMergeKind LocalAMK = AMK_None;
2883     if (isa<DeprecatedAttr>(I) ||
2884         isa<UnavailableAttr>(I) ||
2885         isa<AvailabilityAttr>(I)) {
2886       switch (AMK) {
2887       case AMK_None:
2888         continue;
2889 
2890       case AMK_Redeclaration:
2891       case AMK_Override:
2892       case AMK_ProtocolImplementation:
2893         LocalAMK = AMK;
2894         break;
2895       }
2896     }
2897 
2898     // Already handled.
2899     if (isa<UsedAttr>(I))
2900       continue;
2901 
2902     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2903       foundAny = true;
2904   }
2905 
2906   if (mergeAlignedAttrs(*this, New, Old))
2907     foundAny = true;
2908 
2909   if (!foundAny) New->dropAttrs();
2910 }
2911 
2912 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2913 /// to the new one.
2914 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2915                                      const ParmVarDecl *oldDecl,
2916                                      Sema &S) {
2917   // C++11 [dcl.attr.depend]p2:
2918   //   The first declaration of a function shall specify the
2919   //   carries_dependency attribute for its declarator-id if any declaration
2920   //   of the function specifies the carries_dependency attribute.
2921   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2922   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2923     S.Diag(CDA->getLocation(),
2924            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2925     // Find the first declaration of the parameter.
2926     // FIXME: Should we build redeclaration chains for function parameters?
2927     const FunctionDecl *FirstFD =
2928       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2929     const ParmVarDecl *FirstVD =
2930       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2931     S.Diag(FirstVD->getLocation(),
2932            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2933   }
2934 
2935   if (!oldDecl->hasAttrs())
2936     return;
2937 
2938   bool foundAny = newDecl->hasAttrs();
2939 
2940   // Ensure that any moving of objects within the allocated map is
2941   // done before we process them.
2942   if (!foundAny) newDecl->setAttrs(AttrVec());
2943 
2944   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2945     if (!DeclHasAttr(newDecl, I)) {
2946       InheritableAttr *newAttr =
2947         cast<InheritableParamAttr>(I->clone(S.Context));
2948       newAttr->setInherited(true);
2949       newDecl->addAttr(newAttr);
2950       foundAny = true;
2951     }
2952   }
2953 
2954   if (!foundAny) newDecl->dropAttrs();
2955 }
2956 
2957 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2958                                 const ParmVarDecl *OldParam,
2959                                 Sema &S) {
2960   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2961     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2962       if (*Oldnullability != *Newnullability) {
2963         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2964           << DiagNullabilityKind(
2965                *Newnullability,
2966                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2967                 != 0))
2968           << DiagNullabilityKind(
2969                *Oldnullability,
2970                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2971                 != 0));
2972         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2973       }
2974     } else {
2975       QualType NewT = NewParam->getType();
2976       NewT = S.Context.getAttributedType(
2977                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2978                          NewT, NewT);
2979       NewParam->setType(NewT);
2980     }
2981   }
2982 }
2983 
2984 namespace {
2985 
2986 /// Used in MergeFunctionDecl to keep track of function parameters in
2987 /// C.
2988 struct GNUCompatibleParamWarning {
2989   ParmVarDecl *OldParm;
2990   ParmVarDecl *NewParm;
2991   QualType PromotedType;
2992 };
2993 
2994 } // end anonymous namespace
2995 
2996 /// getSpecialMember - get the special member enum for a method.
2997 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2998   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2999     if (Ctor->isDefaultConstructor())
3000       return Sema::CXXDefaultConstructor;
3001 
3002     if (Ctor->isCopyConstructor())
3003       return Sema::CXXCopyConstructor;
3004 
3005     if (Ctor->isMoveConstructor())
3006       return Sema::CXXMoveConstructor;
3007   } else if (isa<CXXDestructorDecl>(MD)) {
3008     return Sema::CXXDestructor;
3009   } else if (MD->isCopyAssignmentOperator()) {
3010     return Sema::CXXCopyAssignment;
3011   } else if (MD->isMoveAssignmentOperator()) {
3012     return Sema::CXXMoveAssignment;
3013   }
3014 
3015   return Sema::CXXInvalid;
3016 }
3017 
3018 // Determine whether the previous declaration was a definition, implicit
3019 // declaration, or a declaration.
3020 template <typename T>
3021 static std::pair<diag::kind, SourceLocation>
3022 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3023   diag::kind PrevDiag;
3024   SourceLocation OldLocation = Old->getLocation();
3025   if (Old->isThisDeclarationADefinition())
3026     PrevDiag = diag::note_previous_definition;
3027   else if (Old->isImplicit()) {
3028     PrevDiag = diag::note_previous_implicit_declaration;
3029     if (OldLocation.isInvalid())
3030       OldLocation = New->getLocation();
3031   } else
3032     PrevDiag = diag::note_previous_declaration;
3033   return std::make_pair(PrevDiag, OldLocation);
3034 }
3035 
3036 /// canRedefineFunction - checks if a function can be redefined. Currently,
3037 /// only extern inline functions can be redefined, and even then only in
3038 /// GNU89 mode.
3039 static bool canRedefineFunction(const FunctionDecl *FD,
3040                                 const LangOptions& LangOpts) {
3041   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3042           !LangOpts.CPlusPlus &&
3043           FD->isInlineSpecified() &&
3044           FD->getStorageClass() == SC_Extern);
3045 }
3046 
3047 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3048   const AttributedType *AT = T->getAs<AttributedType>();
3049   while (AT && !AT->isCallingConv())
3050     AT = AT->getModifiedType()->getAs<AttributedType>();
3051   return AT;
3052 }
3053 
3054 template <typename T>
3055 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3056   const DeclContext *DC = Old->getDeclContext();
3057   if (DC->isRecord())
3058     return false;
3059 
3060   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3061   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3062     return true;
3063   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3064     return true;
3065   return false;
3066 }
3067 
3068 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3069 static bool isExternC(VarTemplateDecl *) { return false; }
3070 
3071 /// Check whether a redeclaration of an entity introduced by a
3072 /// using-declaration is valid, given that we know it's not an overload
3073 /// (nor a hidden tag declaration).
3074 template<typename ExpectedDecl>
3075 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3076                                    ExpectedDecl *New) {
3077   // C++11 [basic.scope.declarative]p4:
3078   //   Given a set of declarations in a single declarative region, each of
3079   //   which specifies the same unqualified name,
3080   //   -- they shall all refer to the same entity, or all refer to functions
3081   //      and function templates; or
3082   //   -- exactly one declaration shall declare a class name or enumeration
3083   //      name that is not a typedef name and the other declarations shall all
3084   //      refer to the same variable or enumerator, or all refer to functions
3085   //      and function templates; in this case the class name or enumeration
3086   //      name is hidden (3.3.10).
3087 
3088   // C++11 [namespace.udecl]p14:
3089   //   If a function declaration in namespace scope or block scope has the
3090   //   same name and the same parameter-type-list as a function introduced
3091   //   by a using-declaration, and the declarations do not declare the same
3092   //   function, the program is ill-formed.
3093 
3094   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3095   if (Old &&
3096       !Old->getDeclContext()->getRedeclContext()->Equals(
3097           New->getDeclContext()->getRedeclContext()) &&
3098       !(isExternC(Old) && isExternC(New)))
3099     Old = nullptr;
3100 
3101   if (!Old) {
3102     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3103     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3104     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3105     return true;
3106   }
3107   return false;
3108 }
3109 
3110 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3111                                             const FunctionDecl *B) {
3112   assert(A->getNumParams() == B->getNumParams());
3113 
3114   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3115     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3116     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3117     if (AttrA == AttrB)
3118       return true;
3119     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3120            AttrA->isDynamic() == AttrB->isDynamic();
3121   };
3122 
3123   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3124 }
3125 
3126 /// If necessary, adjust the semantic declaration context for a qualified
3127 /// declaration to name the correct inline namespace within the qualifier.
3128 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3129                                                DeclaratorDecl *OldD) {
3130   // The only case where we need to update the DeclContext is when
3131   // redeclaration lookup for a qualified name finds a declaration
3132   // in an inline namespace within the context named by the qualifier:
3133   //
3134   //   inline namespace N { int f(); }
3135   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3136   //
3137   // For unqualified declarations, the semantic context *can* change
3138   // along the redeclaration chain (for local extern declarations,
3139   // extern "C" declarations, and friend declarations in particular).
3140   if (!NewD->getQualifier())
3141     return;
3142 
3143   // NewD is probably already in the right context.
3144   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3145   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3146   if (NamedDC->Equals(SemaDC))
3147     return;
3148 
3149   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3150           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3151          "unexpected context for redeclaration");
3152 
3153   auto *LexDC = NewD->getLexicalDeclContext();
3154   auto FixSemaDC = [=](NamedDecl *D) {
3155     if (!D)
3156       return;
3157     D->setDeclContext(SemaDC);
3158     D->setLexicalDeclContext(LexDC);
3159   };
3160 
3161   FixSemaDC(NewD);
3162   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3163     FixSemaDC(FD->getDescribedFunctionTemplate());
3164   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3165     FixSemaDC(VD->getDescribedVarTemplate());
3166 }
3167 
3168 /// MergeFunctionDecl - We just parsed a function 'New' from
3169 /// declarator D which has the same name and scope as a previous
3170 /// declaration 'Old'.  Figure out how to resolve this situation,
3171 /// merging decls or emitting diagnostics as appropriate.
3172 ///
3173 /// In C++, New and Old must be declarations that are not
3174 /// overloaded. Use IsOverload to determine whether New and Old are
3175 /// overloaded, and to select the Old declaration that New should be
3176 /// merged with.
3177 ///
3178 /// Returns true if there was an error, false otherwise.
3179 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3180                              Scope *S, bool MergeTypeWithOld) {
3181   // Verify the old decl was also a function.
3182   FunctionDecl *Old = OldD->getAsFunction();
3183   if (!Old) {
3184     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3185       if (New->getFriendObjectKind()) {
3186         Diag(New->getLocation(), diag::err_using_decl_friend);
3187         Diag(Shadow->getTargetDecl()->getLocation(),
3188              diag::note_using_decl_target);
3189         Diag(Shadow->getUsingDecl()->getLocation(),
3190              diag::note_using_decl) << 0;
3191         return true;
3192       }
3193 
3194       // Check whether the two declarations might declare the same function.
3195       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3196         return true;
3197       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3198     } else {
3199       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3200         << New->getDeclName();
3201       notePreviousDefinition(OldD, New->getLocation());
3202       return true;
3203     }
3204   }
3205 
3206   // If the old declaration is invalid, just give up here.
3207   if (Old->isInvalidDecl())
3208     return true;
3209 
3210   // Disallow redeclaration of some builtins.
3211   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3212     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3213     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3214         << Old << Old->getType();
3215     return true;
3216   }
3217 
3218   diag::kind PrevDiag;
3219   SourceLocation OldLocation;
3220   std::tie(PrevDiag, OldLocation) =
3221       getNoteDiagForInvalidRedeclaration(Old, New);
3222 
3223   // Don't complain about this if we're in GNU89 mode and the old function
3224   // is an extern inline function.
3225   // Don't complain about specializations. They are not supposed to have
3226   // storage classes.
3227   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3228       New->getStorageClass() == SC_Static &&
3229       Old->hasExternalFormalLinkage() &&
3230       !New->getTemplateSpecializationInfo() &&
3231       !canRedefineFunction(Old, getLangOpts())) {
3232     if (getLangOpts().MicrosoftExt) {
3233       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3234       Diag(OldLocation, PrevDiag);
3235     } else {
3236       Diag(New->getLocation(), diag::err_static_non_static) << New;
3237       Diag(OldLocation, PrevDiag);
3238       return true;
3239     }
3240   }
3241 
3242   if (New->hasAttr<InternalLinkageAttr>() &&
3243       !Old->hasAttr<InternalLinkageAttr>()) {
3244     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3245         << New->getDeclName();
3246     notePreviousDefinition(Old, New->getLocation());
3247     New->dropAttr<InternalLinkageAttr>();
3248   }
3249 
3250   if (CheckRedeclarationModuleOwnership(New, Old))
3251     return true;
3252 
3253   if (!getLangOpts().CPlusPlus) {
3254     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3255     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3256       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3257         << New << OldOvl;
3258 
3259       // Try our best to find a decl that actually has the overloadable
3260       // attribute for the note. In most cases (e.g. programs with only one
3261       // broken declaration/definition), this won't matter.
3262       //
3263       // FIXME: We could do this if we juggled some extra state in
3264       // OverloadableAttr, rather than just removing it.
3265       const Decl *DiagOld = Old;
3266       if (OldOvl) {
3267         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3268           const auto *A = D->getAttr<OverloadableAttr>();
3269           return A && !A->isImplicit();
3270         });
3271         // If we've implicitly added *all* of the overloadable attrs to this
3272         // chain, emitting a "previous redecl" note is pointless.
3273         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3274       }
3275 
3276       if (DiagOld)
3277         Diag(DiagOld->getLocation(),
3278              diag::note_attribute_overloadable_prev_overload)
3279           << OldOvl;
3280 
3281       if (OldOvl)
3282         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3283       else
3284         New->dropAttr<OverloadableAttr>();
3285     }
3286   }
3287 
3288   // If a function is first declared with a calling convention, but is later
3289   // declared or defined without one, all following decls assume the calling
3290   // convention of the first.
3291   //
3292   // It's OK if a function is first declared without a calling convention,
3293   // but is later declared or defined with the default calling convention.
3294   //
3295   // To test if either decl has an explicit calling convention, we look for
3296   // AttributedType sugar nodes on the type as written.  If they are missing or
3297   // were canonicalized away, we assume the calling convention was implicit.
3298   //
3299   // Note also that we DO NOT return at this point, because we still have
3300   // other tests to run.
3301   QualType OldQType = Context.getCanonicalType(Old->getType());
3302   QualType NewQType = Context.getCanonicalType(New->getType());
3303   const FunctionType *OldType = cast<FunctionType>(OldQType);
3304   const FunctionType *NewType = cast<FunctionType>(NewQType);
3305   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3306   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3307   bool RequiresAdjustment = false;
3308 
3309   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3310     FunctionDecl *First = Old->getFirstDecl();
3311     const FunctionType *FT =
3312         First->getType().getCanonicalType()->castAs<FunctionType>();
3313     FunctionType::ExtInfo FI = FT->getExtInfo();
3314     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3315     if (!NewCCExplicit) {
3316       // Inherit the CC from the previous declaration if it was specified
3317       // there but not here.
3318       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3319       RequiresAdjustment = true;
3320     } else if (New->getBuiltinID()) {
3321       // Calling Conventions on a Builtin aren't really useful and setting a
3322       // default calling convention and cdecl'ing some builtin redeclarations is
3323       // common, so warn and ignore the calling convention on the redeclaration.
3324       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3325           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3326           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3327       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3328       RequiresAdjustment = true;
3329     } else {
3330       // Calling conventions aren't compatible, so complain.
3331       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3332       Diag(New->getLocation(), diag::err_cconv_change)
3333         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3334         << !FirstCCExplicit
3335         << (!FirstCCExplicit ? "" :
3336             FunctionType::getNameForCallConv(FI.getCC()));
3337 
3338       // Put the note on the first decl, since it is the one that matters.
3339       Diag(First->getLocation(), diag::note_previous_declaration);
3340       return true;
3341     }
3342   }
3343 
3344   // FIXME: diagnose the other way around?
3345   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3346     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3347     RequiresAdjustment = true;
3348   }
3349 
3350   // Merge regparm attribute.
3351   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3352       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3353     if (NewTypeInfo.getHasRegParm()) {
3354       Diag(New->getLocation(), diag::err_regparm_mismatch)
3355         << NewType->getRegParmType()
3356         << OldType->getRegParmType();
3357       Diag(OldLocation, diag::note_previous_declaration);
3358       return true;
3359     }
3360 
3361     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3362     RequiresAdjustment = true;
3363   }
3364 
3365   // Merge ns_returns_retained attribute.
3366   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3367     if (NewTypeInfo.getProducesResult()) {
3368       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3369           << "'ns_returns_retained'";
3370       Diag(OldLocation, diag::note_previous_declaration);
3371       return true;
3372     }
3373 
3374     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3375     RequiresAdjustment = true;
3376   }
3377 
3378   if (OldTypeInfo.getNoCallerSavedRegs() !=
3379       NewTypeInfo.getNoCallerSavedRegs()) {
3380     if (NewTypeInfo.getNoCallerSavedRegs()) {
3381       AnyX86NoCallerSavedRegistersAttr *Attr =
3382         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3383       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3384       Diag(OldLocation, diag::note_previous_declaration);
3385       return true;
3386     }
3387 
3388     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3389     RequiresAdjustment = true;
3390   }
3391 
3392   if (RequiresAdjustment) {
3393     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3394     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3395     New->setType(QualType(AdjustedType, 0));
3396     NewQType = Context.getCanonicalType(New->getType());
3397   }
3398 
3399   // If this redeclaration makes the function inline, we may need to add it to
3400   // UndefinedButUsed.
3401   if (!Old->isInlined() && New->isInlined() &&
3402       !New->hasAttr<GNUInlineAttr>() &&
3403       !getLangOpts().GNUInline &&
3404       Old->isUsed(false) &&
3405       !Old->isDefined() && !New->isThisDeclarationADefinition())
3406     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3407                                            SourceLocation()));
3408 
3409   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3410   // about it.
3411   if (New->hasAttr<GNUInlineAttr>() &&
3412       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3413     UndefinedButUsed.erase(Old->getCanonicalDecl());
3414   }
3415 
3416   // If pass_object_size params don't match up perfectly, this isn't a valid
3417   // redeclaration.
3418   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3419       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3420     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3421         << New->getDeclName();
3422     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3423     return true;
3424   }
3425 
3426   if (getLangOpts().CPlusPlus) {
3427     // C++1z [over.load]p2
3428     //   Certain function declarations cannot be overloaded:
3429     //     -- Function declarations that differ only in the return type,
3430     //        the exception specification, or both cannot be overloaded.
3431 
3432     // Check the exception specifications match. This may recompute the type of
3433     // both Old and New if it resolved exception specifications, so grab the
3434     // types again after this. Because this updates the type, we do this before
3435     // any of the other checks below, which may update the "de facto" NewQType
3436     // but do not necessarily update the type of New.
3437     if (CheckEquivalentExceptionSpec(Old, New))
3438       return true;
3439     OldQType = Context.getCanonicalType(Old->getType());
3440     NewQType = Context.getCanonicalType(New->getType());
3441 
3442     // Go back to the type source info to compare the declared return types,
3443     // per C++1y [dcl.type.auto]p13:
3444     //   Redeclarations or specializations of a function or function template
3445     //   with a declared return type that uses a placeholder type shall also
3446     //   use that placeholder, not a deduced type.
3447     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3448     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3449     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3450         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3451                                        OldDeclaredReturnType)) {
3452       QualType ResQT;
3453       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3454           OldDeclaredReturnType->isObjCObjectPointerType())
3455         // FIXME: This does the wrong thing for a deduced return type.
3456         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3457       if (ResQT.isNull()) {
3458         if (New->isCXXClassMember() && New->isOutOfLine())
3459           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3460               << New << New->getReturnTypeSourceRange();
3461         else
3462           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3463               << New->getReturnTypeSourceRange();
3464         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3465                                     << Old->getReturnTypeSourceRange();
3466         return true;
3467       }
3468       else
3469         NewQType = ResQT;
3470     }
3471 
3472     QualType OldReturnType = OldType->getReturnType();
3473     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3474     if (OldReturnType != NewReturnType) {
3475       // If this function has a deduced return type and has already been
3476       // defined, copy the deduced value from the old declaration.
3477       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3478       if (OldAT && OldAT->isDeduced()) {
3479         New->setType(
3480             SubstAutoType(New->getType(),
3481                           OldAT->isDependentType() ? Context.DependentTy
3482                                                    : OldAT->getDeducedType()));
3483         NewQType = Context.getCanonicalType(
3484             SubstAutoType(NewQType,
3485                           OldAT->isDependentType() ? Context.DependentTy
3486                                                    : OldAT->getDeducedType()));
3487       }
3488     }
3489 
3490     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3491     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3492     if (OldMethod && NewMethod) {
3493       // Preserve triviality.
3494       NewMethod->setTrivial(OldMethod->isTrivial());
3495 
3496       // MSVC allows explicit template specialization at class scope:
3497       // 2 CXXMethodDecls referring to the same function will be injected.
3498       // We don't want a redeclaration error.
3499       bool IsClassScopeExplicitSpecialization =
3500                               OldMethod->isFunctionTemplateSpecialization() &&
3501                               NewMethod->isFunctionTemplateSpecialization();
3502       bool isFriend = NewMethod->getFriendObjectKind();
3503 
3504       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3505           !IsClassScopeExplicitSpecialization) {
3506         //    -- Member function declarations with the same name and the
3507         //       same parameter types cannot be overloaded if any of them
3508         //       is a static member function declaration.
3509         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3510           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3511           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3512           return true;
3513         }
3514 
3515         // C++ [class.mem]p1:
3516         //   [...] A member shall not be declared twice in the
3517         //   member-specification, except that a nested class or member
3518         //   class template can be declared and then later defined.
3519         if (!inTemplateInstantiation()) {
3520           unsigned NewDiag;
3521           if (isa<CXXConstructorDecl>(OldMethod))
3522             NewDiag = diag::err_constructor_redeclared;
3523           else if (isa<CXXDestructorDecl>(NewMethod))
3524             NewDiag = diag::err_destructor_redeclared;
3525           else if (isa<CXXConversionDecl>(NewMethod))
3526             NewDiag = diag::err_conv_function_redeclared;
3527           else
3528             NewDiag = diag::err_member_redeclared;
3529 
3530           Diag(New->getLocation(), NewDiag);
3531         } else {
3532           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3533             << New << New->getType();
3534         }
3535         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3536         return true;
3537 
3538       // Complain if this is an explicit declaration of a special
3539       // member that was initially declared implicitly.
3540       //
3541       // As an exception, it's okay to befriend such methods in order
3542       // to permit the implicit constructor/destructor/operator calls.
3543       } else if (OldMethod->isImplicit()) {
3544         if (isFriend) {
3545           NewMethod->setImplicit();
3546         } else {
3547           Diag(NewMethod->getLocation(),
3548                diag::err_definition_of_implicitly_declared_member)
3549             << New << getSpecialMember(OldMethod);
3550           return true;
3551         }
3552       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3553         Diag(NewMethod->getLocation(),
3554              diag::err_definition_of_explicitly_defaulted_member)
3555           << getSpecialMember(OldMethod);
3556         return true;
3557       }
3558     }
3559 
3560     // C++11 [dcl.attr.noreturn]p1:
3561     //   The first declaration of a function shall specify the noreturn
3562     //   attribute if any declaration of that function specifies the noreturn
3563     //   attribute.
3564     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3565     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3566       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3567       Diag(Old->getFirstDecl()->getLocation(),
3568            diag::note_noreturn_missing_first_decl);
3569     }
3570 
3571     // C++11 [dcl.attr.depend]p2:
3572     //   The first declaration of a function shall specify the
3573     //   carries_dependency attribute for its declarator-id if any declaration
3574     //   of the function specifies the carries_dependency attribute.
3575     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3576     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3577       Diag(CDA->getLocation(),
3578            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3579       Diag(Old->getFirstDecl()->getLocation(),
3580            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3581     }
3582 
3583     // (C++98 8.3.5p3):
3584     //   All declarations for a function shall agree exactly in both the
3585     //   return type and the parameter-type-list.
3586     // We also want to respect all the extended bits except noreturn.
3587 
3588     // noreturn should now match unless the old type info didn't have it.
3589     QualType OldQTypeForComparison = OldQType;
3590     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3591       auto *OldType = OldQType->castAs<FunctionProtoType>();
3592       const FunctionType *OldTypeForComparison
3593         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3594       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3595       assert(OldQTypeForComparison.isCanonical());
3596     }
3597 
3598     if (haveIncompatibleLanguageLinkages(Old, New)) {
3599       // As a special case, retain the language linkage from previous
3600       // declarations of a friend function as an extension.
3601       //
3602       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3603       // and is useful because there's otherwise no way to specify language
3604       // linkage within class scope.
3605       //
3606       // Check cautiously as the friend object kind isn't yet complete.
3607       if (New->getFriendObjectKind() != Decl::FOK_None) {
3608         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3609         Diag(OldLocation, PrevDiag);
3610       } else {
3611         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3612         Diag(OldLocation, PrevDiag);
3613         return true;
3614       }
3615     }
3616 
3617     // If the function types are compatible, merge the declarations. Ignore the
3618     // exception specifier because it was already checked above in
3619     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3620     // about incompatible types under -fms-compatibility.
3621     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3622                                                          NewQType))
3623       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3624 
3625     // If the types are imprecise (due to dependent constructs in friends or
3626     // local extern declarations), it's OK if they differ. We'll check again
3627     // during instantiation.
3628     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3629       return false;
3630 
3631     // Fall through for conflicting redeclarations and redefinitions.
3632   }
3633 
3634   // C: Function types need to be compatible, not identical. This handles
3635   // duplicate function decls like "void f(int); void f(enum X);" properly.
3636   if (!getLangOpts().CPlusPlus &&
3637       Context.typesAreCompatible(OldQType, NewQType)) {
3638     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3639     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3640     const FunctionProtoType *OldProto = nullptr;
3641     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3642         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3643       // The old declaration provided a function prototype, but the
3644       // new declaration does not. Merge in the prototype.
3645       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3646       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3647       NewQType =
3648           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3649                                   OldProto->getExtProtoInfo());
3650       New->setType(NewQType);
3651       New->setHasInheritedPrototype();
3652 
3653       // Synthesize parameters with the same types.
3654       SmallVector<ParmVarDecl*, 16> Params;
3655       for (const auto &ParamType : OldProto->param_types()) {
3656         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3657                                                  SourceLocation(), nullptr,
3658                                                  ParamType, /*TInfo=*/nullptr,
3659                                                  SC_None, nullptr);
3660         Param->setScopeInfo(0, Params.size());
3661         Param->setImplicit();
3662         Params.push_back(Param);
3663       }
3664 
3665       New->setParams(Params);
3666     }
3667 
3668     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3669   }
3670 
3671   // GNU C permits a K&R definition to follow a prototype declaration
3672   // if the declared types of the parameters in the K&R definition
3673   // match the types in the prototype declaration, even when the
3674   // promoted types of the parameters from the K&R definition differ
3675   // from the types in the prototype. GCC then keeps the types from
3676   // the prototype.
3677   //
3678   // If a variadic prototype is followed by a non-variadic K&R definition,
3679   // the K&R definition becomes variadic.  This is sort of an edge case, but
3680   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3681   // C99 6.9.1p8.
3682   if (!getLangOpts().CPlusPlus &&
3683       Old->hasPrototype() && !New->hasPrototype() &&
3684       New->getType()->getAs<FunctionProtoType>() &&
3685       Old->getNumParams() == New->getNumParams()) {
3686     SmallVector<QualType, 16> ArgTypes;
3687     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3688     const FunctionProtoType *OldProto
3689       = Old->getType()->getAs<FunctionProtoType>();
3690     const FunctionProtoType *NewProto
3691       = New->getType()->getAs<FunctionProtoType>();
3692 
3693     // Determine whether this is the GNU C extension.
3694     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3695                                                NewProto->getReturnType());
3696     bool LooseCompatible = !MergedReturn.isNull();
3697     for (unsigned Idx = 0, End = Old->getNumParams();
3698          LooseCompatible && Idx != End; ++Idx) {
3699       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3700       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3701       if (Context.typesAreCompatible(OldParm->getType(),
3702                                      NewProto->getParamType(Idx))) {
3703         ArgTypes.push_back(NewParm->getType());
3704       } else if (Context.typesAreCompatible(OldParm->getType(),
3705                                             NewParm->getType(),
3706                                             /*CompareUnqualified=*/true)) {
3707         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3708                                            NewProto->getParamType(Idx) };
3709         Warnings.push_back(Warn);
3710         ArgTypes.push_back(NewParm->getType());
3711       } else
3712         LooseCompatible = false;
3713     }
3714 
3715     if (LooseCompatible) {
3716       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3717         Diag(Warnings[Warn].NewParm->getLocation(),
3718              diag::ext_param_promoted_not_compatible_with_prototype)
3719           << Warnings[Warn].PromotedType
3720           << Warnings[Warn].OldParm->getType();
3721         if (Warnings[Warn].OldParm->getLocation().isValid())
3722           Diag(Warnings[Warn].OldParm->getLocation(),
3723                diag::note_previous_declaration);
3724       }
3725 
3726       if (MergeTypeWithOld)
3727         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3728                                              OldProto->getExtProtoInfo()));
3729       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3730     }
3731 
3732     // Fall through to diagnose conflicting types.
3733   }
3734 
3735   // A function that has already been declared has been redeclared or
3736   // defined with a different type; show an appropriate diagnostic.
3737 
3738   // If the previous declaration was an implicitly-generated builtin
3739   // declaration, then at the very least we should use a specialized note.
3740   unsigned BuiltinID;
3741   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3742     // If it's actually a library-defined builtin function like 'malloc'
3743     // or 'printf', just warn about the incompatible redeclaration.
3744     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3745       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3746       Diag(OldLocation, diag::note_previous_builtin_declaration)
3747         << Old << Old->getType();
3748 
3749       // If this is a global redeclaration, just forget hereafter
3750       // about the "builtin-ness" of the function.
3751       //
3752       // Doing this for local extern declarations is problematic.  If
3753       // the builtin declaration remains visible, a second invalid
3754       // local declaration will produce a hard error; if it doesn't
3755       // remain visible, a single bogus local redeclaration (which is
3756       // actually only a warning) could break all the downstream code.
3757       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3758         New->getIdentifier()->revertBuiltin();
3759 
3760       return false;
3761     }
3762 
3763     PrevDiag = diag::note_previous_builtin_declaration;
3764   }
3765 
3766   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3767   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3768   return true;
3769 }
3770 
3771 /// Completes the merge of two function declarations that are
3772 /// known to be compatible.
3773 ///
3774 /// This routine handles the merging of attributes and other
3775 /// properties of function declarations from the old declaration to
3776 /// the new declaration, once we know that New is in fact a
3777 /// redeclaration of Old.
3778 ///
3779 /// \returns false
3780 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3781                                         Scope *S, bool MergeTypeWithOld) {
3782   // Merge the attributes
3783   mergeDeclAttributes(New, Old);
3784 
3785   // Merge "pure" flag.
3786   if (Old->isPure())
3787     New->setPure();
3788 
3789   // Merge "used" flag.
3790   if (Old->getMostRecentDecl()->isUsed(false))
3791     New->setIsUsed();
3792 
3793   // Merge attributes from the parameters.  These can mismatch with K&R
3794   // declarations.
3795   if (New->getNumParams() == Old->getNumParams())
3796       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3797         ParmVarDecl *NewParam = New->getParamDecl(i);
3798         ParmVarDecl *OldParam = Old->getParamDecl(i);
3799         mergeParamDeclAttributes(NewParam, OldParam, *this);
3800         mergeParamDeclTypes(NewParam, OldParam, *this);
3801       }
3802 
3803   if (getLangOpts().CPlusPlus)
3804     return MergeCXXFunctionDecl(New, Old, S);
3805 
3806   // Merge the function types so the we get the composite types for the return
3807   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3808   // was visible.
3809   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3810   if (!Merged.isNull() && MergeTypeWithOld)
3811     New->setType(Merged);
3812 
3813   return false;
3814 }
3815 
3816 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3817                                 ObjCMethodDecl *oldMethod) {
3818   // Merge the attributes, including deprecated/unavailable
3819   AvailabilityMergeKind MergeKind =
3820     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3821       ? AMK_ProtocolImplementation
3822       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3823                                                        : AMK_Override;
3824 
3825   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3826 
3827   // Merge attributes from the parameters.
3828   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3829                                        oe = oldMethod->param_end();
3830   for (ObjCMethodDecl::param_iterator
3831          ni = newMethod->param_begin(), ne = newMethod->param_end();
3832        ni != ne && oi != oe; ++ni, ++oi)
3833     mergeParamDeclAttributes(*ni, *oi, *this);
3834 
3835   CheckObjCMethodOverride(newMethod, oldMethod);
3836 }
3837 
3838 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3839   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3840 
3841   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3842          ? diag::err_redefinition_different_type
3843          : diag::err_redeclaration_different_type)
3844     << New->getDeclName() << New->getType() << Old->getType();
3845 
3846   diag::kind PrevDiag;
3847   SourceLocation OldLocation;
3848   std::tie(PrevDiag, OldLocation)
3849     = getNoteDiagForInvalidRedeclaration(Old, New);
3850   S.Diag(OldLocation, PrevDiag);
3851   New->setInvalidDecl();
3852 }
3853 
3854 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3855 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3856 /// emitting diagnostics as appropriate.
3857 ///
3858 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3859 /// to here in AddInitializerToDecl. We can't check them before the initializer
3860 /// is attached.
3861 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3862                              bool MergeTypeWithOld) {
3863   if (New->isInvalidDecl() || Old->isInvalidDecl())
3864     return;
3865 
3866   QualType MergedT;
3867   if (getLangOpts().CPlusPlus) {
3868     if (New->getType()->isUndeducedType()) {
3869       // We don't know what the new type is until the initializer is attached.
3870       return;
3871     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3872       // These could still be something that needs exception specs checked.
3873       return MergeVarDeclExceptionSpecs(New, Old);
3874     }
3875     // C++ [basic.link]p10:
3876     //   [...] the types specified by all declarations referring to a given
3877     //   object or function shall be identical, except that declarations for an
3878     //   array object can specify array types that differ by the presence or
3879     //   absence of a major array bound (8.3.4).
3880     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3881       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3882       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3883 
3884       // We are merging a variable declaration New into Old. If it has an array
3885       // bound, and that bound differs from Old's bound, we should diagnose the
3886       // mismatch.
3887       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3888         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3889              PrevVD = PrevVD->getPreviousDecl()) {
3890           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3891           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3892             continue;
3893 
3894           if (!Context.hasSameType(NewArray, PrevVDTy))
3895             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3896         }
3897       }
3898 
3899       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3900         if (Context.hasSameType(OldArray->getElementType(),
3901                                 NewArray->getElementType()))
3902           MergedT = New->getType();
3903       }
3904       // FIXME: Check visibility. New is hidden but has a complete type. If New
3905       // has no array bound, it should not inherit one from Old, if Old is not
3906       // visible.
3907       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3908         if (Context.hasSameType(OldArray->getElementType(),
3909                                 NewArray->getElementType()))
3910           MergedT = Old->getType();
3911       }
3912     }
3913     else if (New->getType()->isObjCObjectPointerType() &&
3914                Old->getType()->isObjCObjectPointerType()) {
3915       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3916                                               Old->getType());
3917     }
3918   } else {
3919     // C 6.2.7p2:
3920     //   All declarations that refer to the same object or function shall have
3921     //   compatible type.
3922     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3923   }
3924   if (MergedT.isNull()) {
3925     // It's OK if we couldn't merge types if either type is dependent, for a
3926     // block-scope variable. In other cases (static data members of class
3927     // templates, variable templates, ...), we require the types to be
3928     // equivalent.
3929     // FIXME: The C++ standard doesn't say anything about this.
3930     if ((New->getType()->isDependentType() ||
3931          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3932       // If the old type was dependent, we can't merge with it, so the new type
3933       // becomes dependent for now. We'll reproduce the original type when we
3934       // instantiate the TypeSourceInfo for the variable.
3935       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3936         New->setType(Context.DependentTy);
3937       return;
3938     }
3939     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3940   }
3941 
3942   // Don't actually update the type on the new declaration if the old
3943   // declaration was an extern declaration in a different scope.
3944   if (MergeTypeWithOld)
3945     New->setType(MergedT);
3946 }
3947 
3948 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3949                                   LookupResult &Previous) {
3950   // C11 6.2.7p4:
3951   //   For an identifier with internal or external linkage declared
3952   //   in a scope in which a prior declaration of that identifier is
3953   //   visible, if the prior declaration specifies internal or
3954   //   external linkage, the type of the identifier at the later
3955   //   declaration becomes the composite type.
3956   //
3957   // If the variable isn't visible, we do not merge with its type.
3958   if (Previous.isShadowed())
3959     return false;
3960 
3961   if (S.getLangOpts().CPlusPlus) {
3962     // C++11 [dcl.array]p3:
3963     //   If there is a preceding declaration of the entity in the same
3964     //   scope in which the bound was specified, an omitted array bound
3965     //   is taken to be the same as in that earlier declaration.
3966     return NewVD->isPreviousDeclInSameBlockScope() ||
3967            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3968             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3969   } else {
3970     // If the old declaration was function-local, don't merge with its
3971     // type unless we're in the same function.
3972     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3973            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3974   }
3975 }
3976 
3977 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3978 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3979 /// situation, merging decls or emitting diagnostics as appropriate.
3980 ///
3981 /// Tentative definition rules (C99 6.9.2p2) are checked by
3982 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3983 /// definitions here, since the initializer hasn't been attached.
3984 ///
3985 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3986   // If the new decl is already invalid, don't do any other checking.
3987   if (New->isInvalidDecl())
3988     return;
3989 
3990   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3991     return;
3992 
3993   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3994 
3995   // Verify the old decl was also a variable or variable template.
3996   VarDecl *Old = nullptr;
3997   VarTemplateDecl *OldTemplate = nullptr;
3998   if (Previous.isSingleResult()) {
3999     if (NewTemplate) {
4000       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4001       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4002 
4003       if (auto *Shadow =
4004               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4005         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4006           return New->setInvalidDecl();
4007     } else {
4008       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4009 
4010       if (auto *Shadow =
4011               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4012         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4013           return New->setInvalidDecl();
4014     }
4015   }
4016   if (!Old) {
4017     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4018         << New->getDeclName();
4019     notePreviousDefinition(Previous.getRepresentativeDecl(),
4020                            New->getLocation());
4021     return New->setInvalidDecl();
4022   }
4023 
4024   // Ensure the template parameters are compatible.
4025   if (NewTemplate &&
4026       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4027                                       OldTemplate->getTemplateParameters(),
4028                                       /*Complain=*/true, TPL_TemplateMatch))
4029     return New->setInvalidDecl();
4030 
4031   // C++ [class.mem]p1:
4032   //   A member shall not be declared twice in the member-specification [...]
4033   //
4034   // Here, we need only consider static data members.
4035   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4036     Diag(New->getLocation(), diag::err_duplicate_member)
4037       << New->getIdentifier();
4038     Diag(Old->getLocation(), diag::note_previous_declaration);
4039     New->setInvalidDecl();
4040   }
4041 
4042   mergeDeclAttributes(New, Old);
4043   // Warn if an already-declared variable is made a weak_import in a subsequent
4044   // declaration
4045   if (New->hasAttr<WeakImportAttr>() &&
4046       Old->getStorageClass() == SC_None &&
4047       !Old->hasAttr<WeakImportAttr>()) {
4048     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4049     notePreviousDefinition(Old, New->getLocation());
4050     // Remove weak_import attribute on new declaration.
4051     New->dropAttr<WeakImportAttr>();
4052   }
4053 
4054   if (New->hasAttr<InternalLinkageAttr>() &&
4055       !Old->hasAttr<InternalLinkageAttr>()) {
4056     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4057         << New->getDeclName();
4058     notePreviousDefinition(Old, New->getLocation());
4059     New->dropAttr<InternalLinkageAttr>();
4060   }
4061 
4062   // Merge the types.
4063   VarDecl *MostRecent = Old->getMostRecentDecl();
4064   if (MostRecent != Old) {
4065     MergeVarDeclTypes(New, MostRecent,
4066                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4067     if (New->isInvalidDecl())
4068       return;
4069   }
4070 
4071   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4072   if (New->isInvalidDecl())
4073     return;
4074 
4075   diag::kind PrevDiag;
4076   SourceLocation OldLocation;
4077   std::tie(PrevDiag, OldLocation) =
4078       getNoteDiagForInvalidRedeclaration(Old, New);
4079 
4080   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4081   if (New->getStorageClass() == SC_Static &&
4082       !New->isStaticDataMember() &&
4083       Old->hasExternalFormalLinkage()) {
4084     if (getLangOpts().MicrosoftExt) {
4085       Diag(New->getLocation(), diag::ext_static_non_static)
4086           << New->getDeclName();
4087       Diag(OldLocation, PrevDiag);
4088     } else {
4089       Diag(New->getLocation(), diag::err_static_non_static)
4090           << New->getDeclName();
4091       Diag(OldLocation, PrevDiag);
4092       return New->setInvalidDecl();
4093     }
4094   }
4095   // C99 6.2.2p4:
4096   //   For an identifier declared with the storage-class specifier
4097   //   extern in a scope in which a prior declaration of that
4098   //   identifier is visible,23) if the prior declaration specifies
4099   //   internal or external linkage, the linkage of the identifier at
4100   //   the later declaration is the same as the linkage specified at
4101   //   the prior declaration. If no prior declaration is visible, or
4102   //   if the prior declaration specifies no linkage, then the
4103   //   identifier has external linkage.
4104   if (New->hasExternalStorage() && Old->hasLinkage())
4105     /* Okay */;
4106   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4107            !New->isStaticDataMember() &&
4108            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4109     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4110     Diag(OldLocation, PrevDiag);
4111     return New->setInvalidDecl();
4112   }
4113 
4114   // Check if extern is followed by non-extern and vice-versa.
4115   if (New->hasExternalStorage() &&
4116       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4117     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4118     Diag(OldLocation, PrevDiag);
4119     return New->setInvalidDecl();
4120   }
4121   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4122       !New->hasExternalStorage()) {
4123     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4124     Diag(OldLocation, PrevDiag);
4125     return New->setInvalidDecl();
4126   }
4127 
4128   if (CheckRedeclarationModuleOwnership(New, Old))
4129     return;
4130 
4131   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4132 
4133   // FIXME: The test for external storage here seems wrong? We still
4134   // need to check for mismatches.
4135   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4136       // Don't complain about out-of-line definitions of static members.
4137       !(Old->getLexicalDeclContext()->isRecord() &&
4138         !New->getLexicalDeclContext()->isRecord())) {
4139     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4140     Diag(OldLocation, PrevDiag);
4141     return New->setInvalidDecl();
4142   }
4143 
4144   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4145     if (VarDecl *Def = Old->getDefinition()) {
4146       // C++1z [dcl.fcn.spec]p4:
4147       //   If the definition of a variable appears in a translation unit before
4148       //   its first declaration as inline, the program is ill-formed.
4149       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4150       Diag(Def->getLocation(), diag::note_previous_definition);
4151     }
4152   }
4153 
4154   // If this redeclaration makes the variable inline, we may need to add it to
4155   // UndefinedButUsed.
4156   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4157       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4158     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4159                                            SourceLocation()));
4160 
4161   if (New->getTLSKind() != Old->getTLSKind()) {
4162     if (!Old->getTLSKind()) {
4163       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4164       Diag(OldLocation, PrevDiag);
4165     } else if (!New->getTLSKind()) {
4166       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4167       Diag(OldLocation, PrevDiag);
4168     } else {
4169       // Do not allow redeclaration to change the variable between requiring
4170       // static and dynamic initialization.
4171       // FIXME: GCC allows this, but uses the TLS keyword on the first
4172       // declaration to determine the kind. Do we need to be compatible here?
4173       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4174         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4175       Diag(OldLocation, PrevDiag);
4176     }
4177   }
4178 
4179   // C++ doesn't have tentative definitions, so go right ahead and check here.
4180   if (getLangOpts().CPlusPlus &&
4181       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4182     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4183         Old->getCanonicalDecl()->isConstexpr()) {
4184       // This definition won't be a definition any more once it's been merged.
4185       Diag(New->getLocation(),
4186            diag::warn_deprecated_redundant_constexpr_static_def);
4187     } else if (VarDecl *Def = Old->getDefinition()) {
4188       if (checkVarDeclRedefinition(Def, New))
4189         return;
4190     }
4191   }
4192 
4193   if (haveIncompatibleLanguageLinkages(Old, New)) {
4194     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4195     Diag(OldLocation, PrevDiag);
4196     New->setInvalidDecl();
4197     return;
4198   }
4199 
4200   // Merge "used" flag.
4201   if (Old->getMostRecentDecl()->isUsed(false))
4202     New->setIsUsed();
4203 
4204   // Keep a chain of previous declarations.
4205   New->setPreviousDecl(Old);
4206   if (NewTemplate)
4207     NewTemplate->setPreviousDecl(OldTemplate);
4208   adjustDeclContextForDeclaratorDecl(New, Old);
4209 
4210   // Inherit access appropriately.
4211   New->setAccess(Old->getAccess());
4212   if (NewTemplate)
4213     NewTemplate->setAccess(New->getAccess());
4214 
4215   if (Old->isInline())
4216     New->setImplicitlyInline();
4217 }
4218 
4219 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4220   SourceManager &SrcMgr = getSourceManager();
4221   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4222   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4223   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4224   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4225   auto &HSI = PP.getHeaderSearchInfo();
4226   StringRef HdrFilename =
4227       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4228 
4229   auto noteFromModuleOrInclude = [&](Module *Mod,
4230                                      SourceLocation IncLoc) -> bool {
4231     // Redefinition errors with modules are common with non modular mapped
4232     // headers, example: a non-modular header H in module A that also gets
4233     // included directly in a TU. Pointing twice to the same header/definition
4234     // is confusing, try to get better diagnostics when modules is on.
4235     if (IncLoc.isValid()) {
4236       if (Mod) {
4237         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4238             << HdrFilename.str() << Mod->getFullModuleName();
4239         if (!Mod->DefinitionLoc.isInvalid())
4240           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4241               << Mod->getFullModuleName();
4242       } else {
4243         Diag(IncLoc, diag::note_redefinition_include_same_file)
4244             << HdrFilename.str();
4245       }
4246       return true;
4247     }
4248 
4249     return false;
4250   };
4251 
4252   // Is it the same file and same offset? Provide more information on why
4253   // this leads to a redefinition error.
4254   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4255     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4256     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4257     bool EmittedDiag =
4258         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4259     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4260 
4261     // If the header has no guards, emit a note suggesting one.
4262     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4263       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4264 
4265     if (EmittedDiag)
4266       return;
4267   }
4268 
4269   // Redefinition coming from different files or couldn't do better above.
4270   if (Old->getLocation().isValid())
4271     Diag(Old->getLocation(), diag::note_previous_definition);
4272 }
4273 
4274 /// We've just determined that \p Old and \p New both appear to be definitions
4275 /// of the same variable. Either diagnose or fix the problem.
4276 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4277   if (!hasVisibleDefinition(Old) &&
4278       (New->getFormalLinkage() == InternalLinkage ||
4279        New->isInline() ||
4280        New->getDescribedVarTemplate() ||
4281        New->getNumTemplateParameterLists() ||
4282        New->getDeclContext()->isDependentContext())) {
4283     // The previous definition is hidden, and multiple definitions are
4284     // permitted (in separate TUs). Demote this to a declaration.
4285     New->demoteThisDefinitionToDeclaration();
4286 
4287     // Make the canonical definition visible.
4288     if (auto *OldTD = Old->getDescribedVarTemplate())
4289       makeMergedDefinitionVisible(OldTD);
4290     makeMergedDefinitionVisible(Old);
4291     return false;
4292   } else {
4293     Diag(New->getLocation(), diag::err_redefinition) << New;
4294     notePreviousDefinition(Old, New->getLocation());
4295     New->setInvalidDecl();
4296     return true;
4297   }
4298 }
4299 
4300 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4301 /// no declarator (e.g. "struct foo;") is parsed.
4302 Decl *
4303 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4304                                  RecordDecl *&AnonRecord) {
4305   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4306                                     AnonRecord);
4307 }
4308 
4309 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4310 // disambiguate entities defined in different scopes.
4311 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4312 // compatibility.
4313 // We will pick our mangling number depending on which version of MSVC is being
4314 // targeted.
4315 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4316   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4317              ? S->getMSCurManglingNumber()
4318              : S->getMSLastManglingNumber();
4319 }
4320 
4321 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4322   if (!Context.getLangOpts().CPlusPlus)
4323     return;
4324 
4325   if (isa<CXXRecordDecl>(Tag->getParent())) {
4326     // If this tag is the direct child of a class, number it if
4327     // it is anonymous.
4328     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4329       return;
4330     MangleNumberingContext &MCtx =
4331         Context.getManglingNumberContext(Tag->getParent());
4332     Context.setManglingNumber(
4333         Tag, MCtx.getManglingNumber(
4334                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4335     return;
4336   }
4337 
4338   // If this tag isn't a direct child of a class, number it if it is local.
4339   MangleNumberingContext *MCtx;
4340   Decl *ManglingContextDecl;
4341   std::tie(MCtx, ManglingContextDecl) =
4342       getCurrentMangleNumberContext(Tag->getDeclContext());
4343   if (MCtx) {
4344     Context.setManglingNumber(
4345         Tag, MCtx->getManglingNumber(
4346                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4347   }
4348 }
4349 
4350 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4351                                         TypedefNameDecl *NewTD) {
4352   if (TagFromDeclSpec->isInvalidDecl())
4353     return;
4354 
4355   // Do nothing if the tag already has a name for linkage purposes.
4356   if (TagFromDeclSpec->hasNameForLinkage())
4357     return;
4358 
4359   // A well-formed anonymous tag must always be a TUK_Definition.
4360   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4361 
4362   // The type must match the tag exactly;  no qualifiers allowed.
4363   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4364                            Context.getTagDeclType(TagFromDeclSpec))) {
4365     if (getLangOpts().CPlusPlus)
4366       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4367     return;
4368   }
4369 
4370   // If we've already computed linkage for the anonymous tag, then
4371   // adding a typedef name for the anonymous decl can change that
4372   // linkage, which might be a serious problem.  Diagnose this as
4373   // unsupported and ignore the typedef name.  TODO: we should
4374   // pursue this as a language defect and establish a formal rule
4375   // for how to handle it.
4376   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4377     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4378 
4379     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4380     tagLoc = getLocForEndOfToken(tagLoc);
4381 
4382     llvm::SmallString<40> textToInsert;
4383     textToInsert += ' ';
4384     textToInsert += NewTD->getIdentifier()->getName();
4385     Diag(tagLoc, diag::note_typedef_changes_linkage)
4386         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4387     return;
4388   }
4389 
4390   // Otherwise, set this is the anon-decl typedef for the tag.
4391   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4392 }
4393 
4394 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4395   switch (T) {
4396   case DeclSpec::TST_class:
4397     return 0;
4398   case DeclSpec::TST_struct:
4399     return 1;
4400   case DeclSpec::TST_interface:
4401     return 2;
4402   case DeclSpec::TST_union:
4403     return 3;
4404   case DeclSpec::TST_enum:
4405     return 4;
4406   default:
4407     llvm_unreachable("unexpected type specifier");
4408   }
4409 }
4410 
4411 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4412 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4413 /// parameters to cope with template friend declarations.
4414 Decl *
4415 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4416                                  MultiTemplateParamsArg TemplateParams,
4417                                  bool IsExplicitInstantiation,
4418                                  RecordDecl *&AnonRecord) {
4419   Decl *TagD = nullptr;
4420   TagDecl *Tag = nullptr;
4421   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4422       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4423       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4424       DS.getTypeSpecType() == DeclSpec::TST_union ||
4425       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4426     TagD = DS.getRepAsDecl();
4427 
4428     if (!TagD) // We probably had an error
4429       return nullptr;
4430 
4431     // Note that the above type specs guarantee that the
4432     // type rep is a Decl, whereas in many of the others
4433     // it's a Type.
4434     if (isa<TagDecl>(TagD))
4435       Tag = cast<TagDecl>(TagD);
4436     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4437       Tag = CTD->getTemplatedDecl();
4438   }
4439 
4440   if (Tag) {
4441     handleTagNumbering(Tag, S);
4442     Tag->setFreeStanding();
4443     if (Tag->isInvalidDecl())
4444       return Tag;
4445   }
4446 
4447   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4448     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4449     // or incomplete types shall not be restrict-qualified."
4450     if (TypeQuals & DeclSpec::TQ_restrict)
4451       Diag(DS.getRestrictSpecLoc(),
4452            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4453            << DS.getSourceRange();
4454   }
4455 
4456   if (DS.isInlineSpecified())
4457     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4458         << getLangOpts().CPlusPlus17;
4459 
4460   if (DS.hasConstexprSpecifier()) {
4461     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4462     // and definitions of functions and variables.
4463     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4464     // the declaration of a function or function template
4465     if (Tag)
4466       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4467           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4468           << DS.getConstexprSpecifier();
4469     else
4470       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4471           << DS.getConstexprSpecifier();
4472     // Don't emit warnings after this error.
4473     return TagD;
4474   }
4475 
4476   DiagnoseFunctionSpecifiers(DS);
4477 
4478   if (DS.isFriendSpecified()) {
4479     // If we're dealing with a decl but not a TagDecl, assume that
4480     // whatever routines created it handled the friendship aspect.
4481     if (TagD && !Tag)
4482       return nullptr;
4483     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4484   }
4485 
4486   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4487   bool IsExplicitSpecialization =
4488     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4489   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4490       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4491       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4492     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4493     // nested-name-specifier unless it is an explicit instantiation
4494     // or an explicit specialization.
4495     //
4496     // FIXME: We allow class template partial specializations here too, per the
4497     // obvious intent of DR1819.
4498     //
4499     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4500     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4501         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4502     return nullptr;
4503   }
4504 
4505   // Track whether this decl-specifier declares anything.
4506   bool DeclaresAnything = true;
4507 
4508   // Handle anonymous struct definitions.
4509   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4510     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4511         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4512       if (getLangOpts().CPlusPlus ||
4513           Record->getDeclContext()->isRecord()) {
4514         // If CurContext is a DeclContext that can contain statements,
4515         // RecursiveASTVisitor won't visit the decls that
4516         // BuildAnonymousStructOrUnion() will put into CurContext.
4517         // Also store them here so that they can be part of the
4518         // DeclStmt that gets created in this case.
4519         // FIXME: Also return the IndirectFieldDecls created by
4520         // BuildAnonymousStructOr union, for the same reason?
4521         if (CurContext->isFunctionOrMethod())
4522           AnonRecord = Record;
4523         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4524                                            Context.getPrintingPolicy());
4525       }
4526 
4527       DeclaresAnything = false;
4528     }
4529   }
4530 
4531   // C11 6.7.2.1p2:
4532   //   A struct-declaration that does not declare an anonymous structure or
4533   //   anonymous union shall contain a struct-declarator-list.
4534   //
4535   // This rule also existed in C89 and C99; the grammar for struct-declaration
4536   // did not permit a struct-declaration without a struct-declarator-list.
4537   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4538       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4539     // Check for Microsoft C extension: anonymous struct/union member.
4540     // Handle 2 kinds of anonymous struct/union:
4541     //   struct STRUCT;
4542     //   union UNION;
4543     // and
4544     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4545     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4546     if ((Tag && Tag->getDeclName()) ||
4547         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4548       RecordDecl *Record = nullptr;
4549       if (Tag)
4550         Record = dyn_cast<RecordDecl>(Tag);
4551       else if (const RecordType *RT =
4552                    DS.getRepAsType().get()->getAsStructureType())
4553         Record = RT->getDecl();
4554       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4555         Record = UT->getDecl();
4556 
4557       if (Record && getLangOpts().MicrosoftExt) {
4558         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4559             << Record->isUnion() << DS.getSourceRange();
4560         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4561       }
4562 
4563       DeclaresAnything = false;
4564     }
4565   }
4566 
4567   // Skip all the checks below if we have a type error.
4568   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4569       (TagD && TagD->isInvalidDecl()))
4570     return TagD;
4571 
4572   if (getLangOpts().CPlusPlus &&
4573       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4574     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4575       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4576           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4577         DeclaresAnything = false;
4578 
4579   if (!DS.isMissingDeclaratorOk()) {
4580     // Customize diagnostic for a typedef missing a name.
4581     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4582       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4583           << DS.getSourceRange();
4584     else
4585       DeclaresAnything = false;
4586   }
4587 
4588   if (DS.isModulePrivateSpecified() &&
4589       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4590     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4591       << Tag->getTagKind()
4592       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4593 
4594   ActOnDocumentableDecl(TagD);
4595 
4596   // C 6.7/2:
4597   //   A declaration [...] shall declare at least a declarator [...], a tag,
4598   //   or the members of an enumeration.
4599   // C++ [dcl.dcl]p3:
4600   //   [If there are no declarators], and except for the declaration of an
4601   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4602   //   names into the program, or shall redeclare a name introduced by a
4603   //   previous declaration.
4604   if (!DeclaresAnything) {
4605     // In C, we allow this as a (popular) extension / bug. Don't bother
4606     // producing further diagnostics for redundant qualifiers after this.
4607     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4608     return TagD;
4609   }
4610 
4611   // C++ [dcl.stc]p1:
4612   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4613   //   init-declarator-list of the declaration shall not be empty.
4614   // C++ [dcl.fct.spec]p1:
4615   //   If a cv-qualifier appears in a decl-specifier-seq, the
4616   //   init-declarator-list of the declaration shall not be empty.
4617   //
4618   // Spurious qualifiers here appear to be valid in C.
4619   unsigned DiagID = diag::warn_standalone_specifier;
4620   if (getLangOpts().CPlusPlus)
4621     DiagID = diag::ext_standalone_specifier;
4622 
4623   // Note that a linkage-specification sets a storage class, but
4624   // 'extern "C" struct foo;' is actually valid and not theoretically
4625   // useless.
4626   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4627     if (SCS == DeclSpec::SCS_mutable)
4628       // Since mutable is not a viable storage class specifier in C, there is
4629       // no reason to treat it as an extension. Instead, diagnose as an error.
4630       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4631     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4632       Diag(DS.getStorageClassSpecLoc(), DiagID)
4633         << DeclSpec::getSpecifierName(SCS);
4634   }
4635 
4636   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4637     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4638       << DeclSpec::getSpecifierName(TSCS);
4639   if (DS.getTypeQualifiers()) {
4640     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4641       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4642     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4643       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4644     // Restrict is covered above.
4645     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4646       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4647     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4648       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4649   }
4650 
4651   // Warn about ignored type attributes, for example:
4652   // __attribute__((aligned)) struct A;
4653   // Attributes should be placed after tag to apply to type declaration.
4654   if (!DS.getAttributes().empty()) {
4655     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4656     if (TypeSpecType == DeclSpec::TST_class ||
4657         TypeSpecType == DeclSpec::TST_struct ||
4658         TypeSpecType == DeclSpec::TST_interface ||
4659         TypeSpecType == DeclSpec::TST_union ||
4660         TypeSpecType == DeclSpec::TST_enum) {
4661       for (const ParsedAttr &AL : DS.getAttributes())
4662         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4663             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4664     }
4665   }
4666 
4667   return TagD;
4668 }
4669 
4670 /// We are trying to inject an anonymous member into the given scope;
4671 /// check if there's an existing declaration that can't be overloaded.
4672 ///
4673 /// \return true if this is a forbidden redeclaration
4674 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4675                                          Scope *S,
4676                                          DeclContext *Owner,
4677                                          DeclarationName Name,
4678                                          SourceLocation NameLoc,
4679                                          bool IsUnion) {
4680   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4681                  Sema::ForVisibleRedeclaration);
4682   if (!SemaRef.LookupName(R, S)) return false;
4683 
4684   // Pick a representative declaration.
4685   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4686   assert(PrevDecl && "Expected a non-null Decl");
4687 
4688   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4689     return false;
4690 
4691   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4692     << IsUnion << Name;
4693   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4694 
4695   return true;
4696 }
4697 
4698 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4699 /// anonymous struct or union AnonRecord into the owning context Owner
4700 /// and scope S. This routine will be invoked just after we realize
4701 /// that an unnamed union or struct is actually an anonymous union or
4702 /// struct, e.g.,
4703 ///
4704 /// @code
4705 /// union {
4706 ///   int i;
4707 ///   float f;
4708 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4709 ///    // f into the surrounding scope.x
4710 /// @endcode
4711 ///
4712 /// This routine is recursive, injecting the names of nested anonymous
4713 /// structs/unions into the owning context and scope as well.
4714 static bool
4715 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4716                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4717                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4718   bool Invalid = false;
4719 
4720   // Look every FieldDecl and IndirectFieldDecl with a name.
4721   for (auto *D : AnonRecord->decls()) {
4722     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4723         cast<NamedDecl>(D)->getDeclName()) {
4724       ValueDecl *VD = cast<ValueDecl>(D);
4725       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4726                                        VD->getLocation(),
4727                                        AnonRecord->isUnion())) {
4728         // C++ [class.union]p2:
4729         //   The names of the members of an anonymous union shall be
4730         //   distinct from the names of any other entity in the
4731         //   scope in which the anonymous union is declared.
4732         Invalid = true;
4733       } else {
4734         // C++ [class.union]p2:
4735         //   For the purpose of name lookup, after the anonymous union
4736         //   definition, the members of the anonymous union are
4737         //   considered to have been defined in the scope in which the
4738         //   anonymous union is declared.
4739         unsigned OldChainingSize = Chaining.size();
4740         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4741           Chaining.append(IF->chain_begin(), IF->chain_end());
4742         else
4743           Chaining.push_back(VD);
4744 
4745         assert(Chaining.size() >= 2);
4746         NamedDecl **NamedChain =
4747           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4748         for (unsigned i = 0; i < Chaining.size(); i++)
4749           NamedChain[i] = Chaining[i];
4750 
4751         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4752             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4753             VD->getType(), {NamedChain, Chaining.size()});
4754 
4755         for (const auto *Attr : VD->attrs())
4756           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4757 
4758         IndirectField->setAccess(AS);
4759         IndirectField->setImplicit();
4760         SemaRef.PushOnScopeChains(IndirectField, S);
4761 
4762         // That includes picking up the appropriate access specifier.
4763         if (AS != AS_none) IndirectField->setAccess(AS);
4764 
4765         Chaining.resize(OldChainingSize);
4766       }
4767     }
4768   }
4769 
4770   return Invalid;
4771 }
4772 
4773 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4774 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4775 /// illegal input values are mapped to SC_None.
4776 static StorageClass
4777 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4778   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4779   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4780          "Parser allowed 'typedef' as storage class VarDecl.");
4781   switch (StorageClassSpec) {
4782   case DeclSpec::SCS_unspecified:    return SC_None;
4783   case DeclSpec::SCS_extern:
4784     if (DS.isExternInLinkageSpec())
4785       return SC_None;
4786     return SC_Extern;
4787   case DeclSpec::SCS_static:         return SC_Static;
4788   case DeclSpec::SCS_auto:           return SC_Auto;
4789   case DeclSpec::SCS_register:       return SC_Register;
4790   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4791     // Illegal SCSs map to None: error reporting is up to the caller.
4792   case DeclSpec::SCS_mutable:        // Fall through.
4793   case DeclSpec::SCS_typedef:        return SC_None;
4794   }
4795   llvm_unreachable("unknown storage class specifier");
4796 }
4797 
4798 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4799   assert(Record->hasInClassInitializer());
4800 
4801   for (const auto *I : Record->decls()) {
4802     const auto *FD = dyn_cast<FieldDecl>(I);
4803     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4804       FD = IFD->getAnonField();
4805     if (FD && FD->hasInClassInitializer())
4806       return FD->getLocation();
4807   }
4808 
4809   llvm_unreachable("couldn't find in-class initializer");
4810 }
4811 
4812 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4813                                       SourceLocation DefaultInitLoc) {
4814   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4815     return;
4816 
4817   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4818   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4819 }
4820 
4821 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4822                                       CXXRecordDecl *AnonUnion) {
4823   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4824     return;
4825 
4826   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4827 }
4828 
4829 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4830 /// anonymous structure or union. Anonymous unions are a C++ feature
4831 /// (C++ [class.union]) and a C11 feature; anonymous structures
4832 /// are a C11 feature and GNU C++ extension.
4833 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4834                                         AccessSpecifier AS,
4835                                         RecordDecl *Record,
4836                                         const PrintingPolicy &Policy) {
4837   DeclContext *Owner = Record->getDeclContext();
4838 
4839   // Diagnose whether this anonymous struct/union is an extension.
4840   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4841     Diag(Record->getLocation(), diag::ext_anonymous_union);
4842   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4843     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4844   else if (!Record->isUnion() && !getLangOpts().C11)
4845     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4846 
4847   // C and C++ require different kinds of checks for anonymous
4848   // structs/unions.
4849   bool Invalid = false;
4850   if (getLangOpts().CPlusPlus) {
4851     const char *PrevSpec = nullptr;
4852     if (Record->isUnion()) {
4853       // C++ [class.union]p6:
4854       // C++17 [class.union.anon]p2:
4855       //   Anonymous unions declared in a named namespace or in the
4856       //   global namespace shall be declared static.
4857       unsigned DiagID;
4858       DeclContext *OwnerScope = Owner->getRedeclContext();
4859       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4860           (OwnerScope->isTranslationUnit() ||
4861            (OwnerScope->isNamespace() &&
4862             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4863         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4864           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4865 
4866         // Recover by adding 'static'.
4867         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4868                                PrevSpec, DiagID, Policy);
4869       }
4870       // C++ [class.union]p6:
4871       //   A storage class is not allowed in a declaration of an
4872       //   anonymous union in a class scope.
4873       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4874                isa<RecordDecl>(Owner)) {
4875         Diag(DS.getStorageClassSpecLoc(),
4876              diag::err_anonymous_union_with_storage_spec)
4877           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4878 
4879         // Recover by removing the storage specifier.
4880         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4881                                SourceLocation(),
4882                                PrevSpec, DiagID, Context.getPrintingPolicy());
4883       }
4884     }
4885 
4886     // Ignore const/volatile/restrict qualifiers.
4887     if (DS.getTypeQualifiers()) {
4888       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4889         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4890           << Record->isUnion() << "const"
4891           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4892       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4893         Diag(DS.getVolatileSpecLoc(),
4894              diag::ext_anonymous_struct_union_qualified)
4895           << Record->isUnion() << "volatile"
4896           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4897       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4898         Diag(DS.getRestrictSpecLoc(),
4899              diag::ext_anonymous_struct_union_qualified)
4900           << Record->isUnion() << "restrict"
4901           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4902       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4903         Diag(DS.getAtomicSpecLoc(),
4904              diag::ext_anonymous_struct_union_qualified)
4905           << Record->isUnion() << "_Atomic"
4906           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4907       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4908         Diag(DS.getUnalignedSpecLoc(),
4909              diag::ext_anonymous_struct_union_qualified)
4910           << Record->isUnion() << "__unaligned"
4911           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4912 
4913       DS.ClearTypeQualifiers();
4914     }
4915 
4916     // C++ [class.union]p2:
4917     //   The member-specification of an anonymous union shall only
4918     //   define non-static data members. [Note: nested types and
4919     //   functions cannot be declared within an anonymous union. ]
4920     for (auto *Mem : Record->decls()) {
4921       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4922         // C++ [class.union]p3:
4923         //   An anonymous union shall not have private or protected
4924         //   members (clause 11).
4925         assert(FD->getAccess() != AS_none);
4926         if (FD->getAccess() != AS_public) {
4927           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4928             << Record->isUnion() << (FD->getAccess() == AS_protected);
4929           Invalid = true;
4930         }
4931 
4932         // C++ [class.union]p1
4933         //   An object of a class with a non-trivial constructor, a non-trivial
4934         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4935         //   assignment operator cannot be a member of a union, nor can an
4936         //   array of such objects.
4937         if (CheckNontrivialField(FD))
4938           Invalid = true;
4939       } else if (Mem->isImplicit()) {
4940         // Any implicit members are fine.
4941       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4942         // This is a type that showed up in an
4943         // elaborated-type-specifier inside the anonymous struct or
4944         // union, but which actually declares a type outside of the
4945         // anonymous struct or union. It's okay.
4946       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4947         if (!MemRecord->isAnonymousStructOrUnion() &&
4948             MemRecord->getDeclName()) {
4949           // Visual C++ allows type definition in anonymous struct or union.
4950           if (getLangOpts().MicrosoftExt)
4951             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4952               << Record->isUnion();
4953           else {
4954             // This is a nested type declaration.
4955             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4956               << Record->isUnion();
4957             Invalid = true;
4958           }
4959         } else {
4960           // This is an anonymous type definition within another anonymous type.
4961           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4962           // not part of standard C++.
4963           Diag(MemRecord->getLocation(),
4964                diag::ext_anonymous_record_with_anonymous_type)
4965             << Record->isUnion();
4966         }
4967       } else if (isa<AccessSpecDecl>(Mem)) {
4968         // Any access specifier is fine.
4969       } else if (isa<StaticAssertDecl>(Mem)) {
4970         // In C++1z, static_assert declarations are also fine.
4971       } else {
4972         // We have something that isn't a non-static data
4973         // member. Complain about it.
4974         unsigned DK = diag::err_anonymous_record_bad_member;
4975         if (isa<TypeDecl>(Mem))
4976           DK = diag::err_anonymous_record_with_type;
4977         else if (isa<FunctionDecl>(Mem))
4978           DK = diag::err_anonymous_record_with_function;
4979         else if (isa<VarDecl>(Mem))
4980           DK = diag::err_anonymous_record_with_static;
4981 
4982         // Visual C++ allows type definition in anonymous struct or union.
4983         if (getLangOpts().MicrosoftExt &&
4984             DK == diag::err_anonymous_record_with_type)
4985           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4986             << Record->isUnion();
4987         else {
4988           Diag(Mem->getLocation(), DK) << Record->isUnion();
4989           Invalid = true;
4990         }
4991       }
4992     }
4993 
4994     // C++11 [class.union]p8 (DR1460):
4995     //   At most one variant member of a union may have a
4996     //   brace-or-equal-initializer.
4997     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4998         Owner->isRecord())
4999       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5000                                 cast<CXXRecordDecl>(Record));
5001   }
5002 
5003   if (!Record->isUnion() && !Owner->isRecord()) {
5004     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5005       << getLangOpts().CPlusPlus;
5006     Invalid = true;
5007   }
5008 
5009   // C++ [dcl.dcl]p3:
5010   //   [If there are no declarators], and except for the declaration of an
5011   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5012   //   names into the program
5013   // C++ [class.mem]p2:
5014   //   each such member-declaration shall either declare at least one member
5015   //   name of the class or declare at least one unnamed bit-field
5016   //
5017   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5018   if (getLangOpts().CPlusPlus && Record->field_empty())
5019     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5020 
5021   // Mock up a declarator.
5022   Declarator Dc(DS, DeclaratorContext::MemberContext);
5023   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5024   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5025 
5026   // Create a declaration for this anonymous struct/union.
5027   NamedDecl *Anon = nullptr;
5028   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5029     Anon = FieldDecl::Create(
5030         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5031         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5032         /*BitWidth=*/nullptr, /*Mutable=*/false,
5033         /*InitStyle=*/ICIS_NoInit);
5034     Anon->setAccess(AS);
5035     if (getLangOpts().CPlusPlus)
5036       FieldCollector->Add(cast<FieldDecl>(Anon));
5037   } else {
5038     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5039     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5040     if (SCSpec == DeclSpec::SCS_mutable) {
5041       // mutable can only appear on non-static class members, so it's always
5042       // an error here
5043       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5044       Invalid = true;
5045       SC = SC_None;
5046     }
5047 
5048     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5049                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5050                            Context.getTypeDeclType(Record), TInfo, SC);
5051 
5052     // Default-initialize the implicit variable. This initialization will be
5053     // trivial in almost all cases, except if a union member has an in-class
5054     // initializer:
5055     //   union { int n = 0; };
5056     ActOnUninitializedDecl(Anon);
5057   }
5058   Anon->setImplicit();
5059 
5060   // Mark this as an anonymous struct/union type.
5061   Record->setAnonymousStructOrUnion(true);
5062 
5063   // Add the anonymous struct/union object to the current
5064   // context. We'll be referencing this object when we refer to one of
5065   // its members.
5066   Owner->addDecl(Anon);
5067 
5068   // Inject the members of the anonymous struct/union into the owning
5069   // context and into the identifier resolver chain for name lookup
5070   // purposes.
5071   SmallVector<NamedDecl*, 2> Chain;
5072   Chain.push_back(Anon);
5073 
5074   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5075     Invalid = true;
5076 
5077   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5078     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5079       MangleNumberingContext *MCtx;
5080       Decl *ManglingContextDecl;
5081       std::tie(MCtx, ManglingContextDecl) =
5082           getCurrentMangleNumberContext(NewVD->getDeclContext());
5083       if (MCtx) {
5084         Context.setManglingNumber(
5085             NewVD, MCtx->getManglingNumber(
5086                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5087         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5088       }
5089     }
5090   }
5091 
5092   if (Invalid)
5093     Anon->setInvalidDecl();
5094 
5095   return Anon;
5096 }
5097 
5098 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5099 /// Microsoft C anonymous structure.
5100 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5101 /// Example:
5102 ///
5103 /// struct A { int a; };
5104 /// struct B { struct A; int b; };
5105 ///
5106 /// void foo() {
5107 ///   B var;
5108 ///   var.a = 3;
5109 /// }
5110 ///
5111 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5112                                            RecordDecl *Record) {
5113   assert(Record && "expected a record!");
5114 
5115   // Mock up a declarator.
5116   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5117   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5118   assert(TInfo && "couldn't build declarator info for anonymous struct");
5119 
5120   auto *ParentDecl = cast<RecordDecl>(CurContext);
5121   QualType RecTy = Context.getTypeDeclType(Record);
5122 
5123   // Create a declaration for this anonymous struct.
5124   NamedDecl *Anon =
5125       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5126                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5127                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5128                         /*InitStyle=*/ICIS_NoInit);
5129   Anon->setImplicit();
5130 
5131   // Add the anonymous struct object to the current context.
5132   CurContext->addDecl(Anon);
5133 
5134   // Inject the members of the anonymous struct into the current
5135   // context and into the identifier resolver chain for name lookup
5136   // purposes.
5137   SmallVector<NamedDecl*, 2> Chain;
5138   Chain.push_back(Anon);
5139 
5140   RecordDecl *RecordDef = Record->getDefinition();
5141   if (RequireCompleteType(Anon->getLocation(), RecTy,
5142                           diag::err_field_incomplete) ||
5143       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5144                                           AS_none, Chain)) {
5145     Anon->setInvalidDecl();
5146     ParentDecl->setInvalidDecl();
5147   }
5148 
5149   return Anon;
5150 }
5151 
5152 /// GetNameForDeclarator - Determine the full declaration name for the
5153 /// given Declarator.
5154 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5155   return GetNameFromUnqualifiedId(D.getName());
5156 }
5157 
5158 /// Retrieves the declaration name from a parsed unqualified-id.
5159 DeclarationNameInfo
5160 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5161   DeclarationNameInfo NameInfo;
5162   NameInfo.setLoc(Name.StartLocation);
5163 
5164   switch (Name.getKind()) {
5165 
5166   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5167   case UnqualifiedIdKind::IK_Identifier:
5168     NameInfo.setName(Name.Identifier);
5169     return NameInfo;
5170 
5171   case UnqualifiedIdKind::IK_DeductionGuideName: {
5172     // C++ [temp.deduct.guide]p3:
5173     //   The simple-template-id shall name a class template specialization.
5174     //   The template-name shall be the same identifier as the template-name
5175     //   of the simple-template-id.
5176     // These together intend to imply that the template-name shall name a
5177     // class template.
5178     // FIXME: template<typename T> struct X {};
5179     //        template<typename T> using Y = X<T>;
5180     //        Y(int) -> Y<int>;
5181     //   satisfies these rules but does not name a class template.
5182     TemplateName TN = Name.TemplateName.get().get();
5183     auto *Template = TN.getAsTemplateDecl();
5184     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5185       Diag(Name.StartLocation,
5186            diag::err_deduction_guide_name_not_class_template)
5187         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5188       if (Template)
5189         Diag(Template->getLocation(), diag::note_template_decl_here);
5190       return DeclarationNameInfo();
5191     }
5192 
5193     NameInfo.setName(
5194         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5195     return NameInfo;
5196   }
5197 
5198   case UnqualifiedIdKind::IK_OperatorFunctionId:
5199     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5200                                            Name.OperatorFunctionId.Operator));
5201     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5202       = Name.OperatorFunctionId.SymbolLocations[0];
5203     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5204       = Name.EndLocation.getRawEncoding();
5205     return NameInfo;
5206 
5207   case UnqualifiedIdKind::IK_LiteralOperatorId:
5208     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5209                                                            Name.Identifier));
5210     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5211     return NameInfo;
5212 
5213   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5214     TypeSourceInfo *TInfo;
5215     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5216     if (Ty.isNull())
5217       return DeclarationNameInfo();
5218     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5219                                                Context.getCanonicalType(Ty)));
5220     NameInfo.setNamedTypeInfo(TInfo);
5221     return NameInfo;
5222   }
5223 
5224   case UnqualifiedIdKind::IK_ConstructorName: {
5225     TypeSourceInfo *TInfo;
5226     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5227     if (Ty.isNull())
5228       return DeclarationNameInfo();
5229     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5230                                               Context.getCanonicalType(Ty)));
5231     NameInfo.setNamedTypeInfo(TInfo);
5232     return NameInfo;
5233   }
5234 
5235   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5236     // In well-formed code, we can only have a constructor
5237     // template-id that refers to the current context, so go there
5238     // to find the actual type being constructed.
5239     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5240     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5241       return DeclarationNameInfo();
5242 
5243     // Determine the type of the class being constructed.
5244     QualType CurClassType = Context.getTypeDeclType(CurClass);
5245 
5246     // FIXME: Check two things: that the template-id names the same type as
5247     // CurClassType, and that the template-id does not occur when the name
5248     // was qualified.
5249 
5250     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5251                                     Context.getCanonicalType(CurClassType)));
5252     // FIXME: should we retrieve TypeSourceInfo?
5253     NameInfo.setNamedTypeInfo(nullptr);
5254     return NameInfo;
5255   }
5256 
5257   case UnqualifiedIdKind::IK_DestructorName: {
5258     TypeSourceInfo *TInfo;
5259     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5260     if (Ty.isNull())
5261       return DeclarationNameInfo();
5262     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5263                                               Context.getCanonicalType(Ty)));
5264     NameInfo.setNamedTypeInfo(TInfo);
5265     return NameInfo;
5266   }
5267 
5268   case UnqualifiedIdKind::IK_TemplateId: {
5269     TemplateName TName = Name.TemplateId->Template.get();
5270     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5271     return Context.getNameForTemplate(TName, TNameLoc);
5272   }
5273 
5274   } // switch (Name.getKind())
5275 
5276   llvm_unreachable("Unknown name kind");
5277 }
5278 
5279 static QualType getCoreType(QualType Ty) {
5280   do {
5281     if (Ty->isPointerType() || Ty->isReferenceType())
5282       Ty = Ty->getPointeeType();
5283     else if (Ty->isArrayType())
5284       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5285     else
5286       return Ty.withoutLocalFastQualifiers();
5287   } while (true);
5288 }
5289 
5290 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5291 /// and Definition have "nearly" matching parameters. This heuristic is
5292 /// used to improve diagnostics in the case where an out-of-line function
5293 /// definition doesn't match any declaration within the class or namespace.
5294 /// Also sets Params to the list of indices to the parameters that differ
5295 /// between the declaration and the definition. If hasSimilarParameters
5296 /// returns true and Params is empty, then all of the parameters match.
5297 static bool hasSimilarParameters(ASTContext &Context,
5298                                      FunctionDecl *Declaration,
5299                                      FunctionDecl *Definition,
5300                                      SmallVectorImpl<unsigned> &Params) {
5301   Params.clear();
5302   if (Declaration->param_size() != Definition->param_size())
5303     return false;
5304   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5305     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5306     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5307 
5308     // The parameter types are identical
5309     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5310       continue;
5311 
5312     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5313     QualType DefParamBaseTy = getCoreType(DefParamTy);
5314     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5315     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5316 
5317     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5318         (DeclTyName && DeclTyName == DefTyName))
5319       Params.push_back(Idx);
5320     else  // The two parameters aren't even close
5321       return false;
5322   }
5323 
5324   return true;
5325 }
5326 
5327 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5328 /// declarator needs to be rebuilt in the current instantiation.
5329 /// Any bits of declarator which appear before the name are valid for
5330 /// consideration here.  That's specifically the type in the decl spec
5331 /// and the base type in any member-pointer chunks.
5332 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5333                                                     DeclarationName Name) {
5334   // The types we specifically need to rebuild are:
5335   //   - typenames, typeofs, and decltypes
5336   //   - types which will become injected class names
5337   // Of course, we also need to rebuild any type referencing such a
5338   // type.  It's safest to just say "dependent", but we call out a
5339   // few cases here.
5340 
5341   DeclSpec &DS = D.getMutableDeclSpec();
5342   switch (DS.getTypeSpecType()) {
5343   case DeclSpec::TST_typename:
5344   case DeclSpec::TST_typeofType:
5345   case DeclSpec::TST_underlyingType:
5346   case DeclSpec::TST_atomic: {
5347     // Grab the type from the parser.
5348     TypeSourceInfo *TSI = nullptr;
5349     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5350     if (T.isNull() || !T->isDependentType()) break;
5351 
5352     // Make sure there's a type source info.  This isn't really much
5353     // of a waste; most dependent types should have type source info
5354     // attached already.
5355     if (!TSI)
5356       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5357 
5358     // Rebuild the type in the current instantiation.
5359     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5360     if (!TSI) return true;
5361 
5362     // Store the new type back in the decl spec.
5363     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5364     DS.UpdateTypeRep(LocType);
5365     break;
5366   }
5367 
5368   case DeclSpec::TST_decltype:
5369   case DeclSpec::TST_typeofExpr: {
5370     Expr *E = DS.getRepAsExpr();
5371     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5372     if (Result.isInvalid()) return true;
5373     DS.UpdateExprRep(Result.get());
5374     break;
5375   }
5376 
5377   default:
5378     // Nothing to do for these decl specs.
5379     break;
5380   }
5381 
5382   // It doesn't matter what order we do this in.
5383   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5384     DeclaratorChunk &Chunk = D.getTypeObject(I);
5385 
5386     // The only type information in the declarator which can come
5387     // before the declaration name is the base type of a member
5388     // pointer.
5389     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5390       continue;
5391 
5392     // Rebuild the scope specifier in-place.
5393     CXXScopeSpec &SS = Chunk.Mem.Scope();
5394     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5395       return true;
5396   }
5397 
5398   return false;
5399 }
5400 
5401 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5402   D.setFunctionDefinitionKind(FDK_Declaration);
5403   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5404 
5405   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5406       Dcl && Dcl->getDeclContext()->isFileContext())
5407     Dcl->setTopLevelDeclInObjCContainer();
5408 
5409   if (getLangOpts().OpenCL)
5410     setCurrentOpenCLExtensionForDecl(Dcl);
5411 
5412   return Dcl;
5413 }
5414 
5415 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5416 ///   If T is the name of a class, then each of the following shall have a
5417 ///   name different from T:
5418 ///     - every static data member of class T;
5419 ///     - every member function of class T
5420 ///     - every member of class T that is itself a type;
5421 /// \returns true if the declaration name violates these rules.
5422 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5423                                    DeclarationNameInfo NameInfo) {
5424   DeclarationName Name = NameInfo.getName();
5425 
5426   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5427   while (Record && Record->isAnonymousStructOrUnion())
5428     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5429   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5430     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5431     return true;
5432   }
5433 
5434   return false;
5435 }
5436 
5437 /// Diagnose a declaration whose declarator-id has the given
5438 /// nested-name-specifier.
5439 ///
5440 /// \param SS The nested-name-specifier of the declarator-id.
5441 ///
5442 /// \param DC The declaration context to which the nested-name-specifier
5443 /// resolves.
5444 ///
5445 /// \param Name The name of the entity being declared.
5446 ///
5447 /// \param Loc The location of the name of the entity being declared.
5448 ///
5449 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5450 /// we're declaring an explicit / partial specialization / instantiation.
5451 ///
5452 /// \returns true if we cannot safely recover from this error, false otherwise.
5453 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5454                                         DeclarationName Name,
5455                                         SourceLocation Loc, bool IsTemplateId) {
5456   DeclContext *Cur = CurContext;
5457   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5458     Cur = Cur->getParent();
5459 
5460   // If the user provided a superfluous scope specifier that refers back to the
5461   // class in which the entity is already declared, diagnose and ignore it.
5462   //
5463   // class X {
5464   //   void X::f();
5465   // };
5466   //
5467   // Note, it was once ill-formed to give redundant qualification in all
5468   // contexts, but that rule was removed by DR482.
5469   if (Cur->Equals(DC)) {
5470     if (Cur->isRecord()) {
5471       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5472                                       : diag::err_member_extra_qualification)
5473         << Name << FixItHint::CreateRemoval(SS.getRange());
5474       SS.clear();
5475     } else {
5476       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5477     }
5478     return false;
5479   }
5480 
5481   // Check whether the qualifying scope encloses the scope of the original
5482   // declaration. For a template-id, we perform the checks in
5483   // CheckTemplateSpecializationScope.
5484   if (!Cur->Encloses(DC) && !IsTemplateId) {
5485     if (Cur->isRecord())
5486       Diag(Loc, diag::err_member_qualification)
5487         << Name << SS.getRange();
5488     else if (isa<TranslationUnitDecl>(DC))
5489       Diag(Loc, diag::err_invalid_declarator_global_scope)
5490         << Name << SS.getRange();
5491     else if (isa<FunctionDecl>(Cur))
5492       Diag(Loc, diag::err_invalid_declarator_in_function)
5493         << Name << SS.getRange();
5494     else if (isa<BlockDecl>(Cur))
5495       Diag(Loc, diag::err_invalid_declarator_in_block)
5496         << Name << SS.getRange();
5497     else
5498       Diag(Loc, diag::err_invalid_declarator_scope)
5499       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5500 
5501     return true;
5502   }
5503 
5504   if (Cur->isRecord()) {
5505     // Cannot qualify members within a class.
5506     Diag(Loc, diag::err_member_qualification)
5507       << Name << SS.getRange();
5508     SS.clear();
5509 
5510     // C++ constructors and destructors with incorrect scopes can break
5511     // our AST invariants by having the wrong underlying types. If
5512     // that's the case, then drop this declaration entirely.
5513     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5514          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5515         !Context.hasSameType(Name.getCXXNameType(),
5516                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5517       return true;
5518 
5519     return false;
5520   }
5521 
5522   // C++11 [dcl.meaning]p1:
5523   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5524   //   not begin with a decltype-specifer"
5525   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5526   while (SpecLoc.getPrefix())
5527     SpecLoc = SpecLoc.getPrefix();
5528   if (dyn_cast_or_null<DecltypeType>(
5529         SpecLoc.getNestedNameSpecifier()->getAsType()))
5530     Diag(Loc, diag::err_decltype_in_declarator)
5531       << SpecLoc.getTypeLoc().getSourceRange();
5532 
5533   return false;
5534 }
5535 
5536 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5537                                   MultiTemplateParamsArg TemplateParamLists) {
5538   // TODO: consider using NameInfo for diagnostic.
5539   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5540   DeclarationName Name = NameInfo.getName();
5541 
5542   // All of these full declarators require an identifier.  If it doesn't have
5543   // one, the ParsedFreeStandingDeclSpec action should be used.
5544   if (D.isDecompositionDeclarator()) {
5545     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5546   } else if (!Name) {
5547     if (!D.isInvalidType())  // Reject this if we think it is valid.
5548       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5549           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5550     return nullptr;
5551   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5552     return nullptr;
5553 
5554   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5555   // we find one that is.
5556   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5557          (S->getFlags() & Scope::TemplateParamScope) != 0)
5558     S = S->getParent();
5559 
5560   DeclContext *DC = CurContext;
5561   if (D.getCXXScopeSpec().isInvalid())
5562     D.setInvalidType();
5563   else if (D.getCXXScopeSpec().isSet()) {
5564     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5565                                         UPPC_DeclarationQualifier))
5566       return nullptr;
5567 
5568     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5569     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5570     if (!DC || isa<EnumDecl>(DC)) {
5571       // If we could not compute the declaration context, it's because the
5572       // declaration context is dependent but does not refer to a class,
5573       // class template, or class template partial specialization. Complain
5574       // and return early, to avoid the coming semantic disaster.
5575       Diag(D.getIdentifierLoc(),
5576            diag::err_template_qualified_declarator_no_match)
5577         << D.getCXXScopeSpec().getScopeRep()
5578         << D.getCXXScopeSpec().getRange();
5579       return nullptr;
5580     }
5581     bool IsDependentContext = DC->isDependentContext();
5582 
5583     if (!IsDependentContext &&
5584         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5585       return nullptr;
5586 
5587     // If a class is incomplete, do not parse entities inside it.
5588     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5589       Diag(D.getIdentifierLoc(),
5590            diag::err_member_def_undefined_record)
5591         << Name << DC << D.getCXXScopeSpec().getRange();
5592       return nullptr;
5593     }
5594     if (!D.getDeclSpec().isFriendSpecified()) {
5595       if (diagnoseQualifiedDeclaration(
5596               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5597               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5598         if (DC->isRecord())
5599           return nullptr;
5600 
5601         D.setInvalidType();
5602       }
5603     }
5604 
5605     // Check whether we need to rebuild the type of the given
5606     // declaration in the current instantiation.
5607     if (EnteringContext && IsDependentContext &&
5608         TemplateParamLists.size() != 0) {
5609       ContextRAII SavedContext(*this, DC);
5610       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5611         D.setInvalidType();
5612     }
5613   }
5614 
5615   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5616   QualType R = TInfo->getType();
5617 
5618   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5619                                       UPPC_DeclarationType))
5620     D.setInvalidType();
5621 
5622   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5623                         forRedeclarationInCurContext());
5624 
5625   // See if this is a redefinition of a variable in the same scope.
5626   if (!D.getCXXScopeSpec().isSet()) {
5627     bool IsLinkageLookup = false;
5628     bool CreateBuiltins = false;
5629 
5630     // If the declaration we're planning to build will be a function
5631     // or object with linkage, then look for another declaration with
5632     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5633     //
5634     // If the declaration we're planning to build will be declared with
5635     // external linkage in the translation unit, create any builtin with
5636     // the same name.
5637     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5638       /* Do nothing*/;
5639     else if (CurContext->isFunctionOrMethod() &&
5640              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5641               R->isFunctionType())) {
5642       IsLinkageLookup = true;
5643       CreateBuiltins =
5644           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5645     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5646                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5647       CreateBuiltins = true;
5648 
5649     if (IsLinkageLookup) {
5650       Previous.clear(LookupRedeclarationWithLinkage);
5651       Previous.setRedeclarationKind(ForExternalRedeclaration);
5652     }
5653 
5654     LookupName(Previous, S, CreateBuiltins);
5655   } else { // Something like "int foo::x;"
5656     LookupQualifiedName(Previous, DC);
5657 
5658     // C++ [dcl.meaning]p1:
5659     //   When the declarator-id is qualified, the declaration shall refer to a
5660     //  previously declared member of the class or namespace to which the
5661     //  qualifier refers (or, in the case of a namespace, of an element of the
5662     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5663     //  thereof; [...]
5664     //
5665     // Note that we already checked the context above, and that we do not have
5666     // enough information to make sure that Previous contains the declaration
5667     // we want to match. For example, given:
5668     //
5669     //   class X {
5670     //     void f();
5671     //     void f(float);
5672     //   };
5673     //
5674     //   void X::f(int) { } // ill-formed
5675     //
5676     // In this case, Previous will point to the overload set
5677     // containing the two f's declared in X, but neither of them
5678     // matches.
5679 
5680     // C++ [dcl.meaning]p1:
5681     //   [...] the member shall not merely have been introduced by a
5682     //   using-declaration in the scope of the class or namespace nominated by
5683     //   the nested-name-specifier of the declarator-id.
5684     RemoveUsingDecls(Previous);
5685   }
5686 
5687   if (Previous.isSingleResult() &&
5688       Previous.getFoundDecl()->isTemplateParameter()) {
5689     // Maybe we will complain about the shadowed template parameter.
5690     if (!D.isInvalidType())
5691       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5692                                       Previous.getFoundDecl());
5693 
5694     // Just pretend that we didn't see the previous declaration.
5695     Previous.clear();
5696   }
5697 
5698   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5699     // Forget that the previous declaration is the injected-class-name.
5700     Previous.clear();
5701 
5702   // In C++, the previous declaration we find might be a tag type
5703   // (class or enum). In this case, the new declaration will hide the
5704   // tag type. Note that this applies to functions, function templates, and
5705   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5706   if (Previous.isSingleTagDecl() &&
5707       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5708       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5709     Previous.clear();
5710 
5711   // Check that there are no default arguments other than in the parameters
5712   // of a function declaration (C++ only).
5713   if (getLangOpts().CPlusPlus)
5714     CheckExtraCXXDefaultArguments(D);
5715 
5716   NamedDecl *New;
5717 
5718   bool AddToScope = true;
5719   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5720     if (TemplateParamLists.size()) {
5721       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5722       return nullptr;
5723     }
5724 
5725     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5726   } else if (R->isFunctionType()) {
5727     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5728                                   TemplateParamLists,
5729                                   AddToScope);
5730   } else {
5731     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5732                                   AddToScope);
5733   }
5734 
5735   if (!New)
5736     return nullptr;
5737 
5738   // If this has an identifier and is not a function template specialization,
5739   // add it to the scope stack.
5740   if (New->getDeclName() && AddToScope)
5741     PushOnScopeChains(New, S);
5742 
5743   if (isInOpenMPDeclareTargetContext())
5744     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5745 
5746   return New;
5747 }
5748 
5749 /// Helper method to turn variable array types into constant array
5750 /// types in certain situations which would otherwise be errors (for
5751 /// GCC compatibility).
5752 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5753                                                     ASTContext &Context,
5754                                                     bool &SizeIsNegative,
5755                                                     llvm::APSInt &Oversized) {
5756   // This method tries to turn a variable array into a constant
5757   // array even when the size isn't an ICE.  This is necessary
5758   // for compatibility with code that depends on gcc's buggy
5759   // constant expression folding, like struct {char x[(int)(char*)2];}
5760   SizeIsNegative = false;
5761   Oversized = 0;
5762 
5763   if (T->isDependentType())
5764     return QualType();
5765 
5766   QualifierCollector Qs;
5767   const Type *Ty = Qs.strip(T);
5768 
5769   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5770     QualType Pointee = PTy->getPointeeType();
5771     QualType FixedType =
5772         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5773                                             Oversized);
5774     if (FixedType.isNull()) return FixedType;
5775     FixedType = Context.getPointerType(FixedType);
5776     return Qs.apply(Context, FixedType);
5777   }
5778   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5779     QualType Inner = PTy->getInnerType();
5780     QualType FixedType =
5781         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5782                                             Oversized);
5783     if (FixedType.isNull()) return FixedType;
5784     FixedType = Context.getParenType(FixedType);
5785     return Qs.apply(Context, FixedType);
5786   }
5787 
5788   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5789   if (!VLATy)
5790     return QualType();
5791   // FIXME: We should probably handle this case
5792   if (VLATy->getElementType()->isVariablyModifiedType())
5793     return QualType();
5794 
5795   Expr::EvalResult Result;
5796   if (!VLATy->getSizeExpr() ||
5797       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5798     return QualType();
5799 
5800   llvm::APSInt Res = Result.Val.getInt();
5801 
5802   // Check whether the array size is negative.
5803   if (Res.isSigned() && Res.isNegative()) {
5804     SizeIsNegative = true;
5805     return QualType();
5806   }
5807 
5808   // Check whether the array is too large to be addressed.
5809   unsigned ActiveSizeBits
5810     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5811                                               Res);
5812   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5813     Oversized = Res;
5814     return QualType();
5815   }
5816 
5817   return Context.getConstantArrayType(
5818       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5819 }
5820 
5821 static void
5822 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5823   SrcTL = SrcTL.getUnqualifiedLoc();
5824   DstTL = DstTL.getUnqualifiedLoc();
5825   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5826     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5827     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5828                                       DstPTL.getPointeeLoc());
5829     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5830     return;
5831   }
5832   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5833     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5834     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5835                                       DstPTL.getInnerLoc());
5836     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5837     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5838     return;
5839   }
5840   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5841   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5842   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5843   TypeLoc DstElemTL = DstATL.getElementLoc();
5844   DstElemTL.initializeFullCopy(SrcElemTL);
5845   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5846   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5847   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5848 }
5849 
5850 /// Helper method to turn variable array types into constant array
5851 /// types in certain situations which would otherwise be errors (for
5852 /// GCC compatibility).
5853 static TypeSourceInfo*
5854 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5855                                               ASTContext &Context,
5856                                               bool &SizeIsNegative,
5857                                               llvm::APSInt &Oversized) {
5858   QualType FixedTy
5859     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5860                                           SizeIsNegative, Oversized);
5861   if (FixedTy.isNull())
5862     return nullptr;
5863   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5864   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5865                                     FixedTInfo->getTypeLoc());
5866   return FixedTInfo;
5867 }
5868 
5869 /// Register the given locally-scoped extern "C" declaration so
5870 /// that it can be found later for redeclarations. We include any extern "C"
5871 /// declaration that is not visible in the translation unit here, not just
5872 /// function-scope declarations.
5873 void
5874 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5875   if (!getLangOpts().CPlusPlus &&
5876       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5877     // Don't need to track declarations in the TU in C.
5878     return;
5879 
5880   // Note that we have a locally-scoped external with this name.
5881   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5882 }
5883 
5884 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5885   // FIXME: We can have multiple results via __attribute__((overloadable)).
5886   auto Result = Context.getExternCContextDecl()->lookup(Name);
5887   return Result.empty() ? nullptr : *Result.begin();
5888 }
5889 
5890 /// Diagnose function specifiers on a declaration of an identifier that
5891 /// does not identify a function.
5892 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5893   // FIXME: We should probably indicate the identifier in question to avoid
5894   // confusion for constructs like "virtual int a(), b;"
5895   if (DS.isVirtualSpecified())
5896     Diag(DS.getVirtualSpecLoc(),
5897          diag::err_virtual_non_function);
5898 
5899   if (DS.hasExplicitSpecifier())
5900     Diag(DS.getExplicitSpecLoc(),
5901          diag::err_explicit_non_function);
5902 
5903   if (DS.isNoreturnSpecified())
5904     Diag(DS.getNoreturnSpecLoc(),
5905          diag::err_noreturn_non_function);
5906 }
5907 
5908 NamedDecl*
5909 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5910                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5911   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5912   if (D.getCXXScopeSpec().isSet()) {
5913     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5914       << D.getCXXScopeSpec().getRange();
5915     D.setInvalidType();
5916     // Pretend we didn't see the scope specifier.
5917     DC = CurContext;
5918     Previous.clear();
5919   }
5920 
5921   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5922 
5923   if (D.getDeclSpec().isInlineSpecified())
5924     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5925         << getLangOpts().CPlusPlus17;
5926   if (D.getDeclSpec().hasConstexprSpecifier())
5927     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5928         << 1 << D.getDeclSpec().getConstexprSpecifier();
5929 
5930   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5931     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5932       Diag(D.getName().StartLocation,
5933            diag::err_deduction_guide_invalid_specifier)
5934           << "typedef";
5935     else
5936       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5937           << D.getName().getSourceRange();
5938     return nullptr;
5939   }
5940 
5941   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5942   if (!NewTD) return nullptr;
5943 
5944   // Handle attributes prior to checking for duplicates in MergeVarDecl
5945   ProcessDeclAttributes(S, NewTD, D);
5946 
5947   CheckTypedefForVariablyModifiedType(S, NewTD);
5948 
5949   bool Redeclaration = D.isRedeclaration();
5950   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5951   D.setRedeclaration(Redeclaration);
5952   return ND;
5953 }
5954 
5955 void
5956 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5957   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5958   // then it shall have block scope.
5959   // Note that variably modified types must be fixed before merging the decl so
5960   // that redeclarations will match.
5961   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5962   QualType T = TInfo->getType();
5963   if (T->isVariablyModifiedType()) {
5964     setFunctionHasBranchProtectedScope();
5965 
5966     if (S->getFnParent() == nullptr) {
5967       bool SizeIsNegative;
5968       llvm::APSInt Oversized;
5969       TypeSourceInfo *FixedTInfo =
5970         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5971                                                       SizeIsNegative,
5972                                                       Oversized);
5973       if (FixedTInfo) {
5974         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5975         NewTD->setTypeSourceInfo(FixedTInfo);
5976       } else {
5977         if (SizeIsNegative)
5978           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5979         else if (T->isVariableArrayType())
5980           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5981         else if (Oversized.getBoolValue())
5982           Diag(NewTD->getLocation(), diag::err_array_too_large)
5983             << Oversized.toString(10);
5984         else
5985           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5986         NewTD->setInvalidDecl();
5987       }
5988     }
5989   }
5990 }
5991 
5992 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5993 /// declares a typedef-name, either using the 'typedef' type specifier or via
5994 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5995 NamedDecl*
5996 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5997                            LookupResult &Previous, bool &Redeclaration) {
5998 
5999   // Find the shadowed declaration before filtering for scope.
6000   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6001 
6002   // Merge the decl with the existing one if appropriate. If the decl is
6003   // in an outer scope, it isn't the same thing.
6004   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6005                        /*AllowInlineNamespace*/false);
6006   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6007   if (!Previous.empty()) {
6008     Redeclaration = true;
6009     MergeTypedefNameDecl(S, NewTD, Previous);
6010   } else {
6011     inferGslPointerAttribute(NewTD);
6012   }
6013 
6014   if (ShadowedDecl && !Redeclaration)
6015     CheckShadow(NewTD, ShadowedDecl, Previous);
6016 
6017   // If this is the C FILE type, notify the AST context.
6018   if (IdentifierInfo *II = NewTD->getIdentifier())
6019     if (!NewTD->isInvalidDecl() &&
6020         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6021       if (II->isStr("FILE"))
6022         Context.setFILEDecl(NewTD);
6023       else if (II->isStr("jmp_buf"))
6024         Context.setjmp_bufDecl(NewTD);
6025       else if (II->isStr("sigjmp_buf"))
6026         Context.setsigjmp_bufDecl(NewTD);
6027       else if (II->isStr("ucontext_t"))
6028         Context.setucontext_tDecl(NewTD);
6029     }
6030 
6031   return NewTD;
6032 }
6033 
6034 /// Determines whether the given declaration is an out-of-scope
6035 /// previous declaration.
6036 ///
6037 /// This routine should be invoked when name lookup has found a
6038 /// previous declaration (PrevDecl) that is not in the scope where a
6039 /// new declaration by the same name is being introduced. If the new
6040 /// declaration occurs in a local scope, previous declarations with
6041 /// linkage may still be considered previous declarations (C99
6042 /// 6.2.2p4-5, C++ [basic.link]p6).
6043 ///
6044 /// \param PrevDecl the previous declaration found by name
6045 /// lookup
6046 ///
6047 /// \param DC the context in which the new declaration is being
6048 /// declared.
6049 ///
6050 /// \returns true if PrevDecl is an out-of-scope previous declaration
6051 /// for a new delcaration with the same name.
6052 static bool
6053 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6054                                 ASTContext &Context) {
6055   if (!PrevDecl)
6056     return false;
6057 
6058   if (!PrevDecl->hasLinkage())
6059     return false;
6060 
6061   if (Context.getLangOpts().CPlusPlus) {
6062     // C++ [basic.link]p6:
6063     //   If there is a visible declaration of an entity with linkage
6064     //   having the same name and type, ignoring entities declared
6065     //   outside the innermost enclosing namespace scope, the block
6066     //   scope declaration declares that same entity and receives the
6067     //   linkage of the previous declaration.
6068     DeclContext *OuterContext = DC->getRedeclContext();
6069     if (!OuterContext->isFunctionOrMethod())
6070       // This rule only applies to block-scope declarations.
6071       return false;
6072 
6073     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6074     if (PrevOuterContext->isRecord())
6075       // We found a member function: ignore it.
6076       return false;
6077 
6078     // Find the innermost enclosing namespace for the new and
6079     // previous declarations.
6080     OuterContext = OuterContext->getEnclosingNamespaceContext();
6081     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6082 
6083     // The previous declaration is in a different namespace, so it
6084     // isn't the same function.
6085     if (!OuterContext->Equals(PrevOuterContext))
6086       return false;
6087   }
6088 
6089   return true;
6090 }
6091 
6092 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6093   CXXScopeSpec &SS = D.getCXXScopeSpec();
6094   if (!SS.isSet()) return;
6095   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6096 }
6097 
6098 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6099   QualType type = decl->getType();
6100   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6101   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6102     // Various kinds of declaration aren't allowed to be __autoreleasing.
6103     unsigned kind = -1U;
6104     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6105       if (var->hasAttr<BlocksAttr>())
6106         kind = 0; // __block
6107       else if (!var->hasLocalStorage())
6108         kind = 1; // global
6109     } else if (isa<ObjCIvarDecl>(decl)) {
6110       kind = 3; // ivar
6111     } else if (isa<FieldDecl>(decl)) {
6112       kind = 2; // field
6113     }
6114 
6115     if (kind != -1U) {
6116       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6117         << kind;
6118     }
6119   } else if (lifetime == Qualifiers::OCL_None) {
6120     // Try to infer lifetime.
6121     if (!type->isObjCLifetimeType())
6122       return false;
6123 
6124     lifetime = type->getObjCARCImplicitLifetime();
6125     type = Context.getLifetimeQualifiedType(type, lifetime);
6126     decl->setType(type);
6127   }
6128 
6129   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6130     // Thread-local variables cannot have lifetime.
6131     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6132         var->getTLSKind()) {
6133       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6134         << var->getType();
6135       return true;
6136     }
6137   }
6138 
6139   return false;
6140 }
6141 
6142 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6143   // Ensure that an auto decl is deduced otherwise the checks below might cache
6144   // the wrong linkage.
6145   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6146 
6147   // 'weak' only applies to declarations with external linkage.
6148   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6149     if (!ND.isExternallyVisible()) {
6150       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6151       ND.dropAttr<WeakAttr>();
6152     }
6153   }
6154   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6155     if (ND.isExternallyVisible()) {
6156       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6157       ND.dropAttr<WeakRefAttr>();
6158       ND.dropAttr<AliasAttr>();
6159     }
6160   }
6161 
6162   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6163     if (VD->hasInit()) {
6164       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6165         assert(VD->isThisDeclarationADefinition() &&
6166                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6167         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6168         VD->dropAttr<AliasAttr>();
6169       }
6170     }
6171   }
6172 
6173   // 'selectany' only applies to externally visible variable declarations.
6174   // It does not apply to functions.
6175   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6176     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6177       S.Diag(Attr->getLocation(),
6178              diag::err_attribute_selectany_non_extern_data);
6179       ND.dropAttr<SelectAnyAttr>();
6180     }
6181   }
6182 
6183   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6184     auto *VD = dyn_cast<VarDecl>(&ND);
6185     bool IsAnonymousNS = false;
6186     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6187     if (VD) {
6188       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6189       while (NS && !IsAnonymousNS) {
6190         IsAnonymousNS = NS->isAnonymousNamespace();
6191         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6192       }
6193     }
6194     // dll attributes require external linkage. Static locals may have external
6195     // linkage but still cannot be explicitly imported or exported.
6196     // In Microsoft mode, a variable defined in anonymous namespace must have
6197     // external linkage in order to be exported.
6198     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6199     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6200         (!AnonNSInMicrosoftMode &&
6201          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6202       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6203         << &ND << Attr;
6204       ND.setInvalidDecl();
6205     }
6206   }
6207 
6208   // Virtual functions cannot be marked as 'notail'.
6209   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6210     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6211       if (MD->isVirtual()) {
6212         S.Diag(ND.getLocation(),
6213                diag::err_invalid_attribute_on_virtual_function)
6214             << Attr;
6215         ND.dropAttr<NotTailCalledAttr>();
6216       }
6217 
6218   // Check the attributes on the function type, if any.
6219   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6220     // Don't declare this variable in the second operand of the for-statement;
6221     // GCC miscompiles that by ending its lifetime before evaluating the
6222     // third operand. See gcc.gnu.org/PR86769.
6223     AttributedTypeLoc ATL;
6224     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6225          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6226          TL = ATL.getModifiedLoc()) {
6227       // The [[lifetimebound]] attribute can be applied to the implicit object
6228       // parameter of a non-static member function (other than a ctor or dtor)
6229       // by applying it to the function type.
6230       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6231         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6232         if (!MD || MD->isStatic()) {
6233           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6234               << !MD << A->getRange();
6235         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6236           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6237               << isa<CXXDestructorDecl>(MD) << A->getRange();
6238         }
6239       }
6240     }
6241   }
6242 }
6243 
6244 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6245                                            NamedDecl *NewDecl,
6246                                            bool IsSpecialization,
6247                                            bool IsDefinition) {
6248   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6249     return;
6250 
6251   bool IsTemplate = false;
6252   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6253     OldDecl = OldTD->getTemplatedDecl();
6254     IsTemplate = true;
6255     if (!IsSpecialization)
6256       IsDefinition = false;
6257   }
6258   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6259     NewDecl = NewTD->getTemplatedDecl();
6260     IsTemplate = true;
6261   }
6262 
6263   if (!OldDecl || !NewDecl)
6264     return;
6265 
6266   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6267   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6268   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6269   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6270 
6271   // dllimport and dllexport are inheritable attributes so we have to exclude
6272   // inherited attribute instances.
6273   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6274                     (NewExportAttr && !NewExportAttr->isInherited());
6275 
6276   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6277   // the only exception being explicit specializations.
6278   // Implicitly generated declarations are also excluded for now because there
6279   // is no other way to switch these to use dllimport or dllexport.
6280   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6281 
6282   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6283     // Allow with a warning for free functions and global variables.
6284     bool JustWarn = false;
6285     if (!OldDecl->isCXXClassMember()) {
6286       auto *VD = dyn_cast<VarDecl>(OldDecl);
6287       if (VD && !VD->getDescribedVarTemplate())
6288         JustWarn = true;
6289       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6290       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6291         JustWarn = true;
6292     }
6293 
6294     // We cannot change a declaration that's been used because IR has already
6295     // been emitted. Dllimported functions will still work though (modulo
6296     // address equality) as they can use the thunk.
6297     if (OldDecl->isUsed())
6298       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6299         JustWarn = false;
6300 
6301     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6302                                : diag::err_attribute_dll_redeclaration;
6303     S.Diag(NewDecl->getLocation(), DiagID)
6304         << NewDecl
6305         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6306     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6307     if (!JustWarn) {
6308       NewDecl->setInvalidDecl();
6309       return;
6310     }
6311   }
6312 
6313   // A redeclaration is not allowed to drop a dllimport attribute, the only
6314   // exceptions being inline function definitions (except for function
6315   // templates), local extern declarations, qualified friend declarations or
6316   // special MSVC extension: in the last case, the declaration is treated as if
6317   // it were marked dllexport.
6318   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6319   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6320   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6321     // Ignore static data because out-of-line definitions are diagnosed
6322     // separately.
6323     IsStaticDataMember = VD->isStaticDataMember();
6324     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6325                    VarDecl::DeclarationOnly;
6326   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6327     IsInline = FD->isInlined();
6328     IsQualifiedFriend = FD->getQualifier() &&
6329                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6330   }
6331 
6332   if (OldImportAttr && !HasNewAttr &&
6333       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6334       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6335     if (IsMicrosoft && IsDefinition) {
6336       S.Diag(NewDecl->getLocation(),
6337              diag::warn_redeclaration_without_import_attribute)
6338           << NewDecl;
6339       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6340       NewDecl->dropAttr<DLLImportAttr>();
6341       NewDecl->addAttr(
6342           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6343     } else {
6344       S.Diag(NewDecl->getLocation(),
6345              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6346           << NewDecl << OldImportAttr;
6347       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6348       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6349       OldDecl->dropAttr<DLLImportAttr>();
6350       NewDecl->dropAttr<DLLImportAttr>();
6351     }
6352   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6353     // In MinGW, seeing a function declared inline drops the dllimport
6354     // attribute.
6355     OldDecl->dropAttr<DLLImportAttr>();
6356     NewDecl->dropAttr<DLLImportAttr>();
6357     S.Diag(NewDecl->getLocation(),
6358            diag::warn_dllimport_dropped_from_inline_function)
6359         << NewDecl << OldImportAttr;
6360   }
6361 
6362   // A specialization of a class template member function is processed here
6363   // since it's a redeclaration. If the parent class is dllexport, the
6364   // specialization inherits that attribute. This doesn't happen automatically
6365   // since the parent class isn't instantiated until later.
6366   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6367     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6368         !NewImportAttr && !NewExportAttr) {
6369       if (const DLLExportAttr *ParentExportAttr =
6370               MD->getParent()->getAttr<DLLExportAttr>()) {
6371         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6372         NewAttr->setInherited(true);
6373         NewDecl->addAttr(NewAttr);
6374       }
6375     }
6376   }
6377 }
6378 
6379 /// Given that we are within the definition of the given function,
6380 /// will that definition behave like C99's 'inline', where the
6381 /// definition is discarded except for optimization purposes?
6382 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6383   // Try to avoid calling GetGVALinkageForFunction.
6384 
6385   // All cases of this require the 'inline' keyword.
6386   if (!FD->isInlined()) return false;
6387 
6388   // This is only possible in C++ with the gnu_inline attribute.
6389   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6390     return false;
6391 
6392   // Okay, go ahead and call the relatively-more-expensive function.
6393   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6394 }
6395 
6396 /// Determine whether a variable is extern "C" prior to attaching
6397 /// an initializer. We can't just call isExternC() here, because that
6398 /// will also compute and cache whether the declaration is externally
6399 /// visible, which might change when we attach the initializer.
6400 ///
6401 /// This can only be used if the declaration is known to not be a
6402 /// redeclaration of an internal linkage declaration.
6403 ///
6404 /// For instance:
6405 ///
6406 ///   auto x = []{};
6407 ///
6408 /// Attaching the initializer here makes this declaration not externally
6409 /// visible, because its type has internal linkage.
6410 ///
6411 /// FIXME: This is a hack.
6412 template<typename T>
6413 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6414   if (S.getLangOpts().CPlusPlus) {
6415     // In C++, the overloadable attribute negates the effects of extern "C".
6416     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6417       return false;
6418 
6419     // So do CUDA's host/device attributes.
6420     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6421                                  D->template hasAttr<CUDAHostAttr>()))
6422       return false;
6423   }
6424   return D->isExternC();
6425 }
6426 
6427 static bool shouldConsiderLinkage(const VarDecl *VD) {
6428   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6429   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6430       isa<OMPDeclareMapperDecl>(DC))
6431     return VD->hasExternalStorage();
6432   if (DC->isFileContext())
6433     return true;
6434   if (DC->isRecord())
6435     return false;
6436   llvm_unreachable("Unexpected context");
6437 }
6438 
6439 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6440   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6441   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6442       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6443     return true;
6444   if (DC->isRecord())
6445     return false;
6446   llvm_unreachable("Unexpected context");
6447 }
6448 
6449 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6450                           ParsedAttr::Kind Kind) {
6451   // Check decl attributes on the DeclSpec.
6452   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6453     return true;
6454 
6455   // Walk the declarator structure, checking decl attributes that were in a type
6456   // position to the decl itself.
6457   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6458     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6459       return true;
6460   }
6461 
6462   // Finally, check attributes on the decl itself.
6463   return PD.getAttributes().hasAttribute(Kind);
6464 }
6465 
6466 /// Adjust the \c DeclContext for a function or variable that might be a
6467 /// function-local external declaration.
6468 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6469   if (!DC->isFunctionOrMethod())
6470     return false;
6471 
6472   // If this is a local extern function or variable declared within a function
6473   // template, don't add it into the enclosing namespace scope until it is
6474   // instantiated; it might have a dependent type right now.
6475   if (DC->isDependentContext())
6476     return true;
6477 
6478   // C++11 [basic.link]p7:
6479   //   When a block scope declaration of an entity with linkage is not found to
6480   //   refer to some other declaration, then that entity is a member of the
6481   //   innermost enclosing namespace.
6482   //
6483   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6484   // semantically-enclosing namespace, not a lexically-enclosing one.
6485   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6486     DC = DC->getParent();
6487   return true;
6488 }
6489 
6490 /// Returns true if given declaration has external C language linkage.
6491 static bool isDeclExternC(const Decl *D) {
6492   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6493     return FD->isExternC();
6494   if (const auto *VD = dyn_cast<VarDecl>(D))
6495     return VD->isExternC();
6496 
6497   llvm_unreachable("Unknown type of decl!");
6498 }
6499 
6500 NamedDecl *Sema::ActOnVariableDeclarator(
6501     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6502     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6503     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6504   QualType R = TInfo->getType();
6505   DeclarationName Name = GetNameForDeclarator(D).getName();
6506 
6507   IdentifierInfo *II = Name.getAsIdentifierInfo();
6508 
6509   if (D.isDecompositionDeclarator()) {
6510     // Take the name of the first declarator as our name for diagnostic
6511     // purposes.
6512     auto &Decomp = D.getDecompositionDeclarator();
6513     if (!Decomp.bindings().empty()) {
6514       II = Decomp.bindings()[0].Name;
6515       Name = II;
6516     }
6517   } else if (!II) {
6518     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6519     return nullptr;
6520   }
6521 
6522   if (getLangOpts().OpenCL) {
6523     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6524     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6525     // argument.
6526     if (R->isImageType() || R->isPipeType()) {
6527       Diag(D.getIdentifierLoc(),
6528            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6529           << R;
6530       D.setInvalidType();
6531       return nullptr;
6532     }
6533 
6534     // OpenCL v1.2 s6.9.r:
6535     // The event type cannot be used to declare a program scope variable.
6536     // OpenCL v2.0 s6.9.q:
6537     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6538     if (NULL == S->getParent()) {
6539       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6540         Diag(D.getIdentifierLoc(),
6541              diag::err_invalid_type_for_program_scope_var) << R;
6542         D.setInvalidType();
6543         return nullptr;
6544       }
6545     }
6546 
6547     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6548     QualType NR = R;
6549     while (NR->isPointerType()) {
6550       if (NR->isFunctionPointerType()) {
6551         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6552         D.setInvalidType();
6553         break;
6554       }
6555       NR = NR->getPointeeType();
6556     }
6557 
6558     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6559       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6560       // half array type (unless the cl_khr_fp16 extension is enabled).
6561       if (Context.getBaseElementType(R)->isHalfType()) {
6562         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6563         D.setInvalidType();
6564       }
6565     }
6566 
6567     if (R->isSamplerT()) {
6568       // OpenCL v1.2 s6.9.b p4:
6569       // The sampler type cannot be used with the __local and __global address
6570       // space qualifiers.
6571       if (R.getAddressSpace() == LangAS::opencl_local ||
6572           R.getAddressSpace() == LangAS::opencl_global) {
6573         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6574       }
6575 
6576       // OpenCL v1.2 s6.12.14.1:
6577       // A global sampler must be declared with either the constant address
6578       // space qualifier or with the const qualifier.
6579       if (DC->isTranslationUnit() &&
6580           !(R.getAddressSpace() == LangAS::opencl_constant ||
6581           R.isConstQualified())) {
6582         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6583         D.setInvalidType();
6584       }
6585     }
6586 
6587     // OpenCL v1.2 s6.9.r:
6588     // The event type cannot be used with the __local, __constant and __global
6589     // address space qualifiers.
6590     if (R->isEventT()) {
6591       if (R.getAddressSpace() != LangAS::opencl_private) {
6592         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6593         D.setInvalidType();
6594       }
6595     }
6596 
6597     // C++ for OpenCL does not allow the thread_local storage qualifier.
6598     // OpenCL C does not support thread_local either, and
6599     // also reject all other thread storage class specifiers.
6600     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6601     if (TSC != TSCS_unspecified) {
6602       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6603       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6604            diag::err_opencl_unknown_type_specifier)
6605           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6606           << DeclSpec::getSpecifierName(TSC) << 1;
6607       D.setInvalidType();
6608       return nullptr;
6609     }
6610   }
6611 
6612   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6613   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6614 
6615   // dllimport globals without explicit storage class are treated as extern. We
6616   // have to change the storage class this early to get the right DeclContext.
6617   if (SC == SC_None && !DC->isRecord() &&
6618       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6619       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6620     SC = SC_Extern;
6621 
6622   DeclContext *OriginalDC = DC;
6623   bool IsLocalExternDecl = SC == SC_Extern &&
6624                            adjustContextForLocalExternDecl(DC);
6625 
6626   if (SCSpec == DeclSpec::SCS_mutable) {
6627     // mutable can only appear on non-static class members, so it's always
6628     // an error here
6629     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6630     D.setInvalidType();
6631     SC = SC_None;
6632   }
6633 
6634   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6635       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6636                               D.getDeclSpec().getStorageClassSpecLoc())) {
6637     // In C++11, the 'register' storage class specifier is deprecated.
6638     // Suppress the warning in system macros, it's used in macros in some
6639     // popular C system headers, such as in glibc's htonl() macro.
6640     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6641          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6642                                    : diag::warn_deprecated_register)
6643       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6644   }
6645 
6646   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6647 
6648   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6649     // C99 6.9p2: The storage-class specifiers auto and register shall not
6650     // appear in the declaration specifiers in an external declaration.
6651     // Global Register+Asm is a GNU extension we support.
6652     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6653       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6654       D.setInvalidType();
6655     }
6656   }
6657 
6658   bool IsMemberSpecialization = false;
6659   bool IsVariableTemplateSpecialization = false;
6660   bool IsPartialSpecialization = false;
6661   bool IsVariableTemplate = false;
6662   VarDecl *NewVD = nullptr;
6663   VarTemplateDecl *NewTemplate = nullptr;
6664   TemplateParameterList *TemplateParams = nullptr;
6665   if (!getLangOpts().CPlusPlus) {
6666     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6667                             II, R, TInfo, SC);
6668 
6669     if (R->getContainedDeducedType())
6670       ParsingInitForAutoVars.insert(NewVD);
6671 
6672     if (D.isInvalidType())
6673       NewVD->setInvalidDecl();
6674 
6675     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6676         NewVD->hasLocalStorage())
6677       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6678                             NTCUC_AutoVar, NTCUK_Destruct);
6679   } else {
6680     bool Invalid = false;
6681 
6682     if (DC->isRecord() && !CurContext->isRecord()) {
6683       // This is an out-of-line definition of a static data member.
6684       switch (SC) {
6685       case SC_None:
6686         break;
6687       case SC_Static:
6688         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6689              diag::err_static_out_of_line)
6690           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6691         break;
6692       case SC_Auto:
6693       case SC_Register:
6694       case SC_Extern:
6695         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6696         // to names of variables declared in a block or to function parameters.
6697         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6698         // of class members
6699 
6700         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6701              diag::err_storage_class_for_static_member)
6702           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6703         break;
6704       case SC_PrivateExtern:
6705         llvm_unreachable("C storage class in c++!");
6706       }
6707     }
6708 
6709     if (SC == SC_Static && CurContext->isRecord()) {
6710       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6711         if (RD->isLocalClass())
6712           Diag(D.getIdentifierLoc(),
6713                diag::err_static_data_member_not_allowed_in_local_class)
6714             << Name << RD->getDeclName();
6715 
6716         // C++98 [class.union]p1: If a union contains a static data member,
6717         // the program is ill-formed. C++11 drops this restriction.
6718         if (RD->isUnion())
6719           Diag(D.getIdentifierLoc(),
6720                getLangOpts().CPlusPlus11
6721                  ? diag::warn_cxx98_compat_static_data_member_in_union
6722                  : diag::ext_static_data_member_in_union) << Name;
6723         // We conservatively disallow static data members in anonymous structs.
6724         else if (!RD->getDeclName())
6725           Diag(D.getIdentifierLoc(),
6726                diag::err_static_data_member_not_allowed_in_anon_struct)
6727             << Name << RD->isUnion();
6728       }
6729     }
6730 
6731     // Match up the template parameter lists with the scope specifier, then
6732     // determine whether we have a template or a template specialization.
6733     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6734         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6735         D.getCXXScopeSpec(),
6736         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6737             ? D.getName().TemplateId
6738             : nullptr,
6739         TemplateParamLists,
6740         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6741 
6742     if (TemplateParams) {
6743       if (!TemplateParams->size() &&
6744           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6745         // There is an extraneous 'template<>' for this variable. Complain
6746         // about it, but allow the declaration of the variable.
6747         Diag(TemplateParams->getTemplateLoc(),
6748              diag::err_template_variable_noparams)
6749           << II
6750           << SourceRange(TemplateParams->getTemplateLoc(),
6751                          TemplateParams->getRAngleLoc());
6752         TemplateParams = nullptr;
6753       } else {
6754         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6755           // This is an explicit specialization or a partial specialization.
6756           // FIXME: Check that we can declare a specialization here.
6757           IsVariableTemplateSpecialization = true;
6758           IsPartialSpecialization = TemplateParams->size() > 0;
6759         } else { // if (TemplateParams->size() > 0)
6760           // This is a template declaration.
6761           IsVariableTemplate = true;
6762 
6763           // Check that we can declare a template here.
6764           if (CheckTemplateDeclScope(S, TemplateParams))
6765             return nullptr;
6766 
6767           // Only C++1y supports variable templates (N3651).
6768           Diag(D.getIdentifierLoc(),
6769                getLangOpts().CPlusPlus14
6770                    ? diag::warn_cxx11_compat_variable_template
6771                    : diag::ext_variable_template);
6772         }
6773       }
6774     } else {
6775       assert((Invalid ||
6776               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6777              "should have a 'template<>' for this decl");
6778     }
6779 
6780     if (IsVariableTemplateSpecialization) {
6781       SourceLocation TemplateKWLoc =
6782           TemplateParamLists.size() > 0
6783               ? TemplateParamLists[0]->getTemplateLoc()
6784               : SourceLocation();
6785       DeclResult Res = ActOnVarTemplateSpecialization(
6786           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6787           IsPartialSpecialization);
6788       if (Res.isInvalid())
6789         return nullptr;
6790       NewVD = cast<VarDecl>(Res.get());
6791       AddToScope = false;
6792     } else if (D.isDecompositionDeclarator()) {
6793       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6794                                         D.getIdentifierLoc(), R, TInfo, SC,
6795                                         Bindings);
6796     } else
6797       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6798                               D.getIdentifierLoc(), II, R, TInfo, SC);
6799 
6800     // If this is supposed to be a variable template, create it as such.
6801     if (IsVariableTemplate) {
6802       NewTemplate =
6803           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6804                                   TemplateParams, NewVD);
6805       NewVD->setDescribedVarTemplate(NewTemplate);
6806     }
6807 
6808     // If this decl has an auto type in need of deduction, make a note of the
6809     // Decl so we can diagnose uses of it in its own initializer.
6810     if (R->getContainedDeducedType())
6811       ParsingInitForAutoVars.insert(NewVD);
6812 
6813     if (D.isInvalidType() || Invalid) {
6814       NewVD->setInvalidDecl();
6815       if (NewTemplate)
6816         NewTemplate->setInvalidDecl();
6817     }
6818 
6819     SetNestedNameSpecifier(*this, NewVD, D);
6820 
6821     // If we have any template parameter lists that don't directly belong to
6822     // the variable (matching the scope specifier), store them.
6823     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6824     if (TemplateParamLists.size() > VDTemplateParamLists)
6825       NewVD->setTemplateParameterListsInfo(
6826           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6827   }
6828 
6829   if (D.getDeclSpec().isInlineSpecified()) {
6830     if (!getLangOpts().CPlusPlus) {
6831       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6832           << 0;
6833     } else if (CurContext->isFunctionOrMethod()) {
6834       // 'inline' is not allowed on block scope variable declaration.
6835       Diag(D.getDeclSpec().getInlineSpecLoc(),
6836            diag::err_inline_declaration_block_scope) << Name
6837         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6838     } else {
6839       Diag(D.getDeclSpec().getInlineSpecLoc(),
6840            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6841                                      : diag::ext_inline_variable);
6842       NewVD->setInlineSpecified();
6843     }
6844   }
6845 
6846   // Set the lexical context. If the declarator has a C++ scope specifier, the
6847   // lexical context will be different from the semantic context.
6848   NewVD->setLexicalDeclContext(CurContext);
6849   if (NewTemplate)
6850     NewTemplate->setLexicalDeclContext(CurContext);
6851 
6852   if (IsLocalExternDecl) {
6853     if (D.isDecompositionDeclarator())
6854       for (auto *B : Bindings)
6855         B->setLocalExternDecl();
6856     else
6857       NewVD->setLocalExternDecl();
6858   }
6859 
6860   bool EmitTLSUnsupportedError = false;
6861   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6862     // C++11 [dcl.stc]p4:
6863     //   When thread_local is applied to a variable of block scope the
6864     //   storage-class-specifier static is implied if it does not appear
6865     //   explicitly.
6866     // Core issue: 'static' is not implied if the variable is declared
6867     //   'extern'.
6868     if (NewVD->hasLocalStorage() &&
6869         (SCSpec != DeclSpec::SCS_unspecified ||
6870          TSCS != DeclSpec::TSCS_thread_local ||
6871          !DC->isFunctionOrMethod()))
6872       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6873            diag::err_thread_non_global)
6874         << DeclSpec::getSpecifierName(TSCS);
6875     else if (!Context.getTargetInfo().isTLSSupported()) {
6876       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6877         // Postpone error emission until we've collected attributes required to
6878         // figure out whether it's a host or device variable and whether the
6879         // error should be ignored.
6880         EmitTLSUnsupportedError = true;
6881         // We still need to mark the variable as TLS so it shows up in AST with
6882         // proper storage class for other tools to use even if we're not going
6883         // to emit any code for it.
6884         NewVD->setTSCSpec(TSCS);
6885       } else
6886         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6887              diag::err_thread_unsupported);
6888     } else
6889       NewVD->setTSCSpec(TSCS);
6890   }
6891 
6892   switch (D.getDeclSpec().getConstexprSpecifier()) {
6893   case CSK_unspecified:
6894     break;
6895 
6896   case CSK_consteval:
6897     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6898         diag::err_constexpr_wrong_decl_kind)
6899       << D.getDeclSpec().getConstexprSpecifier();
6900     LLVM_FALLTHROUGH;
6901 
6902   case CSK_constexpr:
6903     NewVD->setConstexpr(true);
6904     // C++1z [dcl.spec.constexpr]p1:
6905     //   A static data member declared with the constexpr specifier is
6906     //   implicitly an inline variable.
6907     if (NewVD->isStaticDataMember() &&
6908         (getLangOpts().CPlusPlus17 ||
6909          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6910       NewVD->setImplicitlyInline();
6911     break;
6912 
6913   case CSK_constinit:
6914     if (!NewVD->hasGlobalStorage())
6915       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6916            diag::err_constinit_local_variable);
6917     else
6918       NewVD->addAttr(ConstInitAttr::Create(
6919           Context, D.getDeclSpec().getConstexprSpecLoc(),
6920           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6921     break;
6922   }
6923 
6924   // C99 6.7.4p3
6925   //   An inline definition of a function with external linkage shall
6926   //   not contain a definition of a modifiable object with static or
6927   //   thread storage duration...
6928   // We only apply this when the function is required to be defined
6929   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6930   // that a local variable with thread storage duration still has to
6931   // be marked 'static'.  Also note that it's possible to get these
6932   // semantics in C++ using __attribute__((gnu_inline)).
6933   if (SC == SC_Static && S->getFnParent() != nullptr &&
6934       !NewVD->getType().isConstQualified()) {
6935     FunctionDecl *CurFD = getCurFunctionDecl();
6936     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6937       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6938            diag::warn_static_local_in_extern_inline);
6939       MaybeSuggestAddingStaticToDecl(CurFD);
6940     }
6941   }
6942 
6943   if (D.getDeclSpec().isModulePrivateSpecified()) {
6944     if (IsVariableTemplateSpecialization)
6945       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6946           << (IsPartialSpecialization ? 1 : 0)
6947           << FixItHint::CreateRemoval(
6948                  D.getDeclSpec().getModulePrivateSpecLoc());
6949     else if (IsMemberSpecialization)
6950       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6951         << 2
6952         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6953     else if (NewVD->hasLocalStorage())
6954       Diag(NewVD->getLocation(), diag::err_module_private_local)
6955         << 0 << NewVD->getDeclName()
6956         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6957         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6958     else {
6959       NewVD->setModulePrivate();
6960       if (NewTemplate)
6961         NewTemplate->setModulePrivate();
6962       for (auto *B : Bindings)
6963         B->setModulePrivate();
6964     }
6965   }
6966 
6967   // Handle attributes prior to checking for duplicates in MergeVarDecl
6968   ProcessDeclAttributes(S, NewVD, D);
6969 
6970   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6971     if (EmitTLSUnsupportedError &&
6972         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6973          (getLangOpts().OpenMPIsDevice &&
6974           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
6975       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6976            diag::err_thread_unsupported);
6977     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6978     // storage [duration]."
6979     if (SC == SC_None && S->getFnParent() != nullptr &&
6980         (NewVD->hasAttr<CUDASharedAttr>() ||
6981          NewVD->hasAttr<CUDAConstantAttr>())) {
6982       NewVD->setStorageClass(SC_Static);
6983     }
6984   }
6985 
6986   // Ensure that dllimport globals without explicit storage class are treated as
6987   // extern. The storage class is set above using parsed attributes. Now we can
6988   // check the VarDecl itself.
6989   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6990          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6991          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6992 
6993   // In auto-retain/release, infer strong retension for variables of
6994   // retainable type.
6995   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6996     NewVD->setInvalidDecl();
6997 
6998   // Handle GNU asm-label extension (encoded as an attribute).
6999   if (Expr *E = (Expr*)D.getAsmLabel()) {
7000     // The parser guarantees this is a string.
7001     StringLiteral *SE = cast<StringLiteral>(E);
7002     StringRef Label = SE->getString();
7003     if (S->getFnParent() != nullptr) {
7004       switch (SC) {
7005       case SC_None:
7006       case SC_Auto:
7007         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7008         break;
7009       case SC_Register:
7010         // Local Named register
7011         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7012             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7013           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7014         break;
7015       case SC_Static:
7016       case SC_Extern:
7017       case SC_PrivateExtern:
7018         break;
7019       }
7020     } else if (SC == SC_Register) {
7021       // Global Named register
7022       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7023         const auto &TI = Context.getTargetInfo();
7024         bool HasSizeMismatch;
7025 
7026         if (!TI.isValidGCCRegisterName(Label))
7027           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7028         else if (!TI.validateGlobalRegisterVariable(Label,
7029                                                     Context.getTypeSize(R),
7030                                                     HasSizeMismatch))
7031           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7032         else if (HasSizeMismatch)
7033           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7034       }
7035 
7036       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7037         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7038         NewVD->setInvalidDecl(true);
7039       }
7040     }
7041 
7042     NewVD->addAttr(::new (Context) AsmLabelAttr(
7043         Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true));
7044   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7045     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7046       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7047     if (I != ExtnameUndeclaredIdentifiers.end()) {
7048       if (isDeclExternC(NewVD)) {
7049         NewVD->addAttr(I->second);
7050         ExtnameUndeclaredIdentifiers.erase(I);
7051       } else
7052         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7053             << /*Variable*/1 << NewVD;
7054     }
7055   }
7056 
7057   // Find the shadowed declaration before filtering for scope.
7058   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7059                                 ? getShadowedDeclaration(NewVD, Previous)
7060                                 : nullptr;
7061 
7062   // Don't consider existing declarations that are in a different
7063   // scope and are out-of-semantic-context declarations (if the new
7064   // declaration has linkage).
7065   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7066                        D.getCXXScopeSpec().isNotEmpty() ||
7067                        IsMemberSpecialization ||
7068                        IsVariableTemplateSpecialization);
7069 
7070   // Check whether the previous declaration is in the same block scope. This
7071   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7072   if (getLangOpts().CPlusPlus &&
7073       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7074     NewVD->setPreviousDeclInSameBlockScope(
7075         Previous.isSingleResult() && !Previous.isShadowed() &&
7076         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7077 
7078   if (!getLangOpts().CPlusPlus) {
7079     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7080   } else {
7081     // If this is an explicit specialization of a static data member, check it.
7082     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7083         CheckMemberSpecialization(NewVD, Previous))
7084       NewVD->setInvalidDecl();
7085 
7086     // Merge the decl with the existing one if appropriate.
7087     if (!Previous.empty()) {
7088       if (Previous.isSingleResult() &&
7089           isa<FieldDecl>(Previous.getFoundDecl()) &&
7090           D.getCXXScopeSpec().isSet()) {
7091         // The user tried to define a non-static data member
7092         // out-of-line (C++ [dcl.meaning]p1).
7093         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7094           << D.getCXXScopeSpec().getRange();
7095         Previous.clear();
7096         NewVD->setInvalidDecl();
7097       }
7098     } else if (D.getCXXScopeSpec().isSet()) {
7099       // No previous declaration in the qualifying scope.
7100       Diag(D.getIdentifierLoc(), diag::err_no_member)
7101         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7102         << D.getCXXScopeSpec().getRange();
7103       NewVD->setInvalidDecl();
7104     }
7105 
7106     if (!IsVariableTemplateSpecialization)
7107       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7108 
7109     if (NewTemplate) {
7110       VarTemplateDecl *PrevVarTemplate =
7111           NewVD->getPreviousDecl()
7112               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7113               : nullptr;
7114 
7115       // Check the template parameter list of this declaration, possibly
7116       // merging in the template parameter list from the previous variable
7117       // template declaration.
7118       if (CheckTemplateParameterList(
7119               TemplateParams,
7120               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7121                               : nullptr,
7122               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7123                DC->isDependentContext())
7124                   ? TPC_ClassTemplateMember
7125                   : TPC_VarTemplate))
7126         NewVD->setInvalidDecl();
7127 
7128       // If we are providing an explicit specialization of a static variable
7129       // template, make a note of that.
7130       if (PrevVarTemplate &&
7131           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7132         PrevVarTemplate->setMemberSpecialization();
7133     }
7134   }
7135 
7136   // Diagnose shadowed variables iff this isn't a redeclaration.
7137   if (ShadowedDecl && !D.isRedeclaration())
7138     CheckShadow(NewVD, ShadowedDecl, Previous);
7139 
7140   ProcessPragmaWeak(S, NewVD);
7141 
7142   // If this is the first declaration of an extern C variable, update
7143   // the map of such variables.
7144   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7145       isIncompleteDeclExternC(*this, NewVD))
7146     RegisterLocallyScopedExternCDecl(NewVD, S);
7147 
7148   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7149     MangleNumberingContext *MCtx;
7150     Decl *ManglingContextDecl;
7151     std::tie(MCtx, ManglingContextDecl) =
7152         getCurrentMangleNumberContext(NewVD->getDeclContext());
7153     if (MCtx) {
7154       Context.setManglingNumber(
7155           NewVD, MCtx->getManglingNumber(
7156                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7157       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7158     }
7159   }
7160 
7161   // Special handling of variable named 'main'.
7162   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7163       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7164       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7165 
7166     // C++ [basic.start.main]p3
7167     // A program that declares a variable main at global scope is ill-formed.
7168     if (getLangOpts().CPlusPlus)
7169       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7170 
7171     // In C, and external-linkage variable named main results in undefined
7172     // behavior.
7173     else if (NewVD->hasExternalFormalLinkage())
7174       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7175   }
7176 
7177   if (D.isRedeclaration() && !Previous.empty()) {
7178     NamedDecl *Prev = Previous.getRepresentativeDecl();
7179     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7180                                    D.isFunctionDefinition());
7181   }
7182 
7183   if (NewTemplate) {
7184     if (NewVD->isInvalidDecl())
7185       NewTemplate->setInvalidDecl();
7186     ActOnDocumentableDecl(NewTemplate);
7187     return NewTemplate;
7188   }
7189 
7190   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7191     CompleteMemberSpecialization(NewVD, Previous);
7192 
7193   return NewVD;
7194 }
7195 
7196 /// Enum describing the %select options in diag::warn_decl_shadow.
7197 enum ShadowedDeclKind {
7198   SDK_Local,
7199   SDK_Global,
7200   SDK_StaticMember,
7201   SDK_Field,
7202   SDK_Typedef,
7203   SDK_Using
7204 };
7205 
7206 /// Determine what kind of declaration we're shadowing.
7207 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7208                                                 const DeclContext *OldDC) {
7209   if (isa<TypeAliasDecl>(ShadowedDecl))
7210     return SDK_Using;
7211   else if (isa<TypedefDecl>(ShadowedDecl))
7212     return SDK_Typedef;
7213   else if (isa<RecordDecl>(OldDC))
7214     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7215 
7216   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7217 }
7218 
7219 /// Return the location of the capture if the given lambda captures the given
7220 /// variable \p VD, or an invalid source location otherwise.
7221 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7222                                          const VarDecl *VD) {
7223   for (const Capture &Capture : LSI->Captures) {
7224     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7225       return Capture.getLocation();
7226   }
7227   return SourceLocation();
7228 }
7229 
7230 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7231                                      const LookupResult &R) {
7232   // Only diagnose if we're shadowing an unambiguous field or variable.
7233   if (R.getResultKind() != LookupResult::Found)
7234     return false;
7235 
7236   // Return false if warning is ignored.
7237   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7238 }
7239 
7240 /// Return the declaration shadowed by the given variable \p D, or null
7241 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7242 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7243                                         const LookupResult &R) {
7244   if (!shouldWarnIfShadowedDecl(Diags, R))
7245     return nullptr;
7246 
7247   // Don't diagnose declarations at file scope.
7248   if (D->hasGlobalStorage())
7249     return nullptr;
7250 
7251   NamedDecl *ShadowedDecl = R.getFoundDecl();
7252   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7253              ? ShadowedDecl
7254              : nullptr;
7255 }
7256 
7257 /// Return the declaration shadowed by the given typedef \p D, or null
7258 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7259 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7260                                         const LookupResult &R) {
7261   // Don't warn if typedef declaration is part of a class
7262   if (D->getDeclContext()->isRecord())
7263     return nullptr;
7264 
7265   if (!shouldWarnIfShadowedDecl(Diags, R))
7266     return nullptr;
7267 
7268   NamedDecl *ShadowedDecl = R.getFoundDecl();
7269   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7270 }
7271 
7272 /// Diagnose variable or built-in function shadowing.  Implements
7273 /// -Wshadow.
7274 ///
7275 /// This method is called whenever a VarDecl is added to a "useful"
7276 /// scope.
7277 ///
7278 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7279 /// \param R the lookup of the name
7280 ///
7281 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7282                        const LookupResult &R) {
7283   DeclContext *NewDC = D->getDeclContext();
7284 
7285   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7286     // Fields are not shadowed by variables in C++ static methods.
7287     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7288       if (MD->isStatic())
7289         return;
7290 
7291     // Fields shadowed by constructor parameters are a special case. Usually
7292     // the constructor initializes the field with the parameter.
7293     if (isa<CXXConstructorDecl>(NewDC))
7294       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7295         // Remember that this was shadowed so we can either warn about its
7296         // modification or its existence depending on warning settings.
7297         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7298         return;
7299       }
7300   }
7301 
7302   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7303     if (shadowedVar->isExternC()) {
7304       // For shadowing external vars, make sure that we point to the global
7305       // declaration, not a locally scoped extern declaration.
7306       for (auto I : shadowedVar->redecls())
7307         if (I->isFileVarDecl()) {
7308           ShadowedDecl = I;
7309           break;
7310         }
7311     }
7312 
7313   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7314 
7315   unsigned WarningDiag = diag::warn_decl_shadow;
7316   SourceLocation CaptureLoc;
7317   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7318       isa<CXXMethodDecl>(NewDC)) {
7319     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7320       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7321         if (RD->getLambdaCaptureDefault() == LCD_None) {
7322           // Try to avoid warnings for lambdas with an explicit capture list.
7323           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7324           // Warn only when the lambda captures the shadowed decl explicitly.
7325           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7326           if (CaptureLoc.isInvalid())
7327             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7328         } else {
7329           // Remember that this was shadowed so we can avoid the warning if the
7330           // shadowed decl isn't captured and the warning settings allow it.
7331           cast<LambdaScopeInfo>(getCurFunction())
7332               ->ShadowingDecls.push_back(
7333                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7334           return;
7335         }
7336       }
7337 
7338       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7339         // A variable can't shadow a local variable in an enclosing scope, if
7340         // they are separated by a non-capturing declaration context.
7341         for (DeclContext *ParentDC = NewDC;
7342              ParentDC && !ParentDC->Equals(OldDC);
7343              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7344           // Only block literals, captured statements, and lambda expressions
7345           // can capture; other scopes don't.
7346           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7347               !isLambdaCallOperator(ParentDC)) {
7348             return;
7349           }
7350         }
7351       }
7352     }
7353   }
7354 
7355   // Only warn about certain kinds of shadowing for class members.
7356   if (NewDC && NewDC->isRecord()) {
7357     // In particular, don't warn about shadowing non-class members.
7358     if (!OldDC->isRecord())
7359       return;
7360 
7361     // TODO: should we warn about static data members shadowing
7362     // static data members from base classes?
7363 
7364     // TODO: don't diagnose for inaccessible shadowed members.
7365     // This is hard to do perfectly because we might friend the
7366     // shadowing context, but that's just a false negative.
7367   }
7368 
7369 
7370   DeclarationName Name = R.getLookupName();
7371 
7372   // Emit warning and note.
7373   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7374     return;
7375   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7376   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7377   if (!CaptureLoc.isInvalid())
7378     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7379         << Name << /*explicitly*/ 1;
7380   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7381 }
7382 
7383 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7384 /// when these variables are captured by the lambda.
7385 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7386   for (const auto &Shadow : LSI->ShadowingDecls) {
7387     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7388     // Try to avoid the warning when the shadowed decl isn't captured.
7389     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7390     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7391     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7392                                        ? diag::warn_decl_shadow_uncaptured_local
7393                                        : diag::warn_decl_shadow)
7394         << Shadow.VD->getDeclName()
7395         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7396     if (!CaptureLoc.isInvalid())
7397       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7398           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7399     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7400   }
7401 }
7402 
7403 /// Check -Wshadow without the advantage of a previous lookup.
7404 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7405   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7406     return;
7407 
7408   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7409                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7410   LookupName(R, S);
7411   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7412     CheckShadow(D, ShadowedDecl, R);
7413 }
7414 
7415 /// Check if 'E', which is an expression that is about to be modified, refers
7416 /// to a constructor parameter that shadows a field.
7417 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7418   // Quickly ignore expressions that can't be shadowing ctor parameters.
7419   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7420     return;
7421   E = E->IgnoreParenImpCasts();
7422   auto *DRE = dyn_cast<DeclRefExpr>(E);
7423   if (!DRE)
7424     return;
7425   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7426   auto I = ShadowingDecls.find(D);
7427   if (I == ShadowingDecls.end())
7428     return;
7429   const NamedDecl *ShadowedDecl = I->second;
7430   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7431   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7432   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7433   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7434 
7435   // Avoid issuing multiple warnings about the same decl.
7436   ShadowingDecls.erase(I);
7437 }
7438 
7439 /// Check for conflict between this global or extern "C" declaration and
7440 /// previous global or extern "C" declarations. This is only used in C++.
7441 template<typename T>
7442 static bool checkGlobalOrExternCConflict(
7443     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7444   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7445   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7446 
7447   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7448     // The common case: this global doesn't conflict with any extern "C"
7449     // declaration.
7450     return false;
7451   }
7452 
7453   if (Prev) {
7454     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7455       // Both the old and new declarations have C language linkage. This is a
7456       // redeclaration.
7457       Previous.clear();
7458       Previous.addDecl(Prev);
7459       return true;
7460     }
7461 
7462     // This is a global, non-extern "C" declaration, and there is a previous
7463     // non-global extern "C" declaration. Diagnose if this is a variable
7464     // declaration.
7465     if (!isa<VarDecl>(ND))
7466       return false;
7467   } else {
7468     // The declaration is extern "C". Check for any declaration in the
7469     // translation unit which might conflict.
7470     if (IsGlobal) {
7471       // We have already performed the lookup into the translation unit.
7472       IsGlobal = false;
7473       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7474            I != E; ++I) {
7475         if (isa<VarDecl>(*I)) {
7476           Prev = *I;
7477           break;
7478         }
7479       }
7480     } else {
7481       DeclContext::lookup_result R =
7482           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7483       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7484            I != E; ++I) {
7485         if (isa<VarDecl>(*I)) {
7486           Prev = *I;
7487           break;
7488         }
7489         // FIXME: If we have any other entity with this name in global scope,
7490         // the declaration is ill-formed, but that is a defect: it breaks the
7491         // 'stat' hack, for instance. Only variables can have mangled name
7492         // clashes with extern "C" declarations, so only they deserve a
7493         // diagnostic.
7494       }
7495     }
7496 
7497     if (!Prev)
7498       return false;
7499   }
7500 
7501   // Use the first declaration's location to ensure we point at something which
7502   // is lexically inside an extern "C" linkage-spec.
7503   assert(Prev && "should have found a previous declaration to diagnose");
7504   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7505     Prev = FD->getFirstDecl();
7506   else
7507     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7508 
7509   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7510     << IsGlobal << ND;
7511   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7512     << IsGlobal;
7513   return false;
7514 }
7515 
7516 /// Apply special rules for handling extern "C" declarations. Returns \c true
7517 /// if we have found that this is a redeclaration of some prior entity.
7518 ///
7519 /// Per C++ [dcl.link]p6:
7520 ///   Two declarations [for a function or variable] with C language linkage
7521 ///   with the same name that appear in different scopes refer to the same
7522 ///   [entity]. An entity with C language linkage shall not be declared with
7523 ///   the same name as an entity in global scope.
7524 template<typename T>
7525 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7526                                                   LookupResult &Previous) {
7527   if (!S.getLangOpts().CPlusPlus) {
7528     // In C, when declaring a global variable, look for a corresponding 'extern'
7529     // variable declared in function scope. We don't need this in C++, because
7530     // we find local extern decls in the surrounding file-scope DeclContext.
7531     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7532       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7533         Previous.clear();
7534         Previous.addDecl(Prev);
7535         return true;
7536       }
7537     }
7538     return false;
7539   }
7540 
7541   // A declaration in the translation unit can conflict with an extern "C"
7542   // declaration.
7543   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7544     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7545 
7546   // An extern "C" declaration can conflict with a declaration in the
7547   // translation unit or can be a redeclaration of an extern "C" declaration
7548   // in another scope.
7549   if (isIncompleteDeclExternC(S,ND))
7550     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7551 
7552   // Neither global nor extern "C": nothing to do.
7553   return false;
7554 }
7555 
7556 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7557   // If the decl is already known invalid, don't check it.
7558   if (NewVD->isInvalidDecl())
7559     return;
7560 
7561   QualType T = NewVD->getType();
7562 
7563   // Defer checking an 'auto' type until its initializer is attached.
7564   if (T->isUndeducedType())
7565     return;
7566 
7567   if (NewVD->hasAttrs())
7568     CheckAlignasUnderalignment(NewVD);
7569 
7570   if (T->isObjCObjectType()) {
7571     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7572       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7573     T = Context.getObjCObjectPointerType(T);
7574     NewVD->setType(T);
7575   }
7576 
7577   // Emit an error if an address space was applied to decl with local storage.
7578   // This includes arrays of objects with address space qualifiers, but not
7579   // automatic variables that point to other address spaces.
7580   // ISO/IEC TR 18037 S5.1.2
7581   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7582       T.getAddressSpace() != LangAS::Default) {
7583     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7584     NewVD->setInvalidDecl();
7585     return;
7586   }
7587 
7588   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7589   // scope.
7590   if (getLangOpts().OpenCLVersion == 120 &&
7591       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7592       NewVD->isStaticLocal()) {
7593     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7594     NewVD->setInvalidDecl();
7595     return;
7596   }
7597 
7598   if (getLangOpts().OpenCL) {
7599     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7600     if (NewVD->hasAttr<BlocksAttr>()) {
7601       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7602       return;
7603     }
7604 
7605     if (T->isBlockPointerType()) {
7606       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7607       // can't use 'extern' storage class.
7608       if (!T.isConstQualified()) {
7609         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7610             << 0 /*const*/;
7611         NewVD->setInvalidDecl();
7612         return;
7613       }
7614       if (NewVD->hasExternalStorage()) {
7615         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7616         NewVD->setInvalidDecl();
7617         return;
7618       }
7619     }
7620     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7621     // __constant address space.
7622     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7623     // variables inside a function can also be declared in the global
7624     // address space.
7625     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7626     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7627     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7628         NewVD->hasExternalStorage()) {
7629       if (!T->isSamplerT() &&
7630           !(T.getAddressSpace() == LangAS::opencl_constant ||
7631             (T.getAddressSpace() == LangAS::opencl_global &&
7632              (getLangOpts().OpenCLVersion == 200 ||
7633               getLangOpts().OpenCLCPlusPlus)))) {
7634         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7635         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7636           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7637               << Scope << "global or constant";
7638         else
7639           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7640               << Scope << "constant";
7641         NewVD->setInvalidDecl();
7642         return;
7643       }
7644     } else {
7645       if (T.getAddressSpace() == LangAS::opencl_global) {
7646         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7647             << 1 /*is any function*/ << "global";
7648         NewVD->setInvalidDecl();
7649         return;
7650       }
7651       if (T.getAddressSpace() == LangAS::opencl_constant ||
7652           T.getAddressSpace() == LangAS::opencl_local) {
7653         FunctionDecl *FD = getCurFunctionDecl();
7654         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7655         // in functions.
7656         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7657           if (T.getAddressSpace() == LangAS::opencl_constant)
7658             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7659                 << 0 /*non-kernel only*/ << "constant";
7660           else
7661             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7662                 << 0 /*non-kernel only*/ << "local";
7663           NewVD->setInvalidDecl();
7664           return;
7665         }
7666         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7667         // in the outermost scope of a kernel function.
7668         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7669           if (!getCurScope()->isFunctionScope()) {
7670             if (T.getAddressSpace() == LangAS::opencl_constant)
7671               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7672                   << "constant";
7673             else
7674               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7675                   << "local";
7676             NewVD->setInvalidDecl();
7677             return;
7678           }
7679         }
7680       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7681                  // If we are parsing a template we didn't deduce an addr
7682                  // space yet.
7683                  T.getAddressSpace() != LangAS::Default) {
7684         // Do not allow other address spaces on automatic variable.
7685         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7686         NewVD->setInvalidDecl();
7687         return;
7688       }
7689     }
7690   }
7691 
7692   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7693       && !NewVD->hasAttr<BlocksAttr>()) {
7694     if (getLangOpts().getGC() != LangOptions::NonGC)
7695       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7696     else {
7697       assert(!getLangOpts().ObjCAutoRefCount);
7698       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7699     }
7700   }
7701 
7702   bool isVM = T->isVariablyModifiedType();
7703   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7704       NewVD->hasAttr<BlocksAttr>())
7705     setFunctionHasBranchProtectedScope();
7706 
7707   if ((isVM && NewVD->hasLinkage()) ||
7708       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7709     bool SizeIsNegative;
7710     llvm::APSInt Oversized;
7711     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7712         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7713     QualType FixedT;
7714     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7715       FixedT = FixedTInfo->getType();
7716     else if (FixedTInfo) {
7717       // Type and type-as-written are canonically different. We need to fix up
7718       // both types separately.
7719       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7720                                                    Oversized);
7721     }
7722     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7723       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7724       // FIXME: This won't give the correct result for
7725       // int a[10][n];
7726       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7727 
7728       if (NewVD->isFileVarDecl())
7729         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7730         << SizeRange;
7731       else if (NewVD->isStaticLocal())
7732         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7733         << SizeRange;
7734       else
7735         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7736         << SizeRange;
7737       NewVD->setInvalidDecl();
7738       return;
7739     }
7740 
7741     if (!FixedTInfo) {
7742       if (NewVD->isFileVarDecl())
7743         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7744       else
7745         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7746       NewVD->setInvalidDecl();
7747       return;
7748     }
7749 
7750     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7751     NewVD->setType(FixedT);
7752     NewVD->setTypeSourceInfo(FixedTInfo);
7753   }
7754 
7755   if (T->isVoidType()) {
7756     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7757     //                    of objects and functions.
7758     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7759       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7760         << T;
7761       NewVD->setInvalidDecl();
7762       return;
7763     }
7764   }
7765 
7766   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7767     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7768     NewVD->setInvalidDecl();
7769     return;
7770   }
7771 
7772   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7773     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7774     NewVD->setInvalidDecl();
7775     return;
7776   }
7777 
7778   if (NewVD->isConstexpr() && !T->isDependentType() &&
7779       RequireLiteralType(NewVD->getLocation(), T,
7780                          diag::err_constexpr_var_non_literal)) {
7781     NewVD->setInvalidDecl();
7782     return;
7783   }
7784 }
7785 
7786 /// Perform semantic checking on a newly-created variable
7787 /// declaration.
7788 ///
7789 /// This routine performs all of the type-checking required for a
7790 /// variable declaration once it has been built. It is used both to
7791 /// check variables after they have been parsed and their declarators
7792 /// have been translated into a declaration, and to check variables
7793 /// that have been instantiated from a template.
7794 ///
7795 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7796 ///
7797 /// Returns true if the variable declaration is a redeclaration.
7798 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7799   CheckVariableDeclarationType(NewVD);
7800 
7801   // If the decl is already known invalid, don't check it.
7802   if (NewVD->isInvalidDecl())
7803     return false;
7804 
7805   // If we did not find anything by this name, look for a non-visible
7806   // extern "C" declaration with the same name.
7807   if (Previous.empty() &&
7808       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7809     Previous.setShadowed();
7810 
7811   if (!Previous.empty()) {
7812     MergeVarDecl(NewVD, Previous);
7813     return true;
7814   }
7815   return false;
7816 }
7817 
7818 namespace {
7819 struct FindOverriddenMethod {
7820   Sema *S;
7821   CXXMethodDecl *Method;
7822 
7823   /// Member lookup function that determines whether a given C++
7824   /// method overrides a method in a base class, to be used with
7825   /// CXXRecordDecl::lookupInBases().
7826   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7827     RecordDecl *BaseRecord =
7828         Specifier->getType()->castAs<RecordType>()->getDecl();
7829 
7830     DeclarationName Name = Method->getDeclName();
7831 
7832     // FIXME: Do we care about other names here too?
7833     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7834       // We really want to find the base class destructor here.
7835       QualType T = S->Context.getTypeDeclType(BaseRecord);
7836       CanQualType CT = S->Context.getCanonicalType(T);
7837 
7838       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7839     }
7840 
7841     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7842          Path.Decls = Path.Decls.slice(1)) {
7843       NamedDecl *D = Path.Decls.front();
7844       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7845         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7846           return true;
7847       }
7848     }
7849 
7850     return false;
7851   }
7852 };
7853 
7854 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7855 } // end anonymous namespace
7856 
7857 /// Report an error regarding overriding, along with any relevant
7858 /// overridden methods.
7859 ///
7860 /// \param DiagID the primary error to report.
7861 /// \param MD the overriding method.
7862 /// \param OEK which overrides to include as notes.
7863 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7864                             OverrideErrorKind OEK = OEK_All) {
7865   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7866   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7867     // This check (& the OEK parameter) could be replaced by a predicate, but
7868     // without lambdas that would be overkill. This is still nicer than writing
7869     // out the diag loop 3 times.
7870     if ((OEK == OEK_All) ||
7871         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7872         (OEK == OEK_Deleted && O->isDeleted()))
7873       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7874   }
7875 }
7876 
7877 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7878 /// and if so, check that it's a valid override and remember it.
7879 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7880   // Look for methods in base classes that this method might override.
7881   CXXBasePaths Paths;
7882   FindOverriddenMethod FOM;
7883   FOM.Method = MD;
7884   FOM.S = this;
7885   bool hasDeletedOverridenMethods = false;
7886   bool hasNonDeletedOverridenMethods = false;
7887   bool AddedAny = false;
7888   if (DC->lookupInBases(FOM, Paths)) {
7889     for (auto *I : Paths.found_decls()) {
7890       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7891         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7892         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7893             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7894             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7895             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7896           hasDeletedOverridenMethods |= OldMD->isDeleted();
7897           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7898           AddedAny = true;
7899         }
7900       }
7901     }
7902   }
7903 
7904   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7905     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7906   }
7907   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7908     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7909   }
7910 
7911   return AddedAny;
7912 }
7913 
7914 namespace {
7915   // Struct for holding all of the extra arguments needed by
7916   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7917   struct ActOnFDArgs {
7918     Scope *S;
7919     Declarator &D;
7920     MultiTemplateParamsArg TemplateParamLists;
7921     bool AddToScope;
7922   };
7923 } // end anonymous namespace
7924 
7925 namespace {
7926 
7927 // Callback to only accept typo corrections that have a non-zero edit distance.
7928 // Also only accept corrections that have the same parent decl.
7929 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7930  public:
7931   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7932                             CXXRecordDecl *Parent)
7933       : Context(Context), OriginalFD(TypoFD),
7934         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7935 
7936   bool ValidateCandidate(const TypoCorrection &candidate) override {
7937     if (candidate.getEditDistance() == 0)
7938       return false;
7939 
7940     SmallVector<unsigned, 1> MismatchedParams;
7941     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7942                                           CDeclEnd = candidate.end();
7943          CDecl != CDeclEnd; ++CDecl) {
7944       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7945 
7946       if (FD && !FD->hasBody() &&
7947           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7948         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7949           CXXRecordDecl *Parent = MD->getParent();
7950           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7951             return true;
7952         } else if (!ExpectedParent) {
7953           return true;
7954         }
7955       }
7956     }
7957 
7958     return false;
7959   }
7960 
7961   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7962     return std::make_unique<DifferentNameValidatorCCC>(*this);
7963   }
7964 
7965  private:
7966   ASTContext &Context;
7967   FunctionDecl *OriginalFD;
7968   CXXRecordDecl *ExpectedParent;
7969 };
7970 
7971 } // end anonymous namespace
7972 
7973 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7974   TypoCorrectedFunctionDefinitions.insert(F);
7975 }
7976 
7977 /// Generate diagnostics for an invalid function redeclaration.
7978 ///
7979 /// This routine handles generating the diagnostic messages for an invalid
7980 /// function redeclaration, including finding possible similar declarations
7981 /// or performing typo correction if there are no previous declarations with
7982 /// the same name.
7983 ///
7984 /// Returns a NamedDecl iff typo correction was performed and substituting in
7985 /// the new declaration name does not cause new errors.
7986 static NamedDecl *DiagnoseInvalidRedeclaration(
7987     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7988     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7989   DeclarationName Name = NewFD->getDeclName();
7990   DeclContext *NewDC = NewFD->getDeclContext();
7991   SmallVector<unsigned, 1> MismatchedParams;
7992   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7993   TypoCorrection Correction;
7994   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7995   unsigned DiagMsg =
7996     IsLocalFriend ? diag::err_no_matching_local_friend :
7997     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7998     diag::err_member_decl_does_not_match;
7999   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8000                     IsLocalFriend ? Sema::LookupLocalFriendName
8001                                   : Sema::LookupOrdinaryName,
8002                     Sema::ForVisibleRedeclaration);
8003 
8004   NewFD->setInvalidDecl();
8005   if (IsLocalFriend)
8006     SemaRef.LookupName(Prev, S);
8007   else
8008     SemaRef.LookupQualifiedName(Prev, NewDC);
8009   assert(!Prev.isAmbiguous() &&
8010          "Cannot have an ambiguity in previous-declaration lookup");
8011   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8012   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8013                                 MD ? MD->getParent() : nullptr);
8014   if (!Prev.empty()) {
8015     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8016          Func != FuncEnd; ++Func) {
8017       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8018       if (FD &&
8019           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8020         // Add 1 to the index so that 0 can mean the mismatch didn't
8021         // involve a parameter
8022         unsigned ParamNum =
8023             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8024         NearMatches.push_back(std::make_pair(FD, ParamNum));
8025       }
8026     }
8027   // If the qualified name lookup yielded nothing, try typo correction
8028   } else if ((Correction = SemaRef.CorrectTypo(
8029                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8030                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8031                   IsLocalFriend ? nullptr : NewDC))) {
8032     // Set up everything for the call to ActOnFunctionDeclarator
8033     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8034                               ExtraArgs.D.getIdentifierLoc());
8035     Previous.clear();
8036     Previous.setLookupName(Correction.getCorrection());
8037     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8038                                     CDeclEnd = Correction.end();
8039          CDecl != CDeclEnd; ++CDecl) {
8040       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8041       if (FD && !FD->hasBody() &&
8042           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8043         Previous.addDecl(FD);
8044       }
8045     }
8046     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8047 
8048     NamedDecl *Result;
8049     // Retry building the function declaration with the new previous
8050     // declarations, and with errors suppressed.
8051     {
8052       // Trap errors.
8053       Sema::SFINAETrap Trap(SemaRef);
8054 
8055       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8056       // pieces need to verify the typo-corrected C++ declaration and hopefully
8057       // eliminate the need for the parameter pack ExtraArgs.
8058       Result = SemaRef.ActOnFunctionDeclarator(
8059           ExtraArgs.S, ExtraArgs.D,
8060           Correction.getCorrectionDecl()->getDeclContext(),
8061           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8062           ExtraArgs.AddToScope);
8063 
8064       if (Trap.hasErrorOccurred())
8065         Result = nullptr;
8066     }
8067 
8068     if (Result) {
8069       // Determine which correction we picked.
8070       Decl *Canonical = Result->getCanonicalDecl();
8071       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8072            I != E; ++I)
8073         if ((*I)->getCanonicalDecl() == Canonical)
8074           Correction.setCorrectionDecl(*I);
8075 
8076       // Let Sema know about the correction.
8077       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8078       SemaRef.diagnoseTypo(
8079           Correction,
8080           SemaRef.PDiag(IsLocalFriend
8081                           ? diag::err_no_matching_local_friend_suggest
8082                           : diag::err_member_decl_does_not_match_suggest)
8083             << Name << NewDC << IsDefinition);
8084       return Result;
8085     }
8086 
8087     // Pretend the typo correction never occurred
8088     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8089                               ExtraArgs.D.getIdentifierLoc());
8090     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8091     Previous.clear();
8092     Previous.setLookupName(Name);
8093   }
8094 
8095   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8096       << Name << NewDC << IsDefinition << NewFD->getLocation();
8097 
8098   bool NewFDisConst = false;
8099   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8100     NewFDisConst = NewMD->isConst();
8101 
8102   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8103        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8104        NearMatch != NearMatchEnd; ++NearMatch) {
8105     FunctionDecl *FD = NearMatch->first;
8106     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8107     bool FDisConst = MD && MD->isConst();
8108     bool IsMember = MD || !IsLocalFriend;
8109 
8110     // FIXME: These notes are poorly worded for the local friend case.
8111     if (unsigned Idx = NearMatch->second) {
8112       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8113       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8114       if (Loc.isInvalid()) Loc = FD->getLocation();
8115       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8116                                  : diag::note_local_decl_close_param_match)
8117         << Idx << FDParam->getType()
8118         << NewFD->getParamDecl(Idx - 1)->getType();
8119     } else if (FDisConst != NewFDisConst) {
8120       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8121           << NewFDisConst << FD->getSourceRange().getEnd();
8122     } else
8123       SemaRef.Diag(FD->getLocation(),
8124                    IsMember ? diag::note_member_def_close_match
8125                             : diag::note_local_decl_close_match);
8126   }
8127   return nullptr;
8128 }
8129 
8130 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8131   switch (D.getDeclSpec().getStorageClassSpec()) {
8132   default: llvm_unreachable("Unknown storage class!");
8133   case DeclSpec::SCS_auto:
8134   case DeclSpec::SCS_register:
8135   case DeclSpec::SCS_mutable:
8136     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8137                  diag::err_typecheck_sclass_func);
8138     D.getMutableDeclSpec().ClearStorageClassSpecs();
8139     D.setInvalidType();
8140     break;
8141   case DeclSpec::SCS_unspecified: break;
8142   case DeclSpec::SCS_extern:
8143     if (D.getDeclSpec().isExternInLinkageSpec())
8144       return SC_None;
8145     return SC_Extern;
8146   case DeclSpec::SCS_static: {
8147     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8148       // C99 6.7.1p5:
8149       //   The declaration of an identifier for a function that has
8150       //   block scope shall have no explicit storage-class specifier
8151       //   other than extern
8152       // See also (C++ [dcl.stc]p4).
8153       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8154                    diag::err_static_block_func);
8155       break;
8156     } else
8157       return SC_Static;
8158   }
8159   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8160   }
8161 
8162   // No explicit storage class has already been returned
8163   return SC_None;
8164 }
8165 
8166 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8167                                            DeclContext *DC, QualType &R,
8168                                            TypeSourceInfo *TInfo,
8169                                            StorageClass SC,
8170                                            bool &IsVirtualOkay) {
8171   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8172   DeclarationName Name = NameInfo.getName();
8173 
8174   FunctionDecl *NewFD = nullptr;
8175   bool isInline = D.getDeclSpec().isInlineSpecified();
8176 
8177   if (!SemaRef.getLangOpts().CPlusPlus) {
8178     // Determine whether the function was written with a
8179     // prototype. This true when:
8180     //   - there is a prototype in the declarator, or
8181     //   - the type R of the function is some kind of typedef or other non-
8182     //     attributed reference to a type name (which eventually refers to a
8183     //     function type).
8184     bool HasPrototype =
8185       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8186       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8187 
8188     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8189                                  R, TInfo, SC, isInline, HasPrototype,
8190                                  CSK_unspecified);
8191     if (D.isInvalidType())
8192       NewFD->setInvalidDecl();
8193 
8194     return NewFD;
8195   }
8196 
8197   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8198 
8199   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8200   if (ConstexprKind == CSK_constinit) {
8201     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8202                  diag::err_constexpr_wrong_decl_kind)
8203         << ConstexprKind;
8204     ConstexprKind = CSK_unspecified;
8205     D.getMutableDeclSpec().ClearConstexprSpec();
8206   }
8207 
8208   // Check that the return type is not an abstract class type.
8209   // For record types, this is done by the AbstractClassUsageDiagnoser once
8210   // the class has been completely parsed.
8211   if (!DC->isRecord() &&
8212       SemaRef.RequireNonAbstractType(
8213           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8214           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8215     D.setInvalidType();
8216 
8217   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8218     // This is a C++ constructor declaration.
8219     assert(DC->isRecord() &&
8220            "Constructors can only be declared in a member context");
8221 
8222     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8223     return CXXConstructorDecl::Create(
8224         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8225         TInfo, ExplicitSpecifier, isInline,
8226         /*isImplicitlyDeclared=*/false, ConstexprKind);
8227 
8228   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8229     // This is a C++ destructor declaration.
8230     if (DC->isRecord()) {
8231       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8232       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8233       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8234           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8235           isInline,
8236           /*isImplicitlyDeclared=*/false, ConstexprKind);
8237 
8238       // If the destructor needs an implicit exception specification, set it
8239       // now. FIXME: It'd be nice to be able to create the right type to start
8240       // with, but the type needs to reference the destructor declaration.
8241       if (SemaRef.getLangOpts().CPlusPlus11)
8242         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8243 
8244       IsVirtualOkay = true;
8245       return NewDD;
8246 
8247     } else {
8248       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8249       D.setInvalidType();
8250 
8251       // Create a FunctionDecl to satisfy the function definition parsing
8252       // code path.
8253       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8254                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8255                                   isInline,
8256                                   /*hasPrototype=*/true, ConstexprKind);
8257     }
8258 
8259   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8260     if (!DC->isRecord()) {
8261       SemaRef.Diag(D.getIdentifierLoc(),
8262            diag::err_conv_function_not_member);
8263       return nullptr;
8264     }
8265 
8266     SemaRef.CheckConversionDeclarator(D, R, SC);
8267     if (D.isInvalidType())
8268       return nullptr;
8269 
8270     IsVirtualOkay = true;
8271     return CXXConversionDecl::Create(
8272         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8273         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8274 
8275   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8276     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8277 
8278     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8279                                          ExplicitSpecifier, NameInfo, R, TInfo,
8280                                          D.getEndLoc());
8281   } else if (DC->isRecord()) {
8282     // If the name of the function is the same as the name of the record,
8283     // then this must be an invalid constructor that has a return type.
8284     // (The parser checks for a return type and makes the declarator a
8285     // constructor if it has no return type).
8286     if (Name.getAsIdentifierInfo() &&
8287         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8288       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8289         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8290         << SourceRange(D.getIdentifierLoc());
8291       return nullptr;
8292     }
8293 
8294     // This is a C++ method declaration.
8295     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8296         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8297         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8298     IsVirtualOkay = !Ret->isStatic();
8299     return Ret;
8300   } else {
8301     bool isFriend =
8302         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8303     if (!isFriend && SemaRef.CurContext->isRecord())
8304       return nullptr;
8305 
8306     // Determine whether the function was written with a
8307     // prototype. This true when:
8308     //   - we're in C++ (where every function has a prototype),
8309     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8310                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8311                                 ConstexprKind);
8312   }
8313 }
8314 
8315 enum OpenCLParamType {
8316   ValidKernelParam,
8317   PtrPtrKernelParam,
8318   PtrKernelParam,
8319   InvalidAddrSpacePtrKernelParam,
8320   InvalidKernelParam,
8321   RecordKernelParam
8322 };
8323 
8324 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8325   // Size dependent types are just typedefs to normal integer types
8326   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8327   // integers other than by their names.
8328   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8329 
8330   // Remove typedefs one by one until we reach a typedef
8331   // for a size dependent type.
8332   QualType DesugaredTy = Ty;
8333   do {
8334     ArrayRef<StringRef> Names(SizeTypeNames);
8335     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8336     if (Names.end() != Match)
8337       return true;
8338 
8339     Ty = DesugaredTy;
8340     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8341   } while (DesugaredTy != Ty);
8342 
8343   return false;
8344 }
8345 
8346 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8347   if (PT->isPointerType()) {
8348     QualType PointeeType = PT->getPointeeType();
8349     if (PointeeType->isPointerType())
8350       return PtrPtrKernelParam;
8351     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8352         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8353         PointeeType.getAddressSpace() == LangAS::Default)
8354       return InvalidAddrSpacePtrKernelParam;
8355     return PtrKernelParam;
8356   }
8357 
8358   // OpenCL v1.2 s6.9.k:
8359   // Arguments to kernel functions in a program cannot be declared with the
8360   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8361   // uintptr_t or a struct and/or union that contain fields declared to be one
8362   // of these built-in scalar types.
8363   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8364     return InvalidKernelParam;
8365 
8366   if (PT->isImageType())
8367     return PtrKernelParam;
8368 
8369   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8370     return InvalidKernelParam;
8371 
8372   // OpenCL extension spec v1.2 s9.5:
8373   // This extension adds support for half scalar and vector types as built-in
8374   // types that can be used for arithmetic operations, conversions etc.
8375   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8376     return InvalidKernelParam;
8377 
8378   if (PT->isRecordType())
8379     return RecordKernelParam;
8380 
8381   // Look into an array argument to check if it has a forbidden type.
8382   if (PT->isArrayType()) {
8383     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8384     // Call ourself to check an underlying type of an array. Since the
8385     // getPointeeOrArrayElementType returns an innermost type which is not an
8386     // array, this recursive call only happens once.
8387     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8388   }
8389 
8390   return ValidKernelParam;
8391 }
8392 
8393 static void checkIsValidOpenCLKernelParameter(
8394   Sema &S,
8395   Declarator &D,
8396   ParmVarDecl *Param,
8397   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8398   QualType PT = Param->getType();
8399 
8400   // Cache the valid types we encounter to avoid rechecking structs that are
8401   // used again
8402   if (ValidTypes.count(PT.getTypePtr()))
8403     return;
8404 
8405   switch (getOpenCLKernelParameterType(S, PT)) {
8406   case PtrPtrKernelParam:
8407     // OpenCL v1.2 s6.9.a:
8408     // A kernel function argument cannot be declared as a
8409     // pointer to a pointer type.
8410     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8411     D.setInvalidType();
8412     return;
8413 
8414   case InvalidAddrSpacePtrKernelParam:
8415     // OpenCL v1.0 s6.5:
8416     // __kernel function arguments declared to be a pointer of a type can point
8417     // to one of the following address spaces only : __global, __local or
8418     // __constant.
8419     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8420     D.setInvalidType();
8421     return;
8422 
8423     // OpenCL v1.2 s6.9.k:
8424     // Arguments to kernel functions in a program cannot be declared with the
8425     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8426     // uintptr_t or a struct and/or union that contain fields declared to be
8427     // one of these built-in scalar types.
8428 
8429   case InvalidKernelParam:
8430     // OpenCL v1.2 s6.8 n:
8431     // A kernel function argument cannot be declared
8432     // of event_t type.
8433     // Do not diagnose half type since it is diagnosed as invalid argument
8434     // type for any function elsewhere.
8435     if (!PT->isHalfType()) {
8436       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8437 
8438       // Explain what typedefs are involved.
8439       const TypedefType *Typedef = nullptr;
8440       while ((Typedef = PT->getAs<TypedefType>())) {
8441         SourceLocation Loc = Typedef->getDecl()->getLocation();
8442         // SourceLocation may be invalid for a built-in type.
8443         if (Loc.isValid())
8444           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8445         PT = Typedef->desugar();
8446       }
8447     }
8448 
8449     D.setInvalidType();
8450     return;
8451 
8452   case PtrKernelParam:
8453   case ValidKernelParam:
8454     ValidTypes.insert(PT.getTypePtr());
8455     return;
8456 
8457   case RecordKernelParam:
8458     break;
8459   }
8460 
8461   // Track nested structs we will inspect
8462   SmallVector<const Decl *, 4> VisitStack;
8463 
8464   // Track where we are in the nested structs. Items will migrate from
8465   // VisitStack to HistoryStack as we do the DFS for bad field.
8466   SmallVector<const FieldDecl *, 4> HistoryStack;
8467   HistoryStack.push_back(nullptr);
8468 
8469   // At this point we already handled everything except of a RecordType or
8470   // an ArrayType of a RecordType.
8471   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8472   const RecordType *RecTy =
8473       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8474   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8475 
8476   VisitStack.push_back(RecTy->getDecl());
8477   assert(VisitStack.back() && "First decl null?");
8478 
8479   do {
8480     const Decl *Next = VisitStack.pop_back_val();
8481     if (!Next) {
8482       assert(!HistoryStack.empty());
8483       // Found a marker, we have gone up a level
8484       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8485         ValidTypes.insert(Hist->getType().getTypePtr());
8486 
8487       continue;
8488     }
8489 
8490     // Adds everything except the original parameter declaration (which is not a
8491     // field itself) to the history stack.
8492     const RecordDecl *RD;
8493     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8494       HistoryStack.push_back(Field);
8495 
8496       QualType FieldTy = Field->getType();
8497       // Other field types (known to be valid or invalid) are handled while we
8498       // walk around RecordDecl::fields().
8499       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8500              "Unexpected type.");
8501       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8502 
8503       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8504     } else {
8505       RD = cast<RecordDecl>(Next);
8506     }
8507 
8508     // Add a null marker so we know when we've gone back up a level
8509     VisitStack.push_back(nullptr);
8510 
8511     for (const auto *FD : RD->fields()) {
8512       QualType QT = FD->getType();
8513 
8514       if (ValidTypes.count(QT.getTypePtr()))
8515         continue;
8516 
8517       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8518       if (ParamType == ValidKernelParam)
8519         continue;
8520 
8521       if (ParamType == RecordKernelParam) {
8522         VisitStack.push_back(FD);
8523         continue;
8524       }
8525 
8526       // OpenCL v1.2 s6.9.p:
8527       // Arguments to kernel functions that are declared to be a struct or union
8528       // do not allow OpenCL objects to be passed as elements of the struct or
8529       // union.
8530       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8531           ParamType == InvalidAddrSpacePtrKernelParam) {
8532         S.Diag(Param->getLocation(),
8533                diag::err_record_with_pointers_kernel_param)
8534           << PT->isUnionType()
8535           << PT;
8536       } else {
8537         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8538       }
8539 
8540       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8541           << OrigRecDecl->getDeclName();
8542 
8543       // We have an error, now let's go back up through history and show where
8544       // the offending field came from
8545       for (ArrayRef<const FieldDecl *>::const_iterator
8546                I = HistoryStack.begin() + 1,
8547                E = HistoryStack.end();
8548            I != E; ++I) {
8549         const FieldDecl *OuterField = *I;
8550         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8551           << OuterField->getType();
8552       }
8553 
8554       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8555         << QT->isPointerType()
8556         << QT;
8557       D.setInvalidType();
8558       return;
8559     }
8560   } while (!VisitStack.empty());
8561 }
8562 
8563 /// Find the DeclContext in which a tag is implicitly declared if we see an
8564 /// elaborated type specifier in the specified context, and lookup finds
8565 /// nothing.
8566 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8567   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8568     DC = DC->getParent();
8569   return DC;
8570 }
8571 
8572 /// Find the Scope in which a tag is implicitly declared if we see an
8573 /// elaborated type specifier in the specified context, and lookup finds
8574 /// nothing.
8575 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8576   while (S->isClassScope() ||
8577          (LangOpts.CPlusPlus &&
8578           S->isFunctionPrototypeScope()) ||
8579          ((S->getFlags() & Scope::DeclScope) == 0) ||
8580          (S->getEntity() && S->getEntity()->isTransparentContext()))
8581     S = S->getParent();
8582   return S;
8583 }
8584 
8585 NamedDecl*
8586 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8587                               TypeSourceInfo *TInfo, LookupResult &Previous,
8588                               MultiTemplateParamsArg TemplateParamLists,
8589                               bool &AddToScope) {
8590   QualType R = TInfo->getType();
8591 
8592   assert(R->isFunctionType());
8593 
8594   // TODO: consider using NameInfo for diagnostic.
8595   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8596   DeclarationName Name = NameInfo.getName();
8597   StorageClass SC = getFunctionStorageClass(*this, D);
8598 
8599   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8600     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8601          diag::err_invalid_thread)
8602       << DeclSpec::getSpecifierName(TSCS);
8603 
8604   if (D.isFirstDeclarationOfMember())
8605     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8606                            D.getIdentifierLoc());
8607 
8608   bool isFriend = false;
8609   FunctionTemplateDecl *FunctionTemplate = nullptr;
8610   bool isMemberSpecialization = false;
8611   bool isFunctionTemplateSpecialization = false;
8612 
8613   bool isDependentClassScopeExplicitSpecialization = false;
8614   bool HasExplicitTemplateArgs = false;
8615   TemplateArgumentListInfo TemplateArgs;
8616 
8617   bool isVirtualOkay = false;
8618 
8619   DeclContext *OriginalDC = DC;
8620   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8621 
8622   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8623                                               isVirtualOkay);
8624   if (!NewFD) return nullptr;
8625 
8626   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8627     NewFD->setTopLevelDeclInObjCContainer();
8628 
8629   // Set the lexical context. If this is a function-scope declaration, or has a
8630   // C++ scope specifier, or is the object of a friend declaration, the lexical
8631   // context will be different from the semantic context.
8632   NewFD->setLexicalDeclContext(CurContext);
8633 
8634   if (IsLocalExternDecl)
8635     NewFD->setLocalExternDecl();
8636 
8637   if (getLangOpts().CPlusPlus) {
8638     bool isInline = D.getDeclSpec().isInlineSpecified();
8639     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8640     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8641     isFriend = D.getDeclSpec().isFriendSpecified();
8642     if (isFriend && !isInline && D.isFunctionDefinition()) {
8643       // C++ [class.friend]p5
8644       //   A function can be defined in a friend declaration of a
8645       //   class . . . . Such a function is implicitly inline.
8646       NewFD->setImplicitlyInline();
8647     }
8648 
8649     // If this is a method defined in an __interface, and is not a constructor
8650     // or an overloaded operator, then set the pure flag (isVirtual will already
8651     // return true).
8652     if (const CXXRecordDecl *Parent =
8653           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8654       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8655         NewFD->setPure(true);
8656 
8657       // C++ [class.union]p2
8658       //   A union can have member functions, but not virtual functions.
8659       if (isVirtual && Parent->isUnion())
8660         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8661     }
8662 
8663     SetNestedNameSpecifier(*this, NewFD, D);
8664     isMemberSpecialization = false;
8665     isFunctionTemplateSpecialization = false;
8666     if (D.isInvalidType())
8667       NewFD->setInvalidDecl();
8668 
8669     // Match up the template parameter lists with the scope specifier, then
8670     // determine whether we have a template or a template specialization.
8671     bool Invalid = false;
8672     if (TemplateParameterList *TemplateParams =
8673             MatchTemplateParametersToScopeSpecifier(
8674                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8675                 D.getCXXScopeSpec(),
8676                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8677                     ? D.getName().TemplateId
8678                     : nullptr,
8679                 TemplateParamLists, isFriend, isMemberSpecialization,
8680                 Invalid)) {
8681       if (TemplateParams->size() > 0) {
8682         // This is a function template
8683 
8684         // Check that we can declare a template here.
8685         if (CheckTemplateDeclScope(S, TemplateParams))
8686           NewFD->setInvalidDecl();
8687 
8688         // A destructor cannot be a template.
8689         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8690           Diag(NewFD->getLocation(), diag::err_destructor_template);
8691           NewFD->setInvalidDecl();
8692         }
8693 
8694         // If we're adding a template to a dependent context, we may need to
8695         // rebuilding some of the types used within the template parameter list,
8696         // now that we know what the current instantiation is.
8697         if (DC->isDependentContext()) {
8698           ContextRAII SavedContext(*this, DC);
8699           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8700             Invalid = true;
8701         }
8702 
8703         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8704                                                         NewFD->getLocation(),
8705                                                         Name, TemplateParams,
8706                                                         NewFD);
8707         FunctionTemplate->setLexicalDeclContext(CurContext);
8708         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8709 
8710         // For source fidelity, store the other template param lists.
8711         if (TemplateParamLists.size() > 1) {
8712           NewFD->setTemplateParameterListsInfo(Context,
8713                                                TemplateParamLists.drop_back(1));
8714         }
8715       } else {
8716         // This is a function template specialization.
8717         isFunctionTemplateSpecialization = true;
8718         // For source fidelity, store all the template param lists.
8719         if (TemplateParamLists.size() > 0)
8720           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8721 
8722         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8723         if (isFriend) {
8724           // We want to remove the "template<>", found here.
8725           SourceRange RemoveRange = TemplateParams->getSourceRange();
8726 
8727           // If we remove the template<> and the name is not a
8728           // template-id, we're actually silently creating a problem:
8729           // the friend declaration will refer to an untemplated decl,
8730           // and clearly the user wants a template specialization.  So
8731           // we need to insert '<>' after the name.
8732           SourceLocation InsertLoc;
8733           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8734             InsertLoc = D.getName().getSourceRange().getEnd();
8735             InsertLoc = getLocForEndOfToken(InsertLoc);
8736           }
8737 
8738           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8739             << Name << RemoveRange
8740             << FixItHint::CreateRemoval(RemoveRange)
8741             << FixItHint::CreateInsertion(InsertLoc, "<>");
8742         }
8743       }
8744     } else {
8745       // All template param lists were matched against the scope specifier:
8746       // this is NOT (an explicit specialization of) a template.
8747       if (TemplateParamLists.size() > 0)
8748         // For source fidelity, store all the template param lists.
8749         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8750     }
8751 
8752     if (Invalid) {
8753       NewFD->setInvalidDecl();
8754       if (FunctionTemplate)
8755         FunctionTemplate->setInvalidDecl();
8756     }
8757 
8758     // C++ [dcl.fct.spec]p5:
8759     //   The virtual specifier shall only be used in declarations of
8760     //   nonstatic class member functions that appear within a
8761     //   member-specification of a class declaration; see 10.3.
8762     //
8763     if (isVirtual && !NewFD->isInvalidDecl()) {
8764       if (!isVirtualOkay) {
8765         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8766              diag::err_virtual_non_function);
8767       } else if (!CurContext->isRecord()) {
8768         // 'virtual' was specified outside of the class.
8769         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8770              diag::err_virtual_out_of_class)
8771           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8772       } else if (NewFD->getDescribedFunctionTemplate()) {
8773         // C++ [temp.mem]p3:
8774         //  A member function template shall not be virtual.
8775         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8776              diag::err_virtual_member_function_template)
8777           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8778       } else {
8779         // Okay: Add virtual to the method.
8780         NewFD->setVirtualAsWritten(true);
8781       }
8782 
8783       if (getLangOpts().CPlusPlus14 &&
8784           NewFD->getReturnType()->isUndeducedType())
8785         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8786     }
8787 
8788     if (getLangOpts().CPlusPlus14 &&
8789         (NewFD->isDependentContext() ||
8790          (isFriend && CurContext->isDependentContext())) &&
8791         NewFD->getReturnType()->isUndeducedType()) {
8792       // If the function template is referenced directly (for instance, as a
8793       // member of the current instantiation), pretend it has a dependent type.
8794       // This is not really justified by the standard, but is the only sane
8795       // thing to do.
8796       // FIXME: For a friend function, we have not marked the function as being
8797       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8798       const FunctionProtoType *FPT =
8799           NewFD->getType()->castAs<FunctionProtoType>();
8800       QualType Result =
8801           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8802       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8803                                              FPT->getExtProtoInfo()));
8804     }
8805 
8806     // C++ [dcl.fct.spec]p3:
8807     //  The inline specifier shall not appear on a block scope function
8808     //  declaration.
8809     if (isInline && !NewFD->isInvalidDecl()) {
8810       if (CurContext->isFunctionOrMethod()) {
8811         // 'inline' is not allowed on block scope function declaration.
8812         Diag(D.getDeclSpec().getInlineSpecLoc(),
8813              diag::err_inline_declaration_block_scope) << Name
8814           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8815       }
8816     }
8817 
8818     // C++ [dcl.fct.spec]p6:
8819     //  The explicit specifier shall be used only in the declaration of a
8820     //  constructor or conversion function within its class definition;
8821     //  see 12.3.1 and 12.3.2.
8822     if (hasExplicit && !NewFD->isInvalidDecl() &&
8823         !isa<CXXDeductionGuideDecl>(NewFD)) {
8824       if (!CurContext->isRecord()) {
8825         // 'explicit' was specified outside of the class.
8826         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8827              diag::err_explicit_out_of_class)
8828             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8829       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8830                  !isa<CXXConversionDecl>(NewFD)) {
8831         // 'explicit' was specified on a function that wasn't a constructor
8832         // or conversion function.
8833         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8834              diag::err_explicit_non_ctor_or_conv_function)
8835             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8836       }
8837     }
8838 
8839     if (ConstexprSpecKind ConstexprKind =
8840             D.getDeclSpec().getConstexprSpecifier()) {
8841       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8842       // are implicitly inline.
8843       NewFD->setImplicitlyInline();
8844 
8845       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8846       // be either constructors or to return a literal type. Therefore,
8847       // destructors cannot be declared constexpr.
8848       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8849         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8850             << ConstexprKind;
8851       }
8852     }
8853 
8854     // If __module_private__ was specified, mark the function accordingly.
8855     if (D.getDeclSpec().isModulePrivateSpecified()) {
8856       if (isFunctionTemplateSpecialization) {
8857         SourceLocation ModulePrivateLoc
8858           = D.getDeclSpec().getModulePrivateSpecLoc();
8859         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8860           << 0
8861           << FixItHint::CreateRemoval(ModulePrivateLoc);
8862       } else {
8863         NewFD->setModulePrivate();
8864         if (FunctionTemplate)
8865           FunctionTemplate->setModulePrivate();
8866       }
8867     }
8868 
8869     if (isFriend) {
8870       if (FunctionTemplate) {
8871         FunctionTemplate->setObjectOfFriendDecl();
8872         FunctionTemplate->setAccess(AS_public);
8873       }
8874       NewFD->setObjectOfFriendDecl();
8875       NewFD->setAccess(AS_public);
8876     }
8877 
8878     // If a function is defined as defaulted or deleted, mark it as such now.
8879     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8880     // definition kind to FDK_Definition.
8881     switch (D.getFunctionDefinitionKind()) {
8882       case FDK_Declaration:
8883       case FDK_Definition:
8884         break;
8885 
8886       case FDK_Defaulted:
8887         NewFD->setDefaulted();
8888         break;
8889 
8890       case FDK_Deleted:
8891         NewFD->setDeletedAsWritten();
8892         break;
8893     }
8894 
8895     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8896         D.isFunctionDefinition()) {
8897       // C++ [class.mfct]p2:
8898       //   A member function may be defined (8.4) in its class definition, in
8899       //   which case it is an inline member function (7.1.2)
8900       NewFD->setImplicitlyInline();
8901     }
8902 
8903     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8904         !CurContext->isRecord()) {
8905       // C++ [class.static]p1:
8906       //   A data or function member of a class may be declared static
8907       //   in a class definition, in which case it is a static member of
8908       //   the class.
8909 
8910       // Complain about the 'static' specifier if it's on an out-of-line
8911       // member function definition.
8912 
8913       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8914       // member function template declaration and class member template
8915       // declaration (MSVC versions before 2015), warn about this.
8916       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8917            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8918              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8919            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8920            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8921         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8922     }
8923 
8924     // C++11 [except.spec]p15:
8925     //   A deallocation function with no exception-specification is treated
8926     //   as if it were specified with noexcept(true).
8927     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8928     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8929          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8930         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8931       NewFD->setType(Context.getFunctionType(
8932           FPT->getReturnType(), FPT->getParamTypes(),
8933           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8934   }
8935 
8936   // Filter out previous declarations that don't match the scope.
8937   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8938                        D.getCXXScopeSpec().isNotEmpty() ||
8939                        isMemberSpecialization ||
8940                        isFunctionTemplateSpecialization);
8941 
8942   // Handle GNU asm-label extension (encoded as an attribute).
8943   if (Expr *E = (Expr*) D.getAsmLabel()) {
8944     // The parser guarantees this is a string.
8945     StringLiteral *SE = cast<StringLiteral>(E);
8946     NewFD->addAttr(::new (Context)
8947                        AsmLabelAttr(Context, SE->getStrTokenLoc(0),
8948                                     SE->getString(), /*IsLiteralLabel=*/true));
8949   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8950     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8951       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8952     if (I != ExtnameUndeclaredIdentifiers.end()) {
8953       if (isDeclExternC(NewFD)) {
8954         NewFD->addAttr(I->second);
8955         ExtnameUndeclaredIdentifiers.erase(I);
8956       } else
8957         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8958             << /*Variable*/0 << NewFD;
8959     }
8960   }
8961 
8962   // Copy the parameter declarations from the declarator D to the function
8963   // declaration NewFD, if they are available.  First scavenge them into Params.
8964   SmallVector<ParmVarDecl*, 16> Params;
8965   unsigned FTIIdx;
8966   if (D.isFunctionDeclarator(FTIIdx)) {
8967     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8968 
8969     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8970     // function that takes no arguments, not a function that takes a
8971     // single void argument.
8972     // We let through "const void" here because Sema::GetTypeForDeclarator
8973     // already checks for that case.
8974     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8975       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8976         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8977         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8978         Param->setDeclContext(NewFD);
8979         Params.push_back(Param);
8980 
8981         if (Param->isInvalidDecl())
8982           NewFD->setInvalidDecl();
8983       }
8984     }
8985 
8986     if (!getLangOpts().CPlusPlus) {
8987       // In C, find all the tag declarations from the prototype and move them
8988       // into the function DeclContext. Remove them from the surrounding tag
8989       // injection context of the function, which is typically but not always
8990       // the TU.
8991       DeclContext *PrototypeTagContext =
8992           getTagInjectionContext(NewFD->getLexicalDeclContext());
8993       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8994         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8995 
8996         // We don't want to reparent enumerators. Look at their parent enum
8997         // instead.
8998         if (!TD) {
8999           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9000             TD = cast<EnumDecl>(ECD->getDeclContext());
9001         }
9002         if (!TD)
9003           continue;
9004         DeclContext *TagDC = TD->getLexicalDeclContext();
9005         if (!TagDC->containsDecl(TD))
9006           continue;
9007         TagDC->removeDecl(TD);
9008         TD->setDeclContext(NewFD);
9009         NewFD->addDecl(TD);
9010 
9011         // Preserve the lexical DeclContext if it is not the surrounding tag
9012         // injection context of the FD. In this example, the semantic context of
9013         // E will be f and the lexical context will be S, while both the
9014         // semantic and lexical contexts of S will be f:
9015         //   void f(struct S { enum E { a } f; } s);
9016         if (TagDC != PrototypeTagContext)
9017           TD->setLexicalDeclContext(TagDC);
9018       }
9019     }
9020   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9021     // When we're declaring a function with a typedef, typeof, etc as in the
9022     // following example, we'll need to synthesize (unnamed)
9023     // parameters for use in the declaration.
9024     //
9025     // @code
9026     // typedef void fn(int);
9027     // fn f;
9028     // @endcode
9029 
9030     // Synthesize a parameter for each argument type.
9031     for (const auto &AI : FT->param_types()) {
9032       ParmVarDecl *Param =
9033           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9034       Param->setScopeInfo(0, Params.size());
9035       Params.push_back(Param);
9036     }
9037   } else {
9038     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9039            "Should not need args for typedef of non-prototype fn");
9040   }
9041 
9042   // Finally, we know we have the right number of parameters, install them.
9043   NewFD->setParams(Params);
9044 
9045   if (D.getDeclSpec().isNoreturnSpecified())
9046     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9047                                            D.getDeclSpec().getNoreturnSpecLoc(),
9048                                            AttributeCommonInfo::AS_Keyword));
9049 
9050   // Functions returning a variably modified type violate C99 6.7.5.2p2
9051   // because all functions have linkage.
9052   if (!NewFD->isInvalidDecl() &&
9053       NewFD->getReturnType()->isVariablyModifiedType()) {
9054     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9055     NewFD->setInvalidDecl();
9056   }
9057 
9058   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9059   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9060       !NewFD->hasAttr<SectionAttr>())
9061     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9062         Context, PragmaClangTextSection.SectionName,
9063         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9064 
9065   // Apply an implicit SectionAttr if #pragma code_seg is active.
9066   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9067       !NewFD->hasAttr<SectionAttr>()) {
9068     NewFD->addAttr(SectionAttr::CreateImplicit(
9069         Context, CodeSegStack.CurrentValue->getString(),
9070         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9071         SectionAttr::Declspec_allocate));
9072     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9073                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9074                          ASTContext::PSF_Read,
9075                      NewFD))
9076       NewFD->dropAttr<SectionAttr>();
9077   }
9078 
9079   // Apply an implicit CodeSegAttr from class declspec or
9080   // apply an implicit SectionAttr from #pragma code_seg if active.
9081   if (!NewFD->hasAttr<CodeSegAttr>()) {
9082     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9083                                                                  D.isFunctionDefinition())) {
9084       NewFD->addAttr(SAttr);
9085     }
9086   }
9087 
9088   // Handle attributes.
9089   ProcessDeclAttributes(S, NewFD, D);
9090 
9091   if (getLangOpts().OpenCL) {
9092     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9093     // type declaration will generate a compilation error.
9094     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9095     if (AddressSpace != LangAS::Default) {
9096       Diag(NewFD->getLocation(),
9097            diag::err_opencl_return_value_with_address_space);
9098       NewFD->setInvalidDecl();
9099     }
9100   }
9101 
9102   if (!getLangOpts().CPlusPlus) {
9103     // Perform semantic checking on the function declaration.
9104     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9105       CheckMain(NewFD, D.getDeclSpec());
9106 
9107     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9108       CheckMSVCRTEntryPoint(NewFD);
9109 
9110     if (!NewFD->isInvalidDecl())
9111       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9112                                                   isMemberSpecialization));
9113     else if (!Previous.empty())
9114       // Recover gracefully from an invalid redeclaration.
9115       D.setRedeclaration(true);
9116     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9117             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9118            "previous declaration set still overloaded");
9119 
9120     // Diagnose no-prototype function declarations with calling conventions that
9121     // don't support variadic calls. Only do this in C and do it after merging
9122     // possibly prototyped redeclarations.
9123     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9124     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9125       CallingConv CC = FT->getExtInfo().getCC();
9126       if (!supportsVariadicCall(CC)) {
9127         // Windows system headers sometimes accidentally use stdcall without
9128         // (void) parameters, so we relax this to a warning.
9129         int DiagID =
9130             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9131         Diag(NewFD->getLocation(), DiagID)
9132             << FunctionType::getNameForCallConv(CC);
9133       }
9134     }
9135 
9136    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9137        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9138      checkNonTrivialCUnion(NewFD->getReturnType(),
9139                            NewFD->getReturnTypeSourceRange().getBegin(),
9140                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9141   } else {
9142     // C++11 [replacement.functions]p3:
9143     //  The program's definitions shall not be specified as inline.
9144     //
9145     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9146     //
9147     // Suppress the diagnostic if the function is __attribute__((used)), since
9148     // that forces an external definition to be emitted.
9149     if (D.getDeclSpec().isInlineSpecified() &&
9150         NewFD->isReplaceableGlobalAllocationFunction() &&
9151         !NewFD->hasAttr<UsedAttr>())
9152       Diag(D.getDeclSpec().getInlineSpecLoc(),
9153            diag::ext_operator_new_delete_declared_inline)
9154         << NewFD->getDeclName();
9155 
9156     // If the declarator is a template-id, translate the parser's template
9157     // argument list into our AST format.
9158     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9159       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9160       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9161       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9162       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9163                                          TemplateId->NumArgs);
9164       translateTemplateArguments(TemplateArgsPtr,
9165                                  TemplateArgs);
9166 
9167       HasExplicitTemplateArgs = true;
9168 
9169       if (NewFD->isInvalidDecl()) {
9170         HasExplicitTemplateArgs = false;
9171       } else if (FunctionTemplate) {
9172         // Function template with explicit template arguments.
9173         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9174           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9175 
9176         HasExplicitTemplateArgs = false;
9177       } else {
9178         assert((isFunctionTemplateSpecialization ||
9179                 D.getDeclSpec().isFriendSpecified()) &&
9180                "should have a 'template<>' for this decl");
9181         // "friend void foo<>(int);" is an implicit specialization decl.
9182         isFunctionTemplateSpecialization = true;
9183       }
9184     } else if (isFriend && isFunctionTemplateSpecialization) {
9185       // This combination is only possible in a recovery case;  the user
9186       // wrote something like:
9187       //   template <> friend void foo(int);
9188       // which we're recovering from as if the user had written:
9189       //   friend void foo<>(int);
9190       // Go ahead and fake up a template id.
9191       HasExplicitTemplateArgs = true;
9192       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9193       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9194     }
9195 
9196     // We do not add HD attributes to specializations here because
9197     // they may have different constexpr-ness compared to their
9198     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9199     // may end up with different effective targets. Instead, a
9200     // specialization inherits its target attributes from its template
9201     // in the CheckFunctionTemplateSpecialization() call below.
9202     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9203       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9204 
9205     // If it's a friend (and only if it's a friend), it's possible
9206     // that either the specialized function type or the specialized
9207     // template is dependent, and therefore matching will fail.  In
9208     // this case, don't check the specialization yet.
9209     bool InstantiationDependent = false;
9210     if (isFunctionTemplateSpecialization && isFriend &&
9211         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9212          TemplateSpecializationType::anyDependentTemplateArguments(
9213             TemplateArgs,
9214             InstantiationDependent))) {
9215       assert(HasExplicitTemplateArgs &&
9216              "friend function specialization without template args");
9217       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9218                                                        Previous))
9219         NewFD->setInvalidDecl();
9220     } else if (isFunctionTemplateSpecialization) {
9221       if (CurContext->isDependentContext() && CurContext->isRecord()
9222           && !isFriend) {
9223         isDependentClassScopeExplicitSpecialization = true;
9224       } else if (!NewFD->isInvalidDecl() &&
9225                  CheckFunctionTemplateSpecialization(
9226                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9227                      Previous))
9228         NewFD->setInvalidDecl();
9229 
9230       // C++ [dcl.stc]p1:
9231       //   A storage-class-specifier shall not be specified in an explicit
9232       //   specialization (14.7.3)
9233       FunctionTemplateSpecializationInfo *Info =
9234           NewFD->getTemplateSpecializationInfo();
9235       if (Info && SC != SC_None) {
9236         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9237           Diag(NewFD->getLocation(),
9238                diag::err_explicit_specialization_inconsistent_storage_class)
9239             << SC
9240             << FixItHint::CreateRemoval(
9241                                       D.getDeclSpec().getStorageClassSpecLoc());
9242 
9243         else
9244           Diag(NewFD->getLocation(),
9245                diag::ext_explicit_specialization_storage_class)
9246             << FixItHint::CreateRemoval(
9247                                       D.getDeclSpec().getStorageClassSpecLoc());
9248       }
9249     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9250       if (CheckMemberSpecialization(NewFD, Previous))
9251           NewFD->setInvalidDecl();
9252     }
9253 
9254     // Perform semantic checking on the function declaration.
9255     if (!isDependentClassScopeExplicitSpecialization) {
9256       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9257         CheckMain(NewFD, D.getDeclSpec());
9258 
9259       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9260         CheckMSVCRTEntryPoint(NewFD);
9261 
9262       if (!NewFD->isInvalidDecl())
9263         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9264                                                     isMemberSpecialization));
9265       else if (!Previous.empty())
9266         // Recover gracefully from an invalid redeclaration.
9267         D.setRedeclaration(true);
9268     }
9269 
9270     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9271             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9272            "previous declaration set still overloaded");
9273 
9274     NamedDecl *PrincipalDecl = (FunctionTemplate
9275                                 ? cast<NamedDecl>(FunctionTemplate)
9276                                 : NewFD);
9277 
9278     if (isFriend && NewFD->getPreviousDecl()) {
9279       AccessSpecifier Access = AS_public;
9280       if (!NewFD->isInvalidDecl())
9281         Access = NewFD->getPreviousDecl()->getAccess();
9282 
9283       NewFD->setAccess(Access);
9284       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9285     }
9286 
9287     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9288         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9289       PrincipalDecl->setNonMemberOperator();
9290 
9291     // If we have a function template, check the template parameter
9292     // list. This will check and merge default template arguments.
9293     if (FunctionTemplate) {
9294       FunctionTemplateDecl *PrevTemplate =
9295                                      FunctionTemplate->getPreviousDecl();
9296       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9297                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9298                                     : nullptr,
9299                             D.getDeclSpec().isFriendSpecified()
9300                               ? (D.isFunctionDefinition()
9301                                    ? TPC_FriendFunctionTemplateDefinition
9302                                    : TPC_FriendFunctionTemplate)
9303                               : (D.getCXXScopeSpec().isSet() &&
9304                                  DC && DC->isRecord() &&
9305                                  DC->isDependentContext())
9306                                   ? TPC_ClassTemplateMember
9307                                   : TPC_FunctionTemplate);
9308     }
9309 
9310     if (NewFD->isInvalidDecl()) {
9311       // Ignore all the rest of this.
9312     } else if (!D.isRedeclaration()) {
9313       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9314                                        AddToScope };
9315       // Fake up an access specifier if it's supposed to be a class member.
9316       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9317         NewFD->setAccess(AS_public);
9318 
9319       // Qualified decls generally require a previous declaration.
9320       if (D.getCXXScopeSpec().isSet()) {
9321         // ...with the major exception of templated-scope or
9322         // dependent-scope friend declarations.
9323 
9324         // TODO: we currently also suppress this check in dependent
9325         // contexts because (1) the parameter depth will be off when
9326         // matching friend templates and (2) we might actually be
9327         // selecting a friend based on a dependent factor.  But there
9328         // are situations where these conditions don't apply and we
9329         // can actually do this check immediately.
9330         //
9331         // Unless the scope is dependent, it's always an error if qualified
9332         // redeclaration lookup found nothing at all. Diagnose that now;
9333         // nothing will diagnose that error later.
9334         if (isFriend &&
9335             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9336              (!Previous.empty() && CurContext->isDependentContext()))) {
9337           // ignore these
9338         } else {
9339           // The user tried to provide an out-of-line definition for a
9340           // function that is a member of a class or namespace, but there
9341           // was no such member function declared (C++ [class.mfct]p2,
9342           // C++ [namespace.memdef]p2). For example:
9343           //
9344           // class X {
9345           //   void f() const;
9346           // };
9347           //
9348           // void X::f() { } // ill-formed
9349           //
9350           // Complain about this problem, and attempt to suggest close
9351           // matches (e.g., those that differ only in cv-qualifiers and
9352           // whether the parameter types are references).
9353 
9354           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9355                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9356             AddToScope = ExtraArgs.AddToScope;
9357             return Result;
9358           }
9359         }
9360 
9361         // Unqualified local friend declarations are required to resolve
9362         // to something.
9363       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9364         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9365                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9366           AddToScope = ExtraArgs.AddToScope;
9367           return Result;
9368         }
9369       }
9370     } else if (!D.isFunctionDefinition() &&
9371                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9372                !isFriend && !isFunctionTemplateSpecialization &&
9373                !isMemberSpecialization) {
9374       // An out-of-line member function declaration must also be a
9375       // definition (C++ [class.mfct]p2).
9376       // Note that this is not the case for explicit specializations of
9377       // function templates or member functions of class templates, per
9378       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9379       // extension for compatibility with old SWIG code which likes to
9380       // generate them.
9381       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9382         << D.getCXXScopeSpec().getRange();
9383     }
9384   }
9385 
9386   ProcessPragmaWeak(S, NewFD);
9387   checkAttributesAfterMerging(*this, *NewFD);
9388 
9389   AddKnownFunctionAttributes(NewFD);
9390 
9391   if (NewFD->hasAttr<OverloadableAttr>() &&
9392       !NewFD->getType()->getAs<FunctionProtoType>()) {
9393     Diag(NewFD->getLocation(),
9394          diag::err_attribute_overloadable_no_prototype)
9395       << NewFD;
9396 
9397     // Turn this into a variadic function with no parameters.
9398     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9399     FunctionProtoType::ExtProtoInfo EPI(
9400         Context.getDefaultCallingConvention(true, false));
9401     EPI.Variadic = true;
9402     EPI.ExtInfo = FT->getExtInfo();
9403 
9404     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9405     NewFD->setType(R);
9406   }
9407 
9408   // If there's a #pragma GCC visibility in scope, and this isn't a class
9409   // member, set the visibility of this function.
9410   if (!DC->isRecord() && NewFD->isExternallyVisible())
9411     AddPushedVisibilityAttribute(NewFD);
9412 
9413   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9414   // marking the function.
9415   AddCFAuditedAttribute(NewFD);
9416 
9417   // If this is a function definition, check if we have to apply optnone due to
9418   // a pragma.
9419   if(D.isFunctionDefinition())
9420     AddRangeBasedOptnone(NewFD);
9421 
9422   // If this is the first declaration of an extern C variable, update
9423   // the map of such variables.
9424   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9425       isIncompleteDeclExternC(*this, NewFD))
9426     RegisterLocallyScopedExternCDecl(NewFD, S);
9427 
9428   // Set this FunctionDecl's range up to the right paren.
9429   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9430 
9431   if (D.isRedeclaration() && !Previous.empty()) {
9432     NamedDecl *Prev = Previous.getRepresentativeDecl();
9433     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9434                                    isMemberSpecialization ||
9435                                        isFunctionTemplateSpecialization,
9436                                    D.isFunctionDefinition());
9437   }
9438 
9439   if (getLangOpts().CUDA) {
9440     IdentifierInfo *II = NewFD->getIdentifier();
9441     if (II && II->isStr(getCudaConfigureFuncName()) &&
9442         !NewFD->isInvalidDecl() &&
9443         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9444       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9445         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9446             << getCudaConfigureFuncName();
9447       Context.setcudaConfigureCallDecl(NewFD);
9448     }
9449 
9450     // Variadic functions, other than a *declaration* of printf, are not allowed
9451     // in device-side CUDA code, unless someone passed
9452     // -fcuda-allow-variadic-functions.
9453     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9454         (NewFD->hasAttr<CUDADeviceAttr>() ||
9455          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9456         !(II && II->isStr("printf") && NewFD->isExternC() &&
9457           !D.isFunctionDefinition())) {
9458       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9459     }
9460   }
9461 
9462   MarkUnusedFileScopedDecl(NewFD);
9463 
9464 
9465 
9466   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9467     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9468     if ((getLangOpts().OpenCLVersion >= 120)
9469         && (SC == SC_Static)) {
9470       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9471       D.setInvalidType();
9472     }
9473 
9474     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9475     if (!NewFD->getReturnType()->isVoidType()) {
9476       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9477       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9478           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9479                                 : FixItHint());
9480       D.setInvalidType();
9481     }
9482 
9483     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9484     for (auto Param : NewFD->parameters())
9485       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9486 
9487     if (getLangOpts().OpenCLCPlusPlus) {
9488       if (DC->isRecord()) {
9489         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9490         D.setInvalidType();
9491       }
9492       if (FunctionTemplate) {
9493         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9494         D.setInvalidType();
9495       }
9496     }
9497   }
9498 
9499   if (getLangOpts().CPlusPlus) {
9500     if (FunctionTemplate) {
9501       if (NewFD->isInvalidDecl())
9502         FunctionTemplate->setInvalidDecl();
9503       return FunctionTemplate;
9504     }
9505 
9506     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9507       CompleteMemberSpecialization(NewFD, Previous);
9508   }
9509 
9510   for (const ParmVarDecl *Param : NewFD->parameters()) {
9511     QualType PT = Param->getType();
9512 
9513     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9514     // types.
9515     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9516       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9517         QualType ElemTy = PipeTy->getElementType();
9518           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9519             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9520             D.setInvalidType();
9521           }
9522       }
9523     }
9524   }
9525 
9526   // Here we have an function template explicit specialization at class scope.
9527   // The actual specialization will be postponed to template instatiation
9528   // time via the ClassScopeFunctionSpecializationDecl node.
9529   if (isDependentClassScopeExplicitSpecialization) {
9530     ClassScopeFunctionSpecializationDecl *NewSpec =
9531                          ClassScopeFunctionSpecializationDecl::Create(
9532                                 Context, CurContext, NewFD->getLocation(),
9533                                 cast<CXXMethodDecl>(NewFD),
9534                                 HasExplicitTemplateArgs, TemplateArgs);
9535     CurContext->addDecl(NewSpec);
9536     AddToScope = false;
9537   }
9538 
9539   // Diagnose availability attributes. Availability cannot be used on functions
9540   // that are run during load/unload.
9541   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9542     if (NewFD->hasAttr<ConstructorAttr>()) {
9543       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9544           << 1;
9545       NewFD->dropAttr<AvailabilityAttr>();
9546     }
9547     if (NewFD->hasAttr<DestructorAttr>()) {
9548       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9549           << 2;
9550       NewFD->dropAttr<AvailabilityAttr>();
9551     }
9552   }
9553 
9554   return NewFD;
9555 }
9556 
9557 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9558 /// when __declspec(code_seg) "is applied to a class, all member functions of
9559 /// the class and nested classes -- this includes compiler-generated special
9560 /// member functions -- are put in the specified segment."
9561 /// The actual behavior is a little more complicated. The Microsoft compiler
9562 /// won't check outer classes if there is an active value from #pragma code_seg.
9563 /// The CodeSeg is always applied from the direct parent but only from outer
9564 /// classes when the #pragma code_seg stack is empty. See:
9565 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9566 /// available since MS has removed the page.
9567 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9568   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9569   if (!Method)
9570     return nullptr;
9571   const CXXRecordDecl *Parent = Method->getParent();
9572   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9573     Attr *NewAttr = SAttr->clone(S.getASTContext());
9574     NewAttr->setImplicit(true);
9575     return NewAttr;
9576   }
9577 
9578   // The Microsoft compiler won't check outer classes for the CodeSeg
9579   // when the #pragma code_seg stack is active.
9580   if (S.CodeSegStack.CurrentValue)
9581    return nullptr;
9582 
9583   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9584     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9585       Attr *NewAttr = SAttr->clone(S.getASTContext());
9586       NewAttr->setImplicit(true);
9587       return NewAttr;
9588     }
9589   }
9590   return nullptr;
9591 }
9592 
9593 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9594 /// containing class. Otherwise it will return implicit SectionAttr if the
9595 /// function is a definition and there is an active value on CodeSegStack
9596 /// (from the current #pragma code-seg value).
9597 ///
9598 /// \param FD Function being declared.
9599 /// \param IsDefinition Whether it is a definition or just a declarartion.
9600 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9601 ///          nullptr if no attribute should be added.
9602 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9603                                                        bool IsDefinition) {
9604   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9605     return A;
9606   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9607       CodeSegStack.CurrentValue)
9608     return SectionAttr::CreateImplicit(
9609         getASTContext(), CodeSegStack.CurrentValue->getString(),
9610         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9611         SectionAttr::Declspec_allocate);
9612   return nullptr;
9613 }
9614 
9615 /// Determines if we can perform a correct type check for \p D as a
9616 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9617 /// best-effort check.
9618 ///
9619 /// \param NewD The new declaration.
9620 /// \param OldD The old declaration.
9621 /// \param NewT The portion of the type of the new declaration to check.
9622 /// \param OldT The portion of the type of the old declaration to check.
9623 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9624                                           QualType NewT, QualType OldT) {
9625   if (!NewD->getLexicalDeclContext()->isDependentContext())
9626     return true;
9627 
9628   // For dependently-typed local extern declarations and friends, we can't
9629   // perform a correct type check in general until instantiation:
9630   //
9631   //   int f();
9632   //   template<typename T> void g() { T f(); }
9633   //
9634   // (valid if g() is only instantiated with T = int).
9635   if (NewT->isDependentType() &&
9636       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9637     return false;
9638 
9639   // Similarly, if the previous declaration was a dependent local extern
9640   // declaration, we don't really know its type yet.
9641   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9642     return false;
9643 
9644   return true;
9645 }
9646 
9647 /// Checks if the new declaration declared in dependent context must be
9648 /// put in the same redeclaration chain as the specified declaration.
9649 ///
9650 /// \param D Declaration that is checked.
9651 /// \param PrevDecl Previous declaration found with proper lookup method for the
9652 ///                 same declaration name.
9653 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9654 ///          belongs to.
9655 ///
9656 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9657   if (!D->getLexicalDeclContext()->isDependentContext())
9658     return true;
9659 
9660   // Don't chain dependent friend function definitions until instantiation, to
9661   // permit cases like
9662   //
9663   //   void func();
9664   //   template<typename T> class C1 { friend void func() {} };
9665   //   template<typename T> class C2 { friend void func() {} };
9666   //
9667   // ... which is valid if only one of C1 and C2 is ever instantiated.
9668   //
9669   // FIXME: This need only apply to function definitions. For now, we proxy
9670   // this by checking for a file-scope function. We do not want this to apply
9671   // to friend declarations nominating member functions, because that gets in
9672   // the way of access checks.
9673   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9674     return false;
9675 
9676   auto *VD = dyn_cast<ValueDecl>(D);
9677   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9678   return !VD || !PrevVD ||
9679          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9680                                         PrevVD->getType());
9681 }
9682 
9683 /// Check the target attribute of the function for MultiVersion
9684 /// validity.
9685 ///
9686 /// Returns true if there was an error, false otherwise.
9687 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9688   const auto *TA = FD->getAttr<TargetAttr>();
9689   assert(TA && "MultiVersion Candidate requires a target attribute");
9690   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9691   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9692   enum ErrType { Feature = 0, Architecture = 1 };
9693 
9694   if (!ParseInfo.Architecture.empty() &&
9695       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9696     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9697         << Architecture << ParseInfo.Architecture;
9698     return true;
9699   }
9700 
9701   for (const auto &Feat : ParseInfo.Features) {
9702     auto BareFeat = StringRef{Feat}.substr(1);
9703     if (Feat[0] == '-') {
9704       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9705           << Feature << ("no-" + BareFeat).str();
9706       return true;
9707     }
9708 
9709     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9710         !TargetInfo.isValidFeatureName(BareFeat)) {
9711       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9712           << Feature << BareFeat;
9713       return true;
9714     }
9715   }
9716   return false;
9717 }
9718 
9719 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9720                                          MultiVersionKind MVType) {
9721   for (const Attr *A : FD->attrs()) {
9722     switch (A->getKind()) {
9723     case attr::CPUDispatch:
9724     case attr::CPUSpecific:
9725       if (MVType != MultiVersionKind::CPUDispatch &&
9726           MVType != MultiVersionKind::CPUSpecific)
9727         return true;
9728       break;
9729     case attr::Target:
9730       if (MVType != MultiVersionKind::Target)
9731         return true;
9732       break;
9733     default:
9734       return true;
9735     }
9736   }
9737   return false;
9738 }
9739 
9740 bool Sema::areMultiversionVariantFunctionsCompatible(
9741     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9742     const PartialDiagnostic &NoProtoDiagID,
9743     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9744     const PartialDiagnosticAt &NoSupportDiagIDAt,
9745     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9746     bool ConstexprSupported, bool CLinkageMayDiffer) {
9747   enum DoesntSupport {
9748     FuncTemplates = 0,
9749     VirtFuncs = 1,
9750     DeducedReturn = 2,
9751     Constructors = 3,
9752     Destructors = 4,
9753     DeletedFuncs = 5,
9754     DefaultedFuncs = 6,
9755     ConstexprFuncs = 7,
9756     ConstevalFuncs = 8,
9757   };
9758   enum Different {
9759     CallingConv = 0,
9760     ReturnType = 1,
9761     ConstexprSpec = 2,
9762     InlineSpec = 3,
9763     StorageClass = 4,
9764     Linkage = 5,
9765   };
9766 
9767   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9768     Diag(OldFD->getLocation(), NoProtoDiagID);
9769     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9770     return true;
9771   }
9772 
9773   if (!NewFD->getType()->getAs<FunctionProtoType>())
9774     return Diag(NewFD->getLocation(), NoProtoDiagID);
9775 
9776   if (!TemplatesSupported &&
9777       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9778     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9779            << FuncTemplates;
9780 
9781   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9782     if (NewCXXFD->isVirtual())
9783       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9784              << VirtFuncs;
9785 
9786     if (isa<CXXConstructorDecl>(NewCXXFD))
9787       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9788              << Constructors;
9789 
9790     if (isa<CXXDestructorDecl>(NewCXXFD))
9791       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9792              << Destructors;
9793   }
9794 
9795   if (NewFD->isDeleted())
9796     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9797            << DeletedFuncs;
9798 
9799   if (NewFD->isDefaulted())
9800     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9801            << DefaultedFuncs;
9802 
9803   if (!ConstexprSupported && NewFD->isConstexpr())
9804     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9805            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9806 
9807   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9808   const auto *NewType = cast<FunctionType>(NewQType);
9809   QualType NewReturnType = NewType->getReturnType();
9810 
9811   if (NewReturnType->isUndeducedType())
9812     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9813            << DeducedReturn;
9814 
9815   // Ensure the return type is identical.
9816   if (OldFD) {
9817     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9818     const auto *OldType = cast<FunctionType>(OldQType);
9819     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9820     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9821 
9822     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9823       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9824 
9825     QualType OldReturnType = OldType->getReturnType();
9826 
9827     if (OldReturnType != NewReturnType)
9828       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9829 
9830     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9831       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9832 
9833     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9834       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9835 
9836     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9837       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9838 
9839     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9840       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9841 
9842     if (CheckEquivalentExceptionSpec(
9843             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9844             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9845       return true;
9846   }
9847   return false;
9848 }
9849 
9850 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9851                                              const FunctionDecl *NewFD,
9852                                              bool CausesMV,
9853                                              MultiVersionKind MVType) {
9854   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9855     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9856     if (OldFD)
9857       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9858     return true;
9859   }
9860 
9861   bool IsCPUSpecificCPUDispatchMVType =
9862       MVType == MultiVersionKind::CPUDispatch ||
9863       MVType == MultiVersionKind::CPUSpecific;
9864 
9865   // For now, disallow all other attributes.  These should be opt-in, but
9866   // an analysis of all of them is a future FIXME.
9867   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9868     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9869         << IsCPUSpecificCPUDispatchMVType;
9870     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9871     return true;
9872   }
9873 
9874   if (HasNonMultiVersionAttributes(NewFD, MVType))
9875     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9876            << IsCPUSpecificCPUDispatchMVType;
9877 
9878   // Only allow transition to MultiVersion if it hasn't been used.
9879   if (OldFD && CausesMV && OldFD->isUsed(false))
9880     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9881 
9882   return S.areMultiversionVariantFunctionsCompatible(
9883       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9884       PartialDiagnosticAt(NewFD->getLocation(),
9885                           S.PDiag(diag::note_multiversioning_caused_here)),
9886       PartialDiagnosticAt(NewFD->getLocation(),
9887                           S.PDiag(diag::err_multiversion_doesnt_support)
9888                               << IsCPUSpecificCPUDispatchMVType),
9889       PartialDiagnosticAt(NewFD->getLocation(),
9890                           S.PDiag(diag::err_multiversion_diff)),
9891       /*TemplatesSupported=*/false,
9892       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
9893       /*CLinkageMayDiffer=*/false);
9894 }
9895 
9896 /// Check the validity of a multiversion function declaration that is the
9897 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9898 ///
9899 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9900 ///
9901 /// Returns true if there was an error, false otherwise.
9902 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9903                                            MultiVersionKind MVType,
9904                                            const TargetAttr *TA) {
9905   assert(MVType != MultiVersionKind::None &&
9906          "Function lacks multiversion attribute");
9907 
9908   // Target only causes MV if it is default, otherwise this is a normal
9909   // function.
9910   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9911     return false;
9912 
9913   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9914     FD->setInvalidDecl();
9915     return true;
9916   }
9917 
9918   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9919     FD->setInvalidDecl();
9920     return true;
9921   }
9922 
9923   FD->setIsMultiVersion();
9924   return false;
9925 }
9926 
9927 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9928   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9929     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9930       return true;
9931   }
9932 
9933   return false;
9934 }
9935 
9936 static bool CheckTargetCausesMultiVersioning(
9937     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9938     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9939     LookupResult &Previous) {
9940   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9941   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9942   // Sort order doesn't matter, it just needs to be consistent.
9943   llvm::sort(NewParsed.Features);
9944 
9945   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9946   // to change, this is a simple redeclaration.
9947   if (!NewTA->isDefaultVersion() &&
9948       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9949     return false;
9950 
9951   // Otherwise, this decl causes MultiVersioning.
9952   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9953     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9954     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9955     NewFD->setInvalidDecl();
9956     return true;
9957   }
9958 
9959   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9960                                        MultiVersionKind::Target)) {
9961     NewFD->setInvalidDecl();
9962     return true;
9963   }
9964 
9965   if (CheckMultiVersionValue(S, NewFD)) {
9966     NewFD->setInvalidDecl();
9967     return true;
9968   }
9969 
9970   // If this is 'default', permit the forward declaration.
9971   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9972     Redeclaration = true;
9973     OldDecl = OldFD;
9974     OldFD->setIsMultiVersion();
9975     NewFD->setIsMultiVersion();
9976     return false;
9977   }
9978 
9979   if (CheckMultiVersionValue(S, OldFD)) {
9980     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9981     NewFD->setInvalidDecl();
9982     return true;
9983   }
9984 
9985   TargetAttr::ParsedTargetAttr OldParsed =
9986       OldTA->parse(std::less<std::string>());
9987 
9988   if (OldParsed == NewParsed) {
9989     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9990     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9991     NewFD->setInvalidDecl();
9992     return true;
9993   }
9994 
9995   for (const auto *FD : OldFD->redecls()) {
9996     const auto *CurTA = FD->getAttr<TargetAttr>();
9997     // We allow forward declarations before ANY multiversioning attributes, but
9998     // nothing after the fact.
9999     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10000         (!CurTA || CurTA->isInherited())) {
10001       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10002           << 0;
10003       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10004       NewFD->setInvalidDecl();
10005       return true;
10006     }
10007   }
10008 
10009   OldFD->setIsMultiVersion();
10010   NewFD->setIsMultiVersion();
10011   Redeclaration = false;
10012   MergeTypeWithPrevious = false;
10013   OldDecl = nullptr;
10014   Previous.clear();
10015   return false;
10016 }
10017 
10018 /// Check the validity of a new function declaration being added to an existing
10019 /// multiversioned declaration collection.
10020 static bool CheckMultiVersionAdditionalDecl(
10021     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10022     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10023     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10024     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10025     LookupResult &Previous) {
10026 
10027   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10028   // Disallow mixing of multiversioning types.
10029   if ((OldMVType == MultiVersionKind::Target &&
10030        NewMVType != MultiVersionKind::Target) ||
10031       (NewMVType == MultiVersionKind::Target &&
10032        OldMVType != MultiVersionKind::Target)) {
10033     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10034     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10035     NewFD->setInvalidDecl();
10036     return true;
10037   }
10038 
10039   TargetAttr::ParsedTargetAttr NewParsed;
10040   if (NewTA) {
10041     NewParsed = NewTA->parse();
10042     llvm::sort(NewParsed.Features);
10043   }
10044 
10045   bool UseMemberUsingDeclRules =
10046       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10047 
10048   // Next, check ALL non-overloads to see if this is a redeclaration of a
10049   // previous member of the MultiVersion set.
10050   for (NamedDecl *ND : Previous) {
10051     FunctionDecl *CurFD = ND->getAsFunction();
10052     if (!CurFD)
10053       continue;
10054     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10055       continue;
10056 
10057     if (NewMVType == MultiVersionKind::Target) {
10058       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10059       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10060         NewFD->setIsMultiVersion();
10061         Redeclaration = true;
10062         OldDecl = ND;
10063         return false;
10064       }
10065 
10066       TargetAttr::ParsedTargetAttr CurParsed =
10067           CurTA->parse(std::less<std::string>());
10068       if (CurParsed == NewParsed) {
10069         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10070         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10071         NewFD->setInvalidDecl();
10072         return true;
10073       }
10074     } else {
10075       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10076       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10077       // Handle CPUDispatch/CPUSpecific versions.
10078       // Only 1 CPUDispatch function is allowed, this will make it go through
10079       // the redeclaration errors.
10080       if (NewMVType == MultiVersionKind::CPUDispatch &&
10081           CurFD->hasAttr<CPUDispatchAttr>()) {
10082         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10083             std::equal(
10084                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10085                 NewCPUDisp->cpus_begin(),
10086                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10087                   return Cur->getName() == New->getName();
10088                 })) {
10089           NewFD->setIsMultiVersion();
10090           Redeclaration = true;
10091           OldDecl = ND;
10092           return false;
10093         }
10094 
10095         // If the declarations don't match, this is an error condition.
10096         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10097         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10098         NewFD->setInvalidDecl();
10099         return true;
10100       }
10101       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10102 
10103         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10104             std::equal(
10105                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10106                 NewCPUSpec->cpus_begin(),
10107                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10108                   return Cur->getName() == New->getName();
10109                 })) {
10110           NewFD->setIsMultiVersion();
10111           Redeclaration = true;
10112           OldDecl = ND;
10113           return false;
10114         }
10115 
10116         // Only 1 version of CPUSpecific is allowed for each CPU.
10117         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10118           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10119             if (CurII == NewII) {
10120               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10121                   << NewII;
10122               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10123               NewFD->setInvalidDecl();
10124               return true;
10125             }
10126           }
10127         }
10128       }
10129       // If the two decls aren't the same MVType, there is no possible error
10130       // condition.
10131     }
10132   }
10133 
10134   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10135   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10136   // handled in the attribute adding step.
10137   if (NewMVType == MultiVersionKind::Target &&
10138       CheckMultiVersionValue(S, NewFD)) {
10139     NewFD->setInvalidDecl();
10140     return true;
10141   }
10142 
10143   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10144                                        !OldFD->isMultiVersion(), NewMVType)) {
10145     NewFD->setInvalidDecl();
10146     return true;
10147   }
10148 
10149   // Permit forward declarations in the case where these two are compatible.
10150   if (!OldFD->isMultiVersion()) {
10151     OldFD->setIsMultiVersion();
10152     NewFD->setIsMultiVersion();
10153     Redeclaration = true;
10154     OldDecl = OldFD;
10155     return false;
10156   }
10157 
10158   NewFD->setIsMultiVersion();
10159   Redeclaration = false;
10160   MergeTypeWithPrevious = false;
10161   OldDecl = nullptr;
10162   Previous.clear();
10163   return false;
10164 }
10165 
10166 
10167 /// Check the validity of a mulitversion function declaration.
10168 /// Also sets the multiversion'ness' of the function itself.
10169 ///
10170 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10171 ///
10172 /// Returns true if there was an error, false otherwise.
10173 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10174                                       bool &Redeclaration, NamedDecl *&OldDecl,
10175                                       bool &MergeTypeWithPrevious,
10176                                       LookupResult &Previous) {
10177   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10178   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10179   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10180 
10181   // Mixing Multiversioning types is prohibited.
10182   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10183       (NewCPUDisp && NewCPUSpec)) {
10184     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10185     NewFD->setInvalidDecl();
10186     return true;
10187   }
10188 
10189   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10190 
10191   // Main isn't allowed to become a multiversion function, however it IS
10192   // permitted to have 'main' be marked with the 'target' optimization hint.
10193   if (NewFD->isMain()) {
10194     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10195         MVType == MultiVersionKind::CPUDispatch ||
10196         MVType == MultiVersionKind::CPUSpecific) {
10197       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10198       NewFD->setInvalidDecl();
10199       return true;
10200     }
10201     return false;
10202   }
10203 
10204   if (!OldDecl || !OldDecl->getAsFunction() ||
10205       OldDecl->getDeclContext()->getRedeclContext() !=
10206           NewFD->getDeclContext()->getRedeclContext()) {
10207     // If there's no previous declaration, AND this isn't attempting to cause
10208     // multiversioning, this isn't an error condition.
10209     if (MVType == MultiVersionKind::None)
10210       return false;
10211     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10212   }
10213 
10214   FunctionDecl *OldFD = OldDecl->getAsFunction();
10215 
10216   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10217     return false;
10218 
10219   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10220     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10221         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10222     NewFD->setInvalidDecl();
10223     return true;
10224   }
10225 
10226   // Handle the target potentially causes multiversioning case.
10227   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10228     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10229                                             Redeclaration, OldDecl,
10230                                             MergeTypeWithPrevious, Previous);
10231 
10232   // At this point, we have a multiversion function decl (in OldFD) AND an
10233   // appropriate attribute in the current function decl.  Resolve that these are
10234   // still compatible with previous declarations.
10235   return CheckMultiVersionAdditionalDecl(
10236       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10237       OldDecl, MergeTypeWithPrevious, Previous);
10238 }
10239 
10240 /// Perform semantic checking of a new function declaration.
10241 ///
10242 /// Performs semantic analysis of the new function declaration
10243 /// NewFD. This routine performs all semantic checking that does not
10244 /// require the actual declarator involved in the declaration, and is
10245 /// used both for the declaration of functions as they are parsed
10246 /// (called via ActOnDeclarator) and for the declaration of functions
10247 /// that have been instantiated via C++ template instantiation (called
10248 /// via InstantiateDecl).
10249 ///
10250 /// \param IsMemberSpecialization whether this new function declaration is
10251 /// a member specialization (that replaces any definition provided by the
10252 /// previous declaration).
10253 ///
10254 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10255 ///
10256 /// \returns true if the function declaration is a redeclaration.
10257 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10258                                     LookupResult &Previous,
10259                                     bool IsMemberSpecialization) {
10260   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10261          "Variably modified return types are not handled here");
10262 
10263   // Determine whether the type of this function should be merged with
10264   // a previous visible declaration. This never happens for functions in C++,
10265   // and always happens in C if the previous declaration was visible.
10266   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10267                                !Previous.isShadowed();
10268 
10269   bool Redeclaration = false;
10270   NamedDecl *OldDecl = nullptr;
10271   bool MayNeedOverloadableChecks = false;
10272 
10273   // Merge or overload the declaration with an existing declaration of
10274   // the same name, if appropriate.
10275   if (!Previous.empty()) {
10276     // Determine whether NewFD is an overload of PrevDecl or
10277     // a declaration that requires merging. If it's an overload,
10278     // there's no more work to do here; we'll just add the new
10279     // function to the scope.
10280     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10281       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10282       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10283         Redeclaration = true;
10284         OldDecl = Candidate;
10285       }
10286     } else {
10287       MayNeedOverloadableChecks = true;
10288       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10289                             /*NewIsUsingDecl*/ false)) {
10290       case Ovl_Match:
10291         Redeclaration = true;
10292         break;
10293 
10294       case Ovl_NonFunction:
10295         Redeclaration = true;
10296         break;
10297 
10298       case Ovl_Overload:
10299         Redeclaration = false;
10300         break;
10301       }
10302     }
10303   }
10304 
10305   // Check for a previous extern "C" declaration with this name.
10306   if (!Redeclaration &&
10307       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10308     if (!Previous.empty()) {
10309       // This is an extern "C" declaration with the same name as a previous
10310       // declaration, and thus redeclares that entity...
10311       Redeclaration = true;
10312       OldDecl = Previous.getFoundDecl();
10313       MergeTypeWithPrevious = false;
10314 
10315       // ... except in the presence of __attribute__((overloadable)).
10316       if (OldDecl->hasAttr<OverloadableAttr>() ||
10317           NewFD->hasAttr<OverloadableAttr>()) {
10318         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10319           MayNeedOverloadableChecks = true;
10320           Redeclaration = false;
10321           OldDecl = nullptr;
10322         }
10323       }
10324     }
10325   }
10326 
10327   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10328                                 MergeTypeWithPrevious, Previous))
10329     return Redeclaration;
10330 
10331   // C++11 [dcl.constexpr]p8:
10332   //   A constexpr specifier for a non-static member function that is not
10333   //   a constructor declares that member function to be const.
10334   //
10335   // This needs to be delayed until we know whether this is an out-of-line
10336   // definition of a static member function.
10337   //
10338   // This rule is not present in C++1y, so we produce a backwards
10339   // compatibility warning whenever it happens in C++11.
10340   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10341   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10342       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10343       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10344     CXXMethodDecl *OldMD = nullptr;
10345     if (OldDecl)
10346       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10347     if (!OldMD || !OldMD->isStatic()) {
10348       const FunctionProtoType *FPT =
10349         MD->getType()->castAs<FunctionProtoType>();
10350       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10351       EPI.TypeQuals.addConst();
10352       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10353                                           FPT->getParamTypes(), EPI));
10354 
10355       // Warn that we did this, if we're not performing template instantiation.
10356       // In that case, we'll have warned already when the template was defined.
10357       if (!inTemplateInstantiation()) {
10358         SourceLocation AddConstLoc;
10359         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10360                 .IgnoreParens().getAs<FunctionTypeLoc>())
10361           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10362 
10363         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10364           << FixItHint::CreateInsertion(AddConstLoc, " const");
10365       }
10366     }
10367   }
10368 
10369   if (Redeclaration) {
10370     // NewFD and OldDecl represent declarations that need to be
10371     // merged.
10372     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10373       NewFD->setInvalidDecl();
10374       return Redeclaration;
10375     }
10376 
10377     Previous.clear();
10378     Previous.addDecl(OldDecl);
10379 
10380     if (FunctionTemplateDecl *OldTemplateDecl =
10381             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10382       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10383       FunctionTemplateDecl *NewTemplateDecl
10384         = NewFD->getDescribedFunctionTemplate();
10385       assert(NewTemplateDecl && "Template/non-template mismatch");
10386 
10387       // The call to MergeFunctionDecl above may have created some state in
10388       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10389       // can add it as a redeclaration.
10390       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10391 
10392       NewFD->setPreviousDeclaration(OldFD);
10393       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10394       if (NewFD->isCXXClassMember()) {
10395         NewFD->setAccess(OldTemplateDecl->getAccess());
10396         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10397       }
10398 
10399       // If this is an explicit specialization of a member that is a function
10400       // template, mark it as a member specialization.
10401       if (IsMemberSpecialization &&
10402           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10403         NewTemplateDecl->setMemberSpecialization();
10404         assert(OldTemplateDecl->isMemberSpecialization());
10405         // Explicit specializations of a member template do not inherit deleted
10406         // status from the parent member template that they are specializing.
10407         if (OldFD->isDeleted()) {
10408           // FIXME: This assert will not hold in the presence of modules.
10409           assert(OldFD->getCanonicalDecl() == OldFD);
10410           // FIXME: We need an update record for this AST mutation.
10411           OldFD->setDeletedAsWritten(false);
10412         }
10413       }
10414 
10415     } else {
10416       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10417         auto *OldFD = cast<FunctionDecl>(OldDecl);
10418         // This needs to happen first so that 'inline' propagates.
10419         NewFD->setPreviousDeclaration(OldFD);
10420         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10421         if (NewFD->isCXXClassMember())
10422           NewFD->setAccess(OldFD->getAccess());
10423       }
10424     }
10425   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10426              !NewFD->getAttr<OverloadableAttr>()) {
10427     assert((Previous.empty() ||
10428             llvm::any_of(Previous,
10429                          [](const NamedDecl *ND) {
10430                            return ND->hasAttr<OverloadableAttr>();
10431                          })) &&
10432            "Non-redecls shouldn't happen without overloadable present");
10433 
10434     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10435       const auto *FD = dyn_cast<FunctionDecl>(ND);
10436       return FD && !FD->hasAttr<OverloadableAttr>();
10437     });
10438 
10439     if (OtherUnmarkedIter != Previous.end()) {
10440       Diag(NewFD->getLocation(),
10441            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10442       Diag((*OtherUnmarkedIter)->getLocation(),
10443            diag::note_attribute_overloadable_prev_overload)
10444           << false;
10445 
10446       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10447     }
10448   }
10449 
10450   // Semantic checking for this function declaration (in isolation).
10451 
10452   if (getLangOpts().CPlusPlus) {
10453     // C++-specific checks.
10454     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10455       CheckConstructor(Constructor);
10456     } else if (CXXDestructorDecl *Destructor =
10457                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10458       CXXRecordDecl *Record = Destructor->getParent();
10459       QualType ClassType = Context.getTypeDeclType(Record);
10460 
10461       // FIXME: Shouldn't we be able to perform this check even when the class
10462       // type is dependent? Both gcc and edg can handle that.
10463       if (!ClassType->isDependentType()) {
10464         DeclarationName Name
10465           = Context.DeclarationNames.getCXXDestructorName(
10466                                         Context.getCanonicalType(ClassType));
10467         if (NewFD->getDeclName() != Name) {
10468           Diag(NewFD->getLocation(), diag::err_destructor_name);
10469           NewFD->setInvalidDecl();
10470           return Redeclaration;
10471         }
10472       }
10473     } else if (CXXConversionDecl *Conversion
10474                = dyn_cast<CXXConversionDecl>(NewFD)) {
10475       ActOnConversionDeclarator(Conversion);
10476     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10477       if (auto *TD = Guide->getDescribedFunctionTemplate())
10478         CheckDeductionGuideTemplate(TD);
10479 
10480       // A deduction guide is not on the list of entities that can be
10481       // explicitly specialized.
10482       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10483         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10484             << /*explicit specialization*/ 1;
10485     }
10486 
10487     // Find any virtual functions that this function overrides.
10488     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10489       if (!Method->isFunctionTemplateSpecialization() &&
10490           !Method->getDescribedFunctionTemplate() &&
10491           Method->isCanonicalDecl()) {
10492         if (AddOverriddenMethods(Method->getParent(), Method)) {
10493           // If the function was marked as "static", we have a problem.
10494           if (NewFD->getStorageClass() == SC_Static) {
10495             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10496           }
10497         }
10498       }
10499 
10500       if (Method->isStatic())
10501         checkThisInStaticMemberFunctionType(Method);
10502     }
10503 
10504     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10505     if (NewFD->isOverloadedOperator() &&
10506         CheckOverloadedOperatorDeclaration(NewFD)) {
10507       NewFD->setInvalidDecl();
10508       return Redeclaration;
10509     }
10510 
10511     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10512     if (NewFD->getLiteralIdentifier() &&
10513         CheckLiteralOperatorDeclaration(NewFD)) {
10514       NewFD->setInvalidDecl();
10515       return Redeclaration;
10516     }
10517 
10518     // In C++, check default arguments now that we have merged decls. Unless
10519     // the lexical context is the class, because in this case this is done
10520     // during delayed parsing anyway.
10521     if (!CurContext->isRecord())
10522       CheckCXXDefaultArguments(NewFD);
10523 
10524     // If this function declares a builtin function, check the type of this
10525     // declaration against the expected type for the builtin.
10526     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10527       ASTContext::GetBuiltinTypeError Error;
10528       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10529       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10530       // If the type of the builtin differs only in its exception
10531       // specification, that's OK.
10532       // FIXME: If the types do differ in this way, it would be better to
10533       // retain the 'noexcept' form of the type.
10534       if (!T.isNull() &&
10535           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10536                                                             NewFD->getType()))
10537         // The type of this function differs from the type of the builtin,
10538         // so forget about the builtin entirely.
10539         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10540     }
10541 
10542     // If this function is declared as being extern "C", then check to see if
10543     // the function returns a UDT (class, struct, or union type) that is not C
10544     // compatible, and if it does, warn the user.
10545     // But, issue any diagnostic on the first declaration only.
10546     if (Previous.empty() && NewFD->isExternC()) {
10547       QualType R = NewFD->getReturnType();
10548       if (R->isIncompleteType() && !R->isVoidType())
10549         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10550             << NewFD << R;
10551       else if (!R.isPODType(Context) && !R->isVoidType() &&
10552                !R->isObjCObjectPointerType())
10553         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10554     }
10555 
10556     // C++1z [dcl.fct]p6:
10557     //   [...] whether the function has a non-throwing exception-specification
10558     //   [is] part of the function type
10559     //
10560     // This results in an ABI break between C++14 and C++17 for functions whose
10561     // declared type includes an exception-specification in a parameter or
10562     // return type. (Exception specifications on the function itself are OK in
10563     // most cases, and exception specifications are not permitted in most other
10564     // contexts where they could make it into a mangling.)
10565     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10566       auto HasNoexcept = [&](QualType T) -> bool {
10567         // Strip off declarator chunks that could be between us and a function
10568         // type. We don't need to look far, exception specifications are very
10569         // restricted prior to C++17.
10570         if (auto *RT = T->getAs<ReferenceType>())
10571           T = RT->getPointeeType();
10572         else if (T->isAnyPointerType())
10573           T = T->getPointeeType();
10574         else if (auto *MPT = T->getAs<MemberPointerType>())
10575           T = MPT->getPointeeType();
10576         if (auto *FPT = T->getAs<FunctionProtoType>())
10577           if (FPT->isNothrow())
10578             return true;
10579         return false;
10580       };
10581 
10582       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10583       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10584       for (QualType T : FPT->param_types())
10585         AnyNoexcept |= HasNoexcept(T);
10586       if (AnyNoexcept)
10587         Diag(NewFD->getLocation(),
10588              diag::warn_cxx17_compat_exception_spec_in_signature)
10589             << NewFD;
10590     }
10591 
10592     if (!Redeclaration && LangOpts.CUDA)
10593       checkCUDATargetOverload(NewFD, Previous);
10594   }
10595   return Redeclaration;
10596 }
10597 
10598 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10599   // C++11 [basic.start.main]p3:
10600   //   A program that [...] declares main to be inline, static or
10601   //   constexpr is ill-formed.
10602   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10603   //   appear in a declaration of main.
10604   // static main is not an error under C99, but we should warn about it.
10605   // We accept _Noreturn main as an extension.
10606   if (FD->getStorageClass() == SC_Static)
10607     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10608          ? diag::err_static_main : diag::warn_static_main)
10609       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10610   if (FD->isInlineSpecified())
10611     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10612       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10613   if (DS.isNoreturnSpecified()) {
10614     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10615     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10616     Diag(NoreturnLoc, diag::ext_noreturn_main);
10617     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10618       << FixItHint::CreateRemoval(NoreturnRange);
10619   }
10620   if (FD->isConstexpr()) {
10621     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10622         << FD->isConsteval()
10623         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10624     FD->setConstexprKind(CSK_unspecified);
10625   }
10626 
10627   if (getLangOpts().OpenCL) {
10628     Diag(FD->getLocation(), diag::err_opencl_no_main)
10629         << FD->hasAttr<OpenCLKernelAttr>();
10630     FD->setInvalidDecl();
10631     return;
10632   }
10633 
10634   QualType T = FD->getType();
10635   assert(T->isFunctionType() && "function decl is not of function type");
10636   const FunctionType* FT = T->castAs<FunctionType>();
10637 
10638   // Set default calling convention for main()
10639   if (FT->getCallConv() != CC_C) {
10640     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10641     FD->setType(QualType(FT, 0));
10642     T = Context.getCanonicalType(FD->getType());
10643   }
10644 
10645   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10646     // In C with GNU extensions we allow main() to have non-integer return
10647     // type, but we should warn about the extension, and we disable the
10648     // implicit-return-zero rule.
10649 
10650     // GCC in C mode accepts qualified 'int'.
10651     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10652       FD->setHasImplicitReturnZero(true);
10653     else {
10654       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10655       SourceRange RTRange = FD->getReturnTypeSourceRange();
10656       if (RTRange.isValid())
10657         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10658             << FixItHint::CreateReplacement(RTRange, "int");
10659     }
10660   } else {
10661     // In C and C++, main magically returns 0 if you fall off the end;
10662     // set the flag which tells us that.
10663     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10664 
10665     // All the standards say that main() should return 'int'.
10666     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10667       FD->setHasImplicitReturnZero(true);
10668     else {
10669       // Otherwise, this is just a flat-out error.
10670       SourceRange RTRange = FD->getReturnTypeSourceRange();
10671       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10672           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10673                                 : FixItHint());
10674       FD->setInvalidDecl(true);
10675     }
10676   }
10677 
10678   // Treat protoless main() as nullary.
10679   if (isa<FunctionNoProtoType>(FT)) return;
10680 
10681   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10682   unsigned nparams = FTP->getNumParams();
10683   assert(FD->getNumParams() == nparams);
10684 
10685   bool HasExtraParameters = (nparams > 3);
10686 
10687   if (FTP->isVariadic()) {
10688     Diag(FD->getLocation(), diag::ext_variadic_main);
10689     // FIXME: if we had information about the location of the ellipsis, we
10690     // could add a FixIt hint to remove it as a parameter.
10691   }
10692 
10693   // Darwin passes an undocumented fourth argument of type char**.  If
10694   // other platforms start sprouting these, the logic below will start
10695   // getting shifty.
10696   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10697     HasExtraParameters = false;
10698 
10699   if (HasExtraParameters) {
10700     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10701     FD->setInvalidDecl(true);
10702     nparams = 3;
10703   }
10704 
10705   // FIXME: a lot of the following diagnostics would be improved
10706   // if we had some location information about types.
10707 
10708   QualType CharPP =
10709     Context.getPointerType(Context.getPointerType(Context.CharTy));
10710   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10711 
10712   for (unsigned i = 0; i < nparams; ++i) {
10713     QualType AT = FTP->getParamType(i);
10714 
10715     bool mismatch = true;
10716 
10717     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10718       mismatch = false;
10719     else if (Expected[i] == CharPP) {
10720       // As an extension, the following forms are okay:
10721       //   char const **
10722       //   char const * const *
10723       //   char * const *
10724 
10725       QualifierCollector qs;
10726       const PointerType* PT;
10727       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10728           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10729           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10730                               Context.CharTy)) {
10731         qs.removeConst();
10732         mismatch = !qs.empty();
10733       }
10734     }
10735 
10736     if (mismatch) {
10737       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10738       // TODO: suggest replacing given type with expected type
10739       FD->setInvalidDecl(true);
10740     }
10741   }
10742 
10743   if (nparams == 1 && !FD->isInvalidDecl()) {
10744     Diag(FD->getLocation(), diag::warn_main_one_arg);
10745   }
10746 
10747   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10748     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10749     FD->setInvalidDecl();
10750   }
10751 }
10752 
10753 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10754   QualType T = FD->getType();
10755   assert(T->isFunctionType() && "function decl is not of function type");
10756   const FunctionType *FT = T->castAs<FunctionType>();
10757 
10758   // Set an implicit return of 'zero' if the function can return some integral,
10759   // enumeration, pointer or nullptr type.
10760   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10761       FT->getReturnType()->isAnyPointerType() ||
10762       FT->getReturnType()->isNullPtrType())
10763     // DllMain is exempt because a return value of zero means it failed.
10764     if (FD->getName() != "DllMain")
10765       FD->setHasImplicitReturnZero(true);
10766 
10767   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10768     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10769     FD->setInvalidDecl();
10770   }
10771 }
10772 
10773 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10774   // FIXME: Need strict checking.  In C89, we need to check for
10775   // any assignment, increment, decrement, function-calls, or
10776   // commas outside of a sizeof.  In C99, it's the same list,
10777   // except that the aforementioned are allowed in unevaluated
10778   // expressions.  Everything else falls under the
10779   // "may accept other forms of constant expressions" exception.
10780   // (We never end up here for C++, so the constant expression
10781   // rules there don't matter.)
10782   const Expr *Culprit;
10783   if (Init->isConstantInitializer(Context, false, &Culprit))
10784     return false;
10785   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10786     << Culprit->getSourceRange();
10787   return true;
10788 }
10789 
10790 namespace {
10791   // Visits an initialization expression to see if OrigDecl is evaluated in
10792   // its own initialization and throws a warning if it does.
10793   class SelfReferenceChecker
10794       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10795     Sema &S;
10796     Decl *OrigDecl;
10797     bool isRecordType;
10798     bool isPODType;
10799     bool isReferenceType;
10800 
10801     bool isInitList;
10802     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10803 
10804   public:
10805     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10806 
10807     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10808                                                     S(S), OrigDecl(OrigDecl) {
10809       isPODType = false;
10810       isRecordType = false;
10811       isReferenceType = false;
10812       isInitList = false;
10813       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10814         isPODType = VD->getType().isPODType(S.Context);
10815         isRecordType = VD->getType()->isRecordType();
10816         isReferenceType = VD->getType()->isReferenceType();
10817       }
10818     }
10819 
10820     // For most expressions, just call the visitor.  For initializer lists,
10821     // track the index of the field being initialized since fields are
10822     // initialized in order allowing use of previously initialized fields.
10823     void CheckExpr(Expr *E) {
10824       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10825       if (!InitList) {
10826         Visit(E);
10827         return;
10828       }
10829 
10830       // Track and increment the index here.
10831       isInitList = true;
10832       InitFieldIndex.push_back(0);
10833       for (auto Child : InitList->children()) {
10834         CheckExpr(cast<Expr>(Child));
10835         ++InitFieldIndex.back();
10836       }
10837       InitFieldIndex.pop_back();
10838     }
10839 
10840     // Returns true if MemberExpr is checked and no further checking is needed.
10841     // Returns false if additional checking is required.
10842     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10843       llvm::SmallVector<FieldDecl*, 4> Fields;
10844       Expr *Base = E;
10845       bool ReferenceField = false;
10846 
10847       // Get the field members used.
10848       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10849         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10850         if (!FD)
10851           return false;
10852         Fields.push_back(FD);
10853         if (FD->getType()->isReferenceType())
10854           ReferenceField = true;
10855         Base = ME->getBase()->IgnoreParenImpCasts();
10856       }
10857 
10858       // Keep checking only if the base Decl is the same.
10859       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10860       if (!DRE || DRE->getDecl() != OrigDecl)
10861         return false;
10862 
10863       // A reference field can be bound to an unininitialized field.
10864       if (CheckReference && !ReferenceField)
10865         return true;
10866 
10867       // Convert FieldDecls to their index number.
10868       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10869       for (const FieldDecl *I : llvm::reverse(Fields))
10870         UsedFieldIndex.push_back(I->getFieldIndex());
10871 
10872       // See if a warning is needed by checking the first difference in index
10873       // numbers.  If field being used has index less than the field being
10874       // initialized, then the use is safe.
10875       for (auto UsedIter = UsedFieldIndex.begin(),
10876                 UsedEnd = UsedFieldIndex.end(),
10877                 OrigIter = InitFieldIndex.begin(),
10878                 OrigEnd = InitFieldIndex.end();
10879            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10880         if (*UsedIter < *OrigIter)
10881           return true;
10882         if (*UsedIter > *OrigIter)
10883           break;
10884       }
10885 
10886       // TODO: Add a different warning which will print the field names.
10887       HandleDeclRefExpr(DRE);
10888       return true;
10889     }
10890 
10891     // For most expressions, the cast is directly above the DeclRefExpr.
10892     // For conditional operators, the cast can be outside the conditional
10893     // operator if both expressions are DeclRefExpr's.
10894     void HandleValue(Expr *E) {
10895       E = E->IgnoreParens();
10896       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10897         HandleDeclRefExpr(DRE);
10898         return;
10899       }
10900 
10901       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10902         Visit(CO->getCond());
10903         HandleValue(CO->getTrueExpr());
10904         HandleValue(CO->getFalseExpr());
10905         return;
10906       }
10907 
10908       if (BinaryConditionalOperator *BCO =
10909               dyn_cast<BinaryConditionalOperator>(E)) {
10910         Visit(BCO->getCond());
10911         HandleValue(BCO->getFalseExpr());
10912         return;
10913       }
10914 
10915       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10916         HandleValue(OVE->getSourceExpr());
10917         return;
10918       }
10919 
10920       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10921         if (BO->getOpcode() == BO_Comma) {
10922           Visit(BO->getLHS());
10923           HandleValue(BO->getRHS());
10924           return;
10925         }
10926       }
10927 
10928       if (isa<MemberExpr>(E)) {
10929         if (isInitList) {
10930           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10931                                       false /*CheckReference*/))
10932             return;
10933         }
10934 
10935         Expr *Base = E->IgnoreParenImpCasts();
10936         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10937           // Check for static member variables and don't warn on them.
10938           if (!isa<FieldDecl>(ME->getMemberDecl()))
10939             return;
10940           Base = ME->getBase()->IgnoreParenImpCasts();
10941         }
10942         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10943           HandleDeclRefExpr(DRE);
10944         return;
10945       }
10946 
10947       Visit(E);
10948     }
10949 
10950     // Reference types not handled in HandleValue are handled here since all
10951     // uses of references are bad, not just r-value uses.
10952     void VisitDeclRefExpr(DeclRefExpr *E) {
10953       if (isReferenceType)
10954         HandleDeclRefExpr(E);
10955     }
10956 
10957     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10958       if (E->getCastKind() == CK_LValueToRValue) {
10959         HandleValue(E->getSubExpr());
10960         return;
10961       }
10962 
10963       Inherited::VisitImplicitCastExpr(E);
10964     }
10965 
10966     void VisitMemberExpr(MemberExpr *E) {
10967       if (isInitList) {
10968         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10969           return;
10970       }
10971 
10972       // Don't warn on arrays since they can be treated as pointers.
10973       if (E->getType()->canDecayToPointerType()) return;
10974 
10975       // Warn when a non-static method call is followed by non-static member
10976       // field accesses, which is followed by a DeclRefExpr.
10977       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10978       bool Warn = (MD && !MD->isStatic());
10979       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10980       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10981         if (!isa<FieldDecl>(ME->getMemberDecl()))
10982           Warn = false;
10983         Base = ME->getBase()->IgnoreParenImpCasts();
10984       }
10985 
10986       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10987         if (Warn)
10988           HandleDeclRefExpr(DRE);
10989         return;
10990       }
10991 
10992       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10993       // Visit that expression.
10994       Visit(Base);
10995     }
10996 
10997     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10998       Expr *Callee = E->getCallee();
10999 
11000       if (isa<UnresolvedLookupExpr>(Callee))
11001         return Inherited::VisitCXXOperatorCallExpr(E);
11002 
11003       Visit(Callee);
11004       for (auto Arg: E->arguments())
11005         HandleValue(Arg->IgnoreParenImpCasts());
11006     }
11007 
11008     void VisitUnaryOperator(UnaryOperator *E) {
11009       // For POD record types, addresses of its own members are well-defined.
11010       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11011           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11012         if (!isPODType)
11013           HandleValue(E->getSubExpr());
11014         return;
11015       }
11016 
11017       if (E->isIncrementDecrementOp()) {
11018         HandleValue(E->getSubExpr());
11019         return;
11020       }
11021 
11022       Inherited::VisitUnaryOperator(E);
11023     }
11024 
11025     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11026 
11027     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11028       if (E->getConstructor()->isCopyConstructor()) {
11029         Expr *ArgExpr = E->getArg(0);
11030         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11031           if (ILE->getNumInits() == 1)
11032             ArgExpr = ILE->getInit(0);
11033         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11034           if (ICE->getCastKind() == CK_NoOp)
11035             ArgExpr = ICE->getSubExpr();
11036         HandleValue(ArgExpr);
11037         return;
11038       }
11039       Inherited::VisitCXXConstructExpr(E);
11040     }
11041 
11042     void VisitCallExpr(CallExpr *E) {
11043       // Treat std::move as a use.
11044       if (E->isCallToStdMove()) {
11045         HandleValue(E->getArg(0));
11046         return;
11047       }
11048 
11049       Inherited::VisitCallExpr(E);
11050     }
11051 
11052     void VisitBinaryOperator(BinaryOperator *E) {
11053       if (E->isCompoundAssignmentOp()) {
11054         HandleValue(E->getLHS());
11055         Visit(E->getRHS());
11056         return;
11057       }
11058 
11059       Inherited::VisitBinaryOperator(E);
11060     }
11061 
11062     // A custom visitor for BinaryConditionalOperator is needed because the
11063     // regular visitor would check the condition and true expression separately
11064     // but both point to the same place giving duplicate diagnostics.
11065     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11066       Visit(E->getCond());
11067       Visit(E->getFalseExpr());
11068     }
11069 
11070     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11071       Decl* ReferenceDecl = DRE->getDecl();
11072       if (OrigDecl != ReferenceDecl) return;
11073       unsigned diag;
11074       if (isReferenceType) {
11075         diag = diag::warn_uninit_self_reference_in_reference_init;
11076       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11077         diag = diag::warn_static_self_reference_in_init;
11078       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11079                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11080                  DRE->getDecl()->getType()->isRecordType()) {
11081         diag = diag::warn_uninit_self_reference_in_init;
11082       } else {
11083         // Local variables will be handled by the CFG analysis.
11084         return;
11085       }
11086 
11087       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11088                             S.PDiag(diag)
11089                                 << DRE->getDecl() << OrigDecl->getLocation()
11090                                 << DRE->getSourceRange());
11091     }
11092   };
11093 
11094   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11095   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11096                                  bool DirectInit) {
11097     // Parameters arguments are occassionially constructed with itself,
11098     // for instance, in recursive functions.  Skip them.
11099     if (isa<ParmVarDecl>(OrigDecl))
11100       return;
11101 
11102     E = E->IgnoreParens();
11103 
11104     // Skip checking T a = a where T is not a record or reference type.
11105     // Doing so is a way to silence uninitialized warnings.
11106     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11107       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11108         if (ICE->getCastKind() == CK_LValueToRValue)
11109           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11110             if (DRE->getDecl() == OrigDecl)
11111               return;
11112 
11113     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11114   }
11115 } // end anonymous namespace
11116 
11117 namespace {
11118   // Simple wrapper to add the name of a variable or (if no variable is
11119   // available) a DeclarationName into a diagnostic.
11120   struct VarDeclOrName {
11121     VarDecl *VDecl;
11122     DeclarationName Name;
11123 
11124     friend const Sema::SemaDiagnosticBuilder &
11125     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11126       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11127     }
11128   };
11129 } // end anonymous namespace
11130 
11131 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11132                                             DeclarationName Name, QualType Type,
11133                                             TypeSourceInfo *TSI,
11134                                             SourceRange Range, bool DirectInit,
11135                                             Expr *Init) {
11136   bool IsInitCapture = !VDecl;
11137   assert((!VDecl || !VDecl->isInitCapture()) &&
11138          "init captures are expected to be deduced prior to initialization");
11139 
11140   VarDeclOrName VN{VDecl, Name};
11141 
11142   DeducedType *Deduced = Type->getContainedDeducedType();
11143   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11144 
11145   // C++11 [dcl.spec.auto]p3
11146   if (!Init) {
11147     assert(VDecl && "no init for init capture deduction?");
11148 
11149     // Except for class argument deduction, and then for an initializing
11150     // declaration only, i.e. no static at class scope or extern.
11151     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11152         VDecl->hasExternalStorage() ||
11153         VDecl->isStaticDataMember()) {
11154       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11155         << VDecl->getDeclName() << Type;
11156       return QualType();
11157     }
11158   }
11159 
11160   ArrayRef<Expr*> DeduceInits;
11161   if (Init)
11162     DeduceInits = Init;
11163 
11164   if (DirectInit) {
11165     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11166       DeduceInits = PL->exprs();
11167   }
11168 
11169   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11170     assert(VDecl && "non-auto type for init capture deduction?");
11171     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11172     InitializationKind Kind = InitializationKind::CreateForInit(
11173         VDecl->getLocation(), DirectInit, Init);
11174     // FIXME: Initialization should not be taking a mutable list of inits.
11175     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11176     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11177                                                        InitsCopy);
11178   }
11179 
11180   if (DirectInit) {
11181     if (auto *IL = dyn_cast<InitListExpr>(Init))
11182       DeduceInits = IL->inits();
11183   }
11184 
11185   // Deduction only works if we have exactly one source expression.
11186   if (DeduceInits.empty()) {
11187     // It isn't possible to write this directly, but it is possible to
11188     // end up in this situation with "auto x(some_pack...);"
11189     Diag(Init->getBeginLoc(), IsInitCapture
11190                                   ? diag::err_init_capture_no_expression
11191                                   : diag::err_auto_var_init_no_expression)
11192         << VN << Type << Range;
11193     return QualType();
11194   }
11195 
11196   if (DeduceInits.size() > 1) {
11197     Diag(DeduceInits[1]->getBeginLoc(),
11198          IsInitCapture ? diag::err_init_capture_multiple_expressions
11199                        : diag::err_auto_var_init_multiple_expressions)
11200         << VN << Type << Range;
11201     return QualType();
11202   }
11203 
11204   Expr *DeduceInit = DeduceInits[0];
11205   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11206     Diag(Init->getBeginLoc(), IsInitCapture
11207                                   ? diag::err_init_capture_paren_braces
11208                                   : diag::err_auto_var_init_paren_braces)
11209         << isa<InitListExpr>(Init) << VN << Type << Range;
11210     return QualType();
11211   }
11212 
11213   // Expressions default to 'id' when we're in a debugger.
11214   bool DefaultedAnyToId = false;
11215   if (getLangOpts().DebuggerCastResultToId &&
11216       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11217     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11218     if (Result.isInvalid()) {
11219       return QualType();
11220     }
11221     Init = Result.get();
11222     DefaultedAnyToId = true;
11223   }
11224 
11225   // C++ [dcl.decomp]p1:
11226   //   If the assignment-expression [...] has array type A and no ref-qualifier
11227   //   is present, e has type cv A
11228   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11229       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11230       DeduceInit->getType()->isConstantArrayType())
11231     return Context.getQualifiedType(DeduceInit->getType(),
11232                                     Type.getQualifiers());
11233 
11234   QualType DeducedType;
11235   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11236     if (!IsInitCapture)
11237       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11238     else if (isa<InitListExpr>(Init))
11239       Diag(Range.getBegin(),
11240            diag::err_init_capture_deduction_failure_from_init_list)
11241           << VN
11242           << (DeduceInit->getType().isNull() ? TSI->getType()
11243                                              : DeduceInit->getType())
11244           << DeduceInit->getSourceRange();
11245     else
11246       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11247           << VN << TSI->getType()
11248           << (DeduceInit->getType().isNull() ? TSI->getType()
11249                                              : DeduceInit->getType())
11250           << DeduceInit->getSourceRange();
11251   }
11252 
11253   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11254   // 'id' instead of a specific object type prevents most of our usual
11255   // checks.
11256   // We only want to warn outside of template instantiations, though:
11257   // inside a template, the 'id' could have come from a parameter.
11258   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11259       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11260     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11261     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11262   }
11263 
11264   return DeducedType;
11265 }
11266 
11267 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11268                                          Expr *Init) {
11269   QualType DeducedType = deduceVarTypeFromInitializer(
11270       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11271       VDecl->getSourceRange(), DirectInit, Init);
11272   if (DeducedType.isNull()) {
11273     VDecl->setInvalidDecl();
11274     return true;
11275   }
11276 
11277   VDecl->setType(DeducedType);
11278   assert(VDecl->isLinkageValid());
11279 
11280   // In ARC, infer lifetime.
11281   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11282     VDecl->setInvalidDecl();
11283 
11284   // If this is a redeclaration, check that the type we just deduced matches
11285   // the previously declared type.
11286   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11287     // We never need to merge the type, because we cannot form an incomplete
11288     // array of auto, nor deduce such a type.
11289     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11290   }
11291 
11292   // Check the deduced type is valid for a variable declaration.
11293   CheckVariableDeclarationType(VDecl);
11294   return VDecl->isInvalidDecl();
11295 }
11296 
11297 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11298                                               SourceLocation Loc) {
11299   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11300     Init = CE->getSubExpr();
11301 
11302   QualType InitType = Init->getType();
11303   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11304           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11305          "shouldn't be called if type doesn't have a non-trivial C struct");
11306   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11307     for (auto I : ILE->inits()) {
11308       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11309           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11310         continue;
11311       SourceLocation SL = I->getExprLoc();
11312       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11313     }
11314     return;
11315   }
11316 
11317   if (isa<ImplicitValueInitExpr>(Init)) {
11318     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11319       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11320                             NTCUK_Init);
11321   } else {
11322     // Assume all other explicit initializers involving copying some existing
11323     // object.
11324     // TODO: ignore any explicit initializers where we can guarantee
11325     // copy-elision.
11326     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11327       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11328   }
11329 }
11330 
11331 namespace {
11332 
11333 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11334   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11335   // in the source code or implicitly by the compiler if it is in a union
11336   // defined in a system header and has non-trivial ObjC ownership
11337   // qualifications. We don't want those fields to participate in determining
11338   // whether the containing union is non-trivial.
11339   return FD->hasAttr<UnavailableAttr>();
11340 }
11341 
11342 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11343     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11344                                     void> {
11345   using Super =
11346       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11347                                     void>;
11348 
11349   DiagNonTrivalCUnionDefaultInitializeVisitor(
11350       QualType OrigTy, SourceLocation OrigLoc,
11351       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11352       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11353 
11354   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11355                      const FieldDecl *FD, bool InNonTrivialUnion) {
11356     if (const auto *AT = S.Context.getAsArrayType(QT))
11357       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11358                                      InNonTrivialUnion);
11359     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11360   }
11361 
11362   void visitARCStrong(QualType QT, const FieldDecl *FD,
11363                       bool InNonTrivialUnion) {
11364     if (InNonTrivialUnion)
11365       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11366           << 1 << 0 << QT << FD->getName();
11367   }
11368 
11369   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11370     if (InNonTrivialUnion)
11371       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11372           << 1 << 0 << QT << FD->getName();
11373   }
11374 
11375   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11376     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11377     if (RD->isUnion()) {
11378       if (OrigLoc.isValid()) {
11379         bool IsUnion = false;
11380         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11381           IsUnion = OrigRD->isUnion();
11382         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11383             << 0 << OrigTy << IsUnion << UseContext;
11384         // Reset OrigLoc so that this diagnostic is emitted only once.
11385         OrigLoc = SourceLocation();
11386       }
11387       InNonTrivialUnion = true;
11388     }
11389 
11390     if (InNonTrivialUnion)
11391       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11392           << 0 << 0 << QT.getUnqualifiedType() << "";
11393 
11394     for (const FieldDecl *FD : RD->fields())
11395       if (!shouldIgnoreForRecordTriviality(FD))
11396         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11397   }
11398 
11399   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11400 
11401   // The non-trivial C union type or the struct/union type that contains a
11402   // non-trivial C union.
11403   QualType OrigTy;
11404   SourceLocation OrigLoc;
11405   Sema::NonTrivialCUnionContext UseContext;
11406   Sema &S;
11407 };
11408 
11409 struct DiagNonTrivalCUnionDestructedTypeVisitor
11410     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11411   using Super =
11412       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11413 
11414   DiagNonTrivalCUnionDestructedTypeVisitor(
11415       QualType OrigTy, SourceLocation OrigLoc,
11416       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11417       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11418 
11419   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11420                      const FieldDecl *FD, bool InNonTrivialUnion) {
11421     if (const auto *AT = S.Context.getAsArrayType(QT))
11422       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11423                                      InNonTrivialUnion);
11424     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11425   }
11426 
11427   void visitARCStrong(QualType QT, const FieldDecl *FD,
11428                       bool InNonTrivialUnion) {
11429     if (InNonTrivialUnion)
11430       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11431           << 1 << 1 << QT << FD->getName();
11432   }
11433 
11434   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11435     if (InNonTrivialUnion)
11436       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11437           << 1 << 1 << QT << FD->getName();
11438   }
11439 
11440   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11441     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11442     if (RD->isUnion()) {
11443       if (OrigLoc.isValid()) {
11444         bool IsUnion = false;
11445         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11446           IsUnion = OrigRD->isUnion();
11447         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11448             << 1 << OrigTy << IsUnion << UseContext;
11449         // Reset OrigLoc so that this diagnostic is emitted only once.
11450         OrigLoc = SourceLocation();
11451       }
11452       InNonTrivialUnion = true;
11453     }
11454 
11455     if (InNonTrivialUnion)
11456       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11457           << 0 << 1 << QT.getUnqualifiedType() << "";
11458 
11459     for (const FieldDecl *FD : RD->fields())
11460       if (!shouldIgnoreForRecordTriviality(FD))
11461         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11462   }
11463 
11464   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11465   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11466                           bool InNonTrivialUnion) {}
11467 
11468   // The non-trivial C union type or the struct/union type that contains a
11469   // non-trivial C union.
11470   QualType OrigTy;
11471   SourceLocation OrigLoc;
11472   Sema::NonTrivialCUnionContext UseContext;
11473   Sema &S;
11474 };
11475 
11476 struct DiagNonTrivalCUnionCopyVisitor
11477     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11478   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11479 
11480   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11481                                  Sema::NonTrivialCUnionContext UseContext,
11482                                  Sema &S)
11483       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11484 
11485   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11486                      const FieldDecl *FD, bool InNonTrivialUnion) {
11487     if (const auto *AT = S.Context.getAsArrayType(QT))
11488       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11489                                      InNonTrivialUnion);
11490     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11491   }
11492 
11493   void visitARCStrong(QualType QT, const FieldDecl *FD,
11494                       bool InNonTrivialUnion) {
11495     if (InNonTrivialUnion)
11496       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11497           << 1 << 2 << QT << FD->getName();
11498   }
11499 
11500   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11501     if (InNonTrivialUnion)
11502       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11503           << 1 << 2 << QT << FD->getName();
11504   }
11505 
11506   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11507     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11508     if (RD->isUnion()) {
11509       if (OrigLoc.isValid()) {
11510         bool IsUnion = false;
11511         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11512           IsUnion = OrigRD->isUnion();
11513         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11514             << 2 << OrigTy << IsUnion << UseContext;
11515         // Reset OrigLoc so that this diagnostic is emitted only once.
11516         OrigLoc = SourceLocation();
11517       }
11518       InNonTrivialUnion = true;
11519     }
11520 
11521     if (InNonTrivialUnion)
11522       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11523           << 0 << 2 << QT.getUnqualifiedType() << "";
11524 
11525     for (const FieldDecl *FD : RD->fields())
11526       if (!shouldIgnoreForRecordTriviality(FD))
11527         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11528   }
11529 
11530   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11531                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11532   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11533   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11534                             bool InNonTrivialUnion) {}
11535 
11536   // The non-trivial C union type or the struct/union type that contains a
11537   // non-trivial C union.
11538   QualType OrigTy;
11539   SourceLocation OrigLoc;
11540   Sema::NonTrivialCUnionContext UseContext;
11541   Sema &S;
11542 };
11543 
11544 } // namespace
11545 
11546 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11547                                  NonTrivialCUnionContext UseContext,
11548                                  unsigned NonTrivialKind) {
11549   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11550           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11551           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11552          "shouldn't be called if type doesn't have a non-trivial C union");
11553 
11554   if ((NonTrivialKind & NTCUK_Init) &&
11555       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11556     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11557         .visit(QT, nullptr, false);
11558   if ((NonTrivialKind & NTCUK_Destruct) &&
11559       QT.hasNonTrivialToPrimitiveDestructCUnion())
11560     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11561         .visit(QT, nullptr, false);
11562   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11563     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11564         .visit(QT, nullptr, false);
11565 }
11566 
11567 /// AddInitializerToDecl - Adds the initializer Init to the
11568 /// declaration dcl. If DirectInit is true, this is C++ direct
11569 /// initialization rather than copy initialization.
11570 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11571   // If there is no declaration, there was an error parsing it.  Just ignore
11572   // the initializer.
11573   if (!RealDecl || RealDecl->isInvalidDecl()) {
11574     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11575     return;
11576   }
11577 
11578   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11579     // Pure-specifiers are handled in ActOnPureSpecifier.
11580     Diag(Method->getLocation(), diag::err_member_function_initialization)
11581       << Method->getDeclName() << Init->getSourceRange();
11582     Method->setInvalidDecl();
11583     return;
11584   }
11585 
11586   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11587   if (!VDecl) {
11588     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11589     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11590     RealDecl->setInvalidDecl();
11591     return;
11592   }
11593 
11594   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11595   if (VDecl->getType()->isUndeducedType()) {
11596     // Attempt typo correction early so that the type of the init expression can
11597     // be deduced based on the chosen correction if the original init contains a
11598     // TypoExpr.
11599     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11600     if (!Res.isUsable()) {
11601       RealDecl->setInvalidDecl();
11602       return;
11603     }
11604     Init = Res.get();
11605 
11606     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11607       return;
11608   }
11609 
11610   // dllimport cannot be used on variable definitions.
11611   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11612     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11613     VDecl->setInvalidDecl();
11614     return;
11615   }
11616 
11617   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11618     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11619     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11620     VDecl->setInvalidDecl();
11621     return;
11622   }
11623 
11624   if (!VDecl->getType()->isDependentType()) {
11625     // A definition must end up with a complete type, which means it must be
11626     // complete with the restriction that an array type might be completed by
11627     // the initializer; note that later code assumes this restriction.
11628     QualType BaseDeclType = VDecl->getType();
11629     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11630       BaseDeclType = Array->getElementType();
11631     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11632                             diag::err_typecheck_decl_incomplete_type)) {
11633       RealDecl->setInvalidDecl();
11634       return;
11635     }
11636 
11637     // The variable can not have an abstract class type.
11638     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11639                                diag::err_abstract_type_in_decl,
11640                                AbstractVariableType))
11641       VDecl->setInvalidDecl();
11642   }
11643 
11644   // If adding the initializer will turn this declaration into a definition,
11645   // and we already have a definition for this variable, diagnose or otherwise
11646   // handle the situation.
11647   VarDecl *Def;
11648   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11649       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11650       !VDecl->isThisDeclarationADemotedDefinition() &&
11651       checkVarDeclRedefinition(Def, VDecl))
11652     return;
11653 
11654   if (getLangOpts().CPlusPlus) {
11655     // C++ [class.static.data]p4
11656     //   If a static data member is of const integral or const
11657     //   enumeration type, its declaration in the class definition can
11658     //   specify a constant-initializer which shall be an integral
11659     //   constant expression (5.19). In that case, the member can appear
11660     //   in integral constant expressions. The member shall still be
11661     //   defined in a namespace scope if it is used in the program and the
11662     //   namespace scope definition shall not contain an initializer.
11663     //
11664     // We already performed a redefinition check above, but for static
11665     // data members we also need to check whether there was an in-class
11666     // declaration with an initializer.
11667     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11668       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11669           << VDecl->getDeclName();
11670       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11671            diag::note_previous_initializer)
11672           << 0;
11673       return;
11674     }
11675 
11676     if (VDecl->hasLocalStorage())
11677       setFunctionHasBranchProtectedScope();
11678 
11679     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11680       VDecl->setInvalidDecl();
11681       return;
11682     }
11683   }
11684 
11685   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11686   // a kernel function cannot be initialized."
11687   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11688     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11689     VDecl->setInvalidDecl();
11690     return;
11691   }
11692 
11693   // Get the decls type and save a reference for later, since
11694   // CheckInitializerTypes may change it.
11695   QualType DclT = VDecl->getType(), SavT = DclT;
11696 
11697   // Expressions default to 'id' when we're in a debugger
11698   // and we are assigning it to a variable of Objective-C pointer type.
11699   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11700       Init->getType() == Context.UnknownAnyTy) {
11701     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11702     if (Result.isInvalid()) {
11703       VDecl->setInvalidDecl();
11704       return;
11705     }
11706     Init = Result.get();
11707   }
11708 
11709   // Perform the initialization.
11710   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11711   if (!VDecl->isInvalidDecl()) {
11712     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11713     InitializationKind Kind = InitializationKind::CreateForInit(
11714         VDecl->getLocation(), DirectInit, Init);
11715 
11716     MultiExprArg Args = Init;
11717     if (CXXDirectInit)
11718       Args = MultiExprArg(CXXDirectInit->getExprs(),
11719                           CXXDirectInit->getNumExprs());
11720 
11721     // Try to correct any TypoExprs in the initialization arguments.
11722     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11723       ExprResult Res = CorrectDelayedTyposInExpr(
11724           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11725             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11726             return Init.Failed() ? ExprError() : E;
11727           });
11728       if (Res.isInvalid()) {
11729         VDecl->setInvalidDecl();
11730       } else if (Res.get() != Args[Idx]) {
11731         Args[Idx] = Res.get();
11732       }
11733     }
11734     if (VDecl->isInvalidDecl())
11735       return;
11736 
11737     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11738                                    /*TopLevelOfInitList=*/false,
11739                                    /*TreatUnavailableAsInvalid=*/false);
11740     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11741     if (Result.isInvalid()) {
11742       VDecl->setInvalidDecl();
11743       return;
11744     }
11745 
11746     Init = Result.getAs<Expr>();
11747   }
11748 
11749   // Check for self-references within variable initializers.
11750   // Variables declared within a function/method body (except for references)
11751   // are handled by a dataflow analysis.
11752   // This is undefined behavior in C++, but valid in C.
11753   if (getLangOpts().CPlusPlus) {
11754     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11755         VDecl->getType()->isReferenceType()) {
11756       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11757     }
11758   }
11759 
11760   // If the type changed, it means we had an incomplete type that was
11761   // completed by the initializer. For example:
11762   //   int ary[] = { 1, 3, 5 };
11763   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11764   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11765     VDecl->setType(DclT);
11766 
11767   if (!VDecl->isInvalidDecl()) {
11768     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11769 
11770     if (VDecl->hasAttr<BlocksAttr>())
11771       checkRetainCycles(VDecl, Init);
11772 
11773     // It is safe to assign a weak reference into a strong variable.
11774     // Although this code can still have problems:
11775     //   id x = self.weakProp;
11776     //   id y = self.weakProp;
11777     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11778     // paths through the function. This should be revisited if
11779     // -Wrepeated-use-of-weak is made flow-sensitive.
11780     if (FunctionScopeInfo *FSI = getCurFunction())
11781       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11782            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11783           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11784                            Init->getBeginLoc()))
11785         FSI->markSafeWeakUse(Init);
11786   }
11787 
11788   // The initialization is usually a full-expression.
11789   //
11790   // FIXME: If this is a braced initialization of an aggregate, it is not
11791   // an expression, and each individual field initializer is a separate
11792   // full-expression. For instance, in:
11793   //
11794   //   struct Temp { ~Temp(); };
11795   //   struct S { S(Temp); };
11796   //   struct T { S a, b; } t = { Temp(), Temp() }
11797   //
11798   // we should destroy the first Temp before constructing the second.
11799   ExprResult Result =
11800       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11801                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11802   if (Result.isInvalid()) {
11803     VDecl->setInvalidDecl();
11804     return;
11805   }
11806   Init = Result.get();
11807 
11808   // Attach the initializer to the decl.
11809   VDecl->setInit(Init);
11810 
11811   if (VDecl->isLocalVarDecl()) {
11812     // Don't check the initializer if the declaration is malformed.
11813     if (VDecl->isInvalidDecl()) {
11814       // do nothing
11815 
11816     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11817     // This is true even in C++ for OpenCL.
11818     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11819       CheckForConstantInitializer(Init, DclT);
11820 
11821     // Otherwise, C++ does not restrict the initializer.
11822     } else if (getLangOpts().CPlusPlus) {
11823       // do nothing
11824 
11825     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11826     // static storage duration shall be constant expressions or string literals.
11827     } else if (VDecl->getStorageClass() == SC_Static) {
11828       CheckForConstantInitializer(Init, DclT);
11829 
11830     // C89 is stricter than C99 for aggregate initializers.
11831     // C89 6.5.7p3: All the expressions [...] in an initializer list
11832     // for an object that has aggregate or union type shall be
11833     // constant expressions.
11834     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11835                isa<InitListExpr>(Init)) {
11836       const Expr *Culprit;
11837       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11838         Diag(Culprit->getExprLoc(),
11839              diag::ext_aggregate_init_not_constant)
11840           << Culprit->getSourceRange();
11841       }
11842     }
11843 
11844     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11845       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11846         if (VDecl->hasLocalStorage())
11847           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11848   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11849              VDecl->getLexicalDeclContext()->isRecord()) {
11850     // This is an in-class initialization for a static data member, e.g.,
11851     //
11852     // struct S {
11853     //   static const int value = 17;
11854     // };
11855 
11856     // C++ [class.mem]p4:
11857     //   A member-declarator can contain a constant-initializer only
11858     //   if it declares a static member (9.4) of const integral or
11859     //   const enumeration type, see 9.4.2.
11860     //
11861     // C++11 [class.static.data]p3:
11862     //   If a non-volatile non-inline const static data member is of integral
11863     //   or enumeration type, its declaration in the class definition can
11864     //   specify a brace-or-equal-initializer in which every initializer-clause
11865     //   that is an assignment-expression is a constant expression. A static
11866     //   data member of literal type can be declared in the class definition
11867     //   with the constexpr specifier; if so, its declaration shall specify a
11868     //   brace-or-equal-initializer in which every initializer-clause that is
11869     //   an assignment-expression is a constant expression.
11870 
11871     // Do nothing on dependent types.
11872     if (DclT->isDependentType()) {
11873 
11874     // Allow any 'static constexpr' members, whether or not they are of literal
11875     // type. We separately check that every constexpr variable is of literal
11876     // type.
11877     } else if (VDecl->isConstexpr()) {
11878 
11879     // Require constness.
11880     } else if (!DclT.isConstQualified()) {
11881       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11882         << Init->getSourceRange();
11883       VDecl->setInvalidDecl();
11884 
11885     // We allow integer constant expressions in all cases.
11886     } else if (DclT->isIntegralOrEnumerationType()) {
11887       // Check whether the expression is a constant expression.
11888       SourceLocation Loc;
11889       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11890         // In C++11, a non-constexpr const static data member with an
11891         // in-class initializer cannot be volatile.
11892         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11893       else if (Init->isValueDependent())
11894         ; // Nothing to check.
11895       else if (Init->isIntegerConstantExpr(Context, &Loc))
11896         ; // Ok, it's an ICE!
11897       else if (Init->getType()->isScopedEnumeralType() &&
11898                Init->isCXX11ConstantExpr(Context))
11899         ; // Ok, it is a scoped-enum constant expression.
11900       else if (Init->isEvaluatable(Context)) {
11901         // If we can constant fold the initializer through heroics, accept it,
11902         // but report this as a use of an extension for -pedantic.
11903         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11904           << Init->getSourceRange();
11905       } else {
11906         // Otherwise, this is some crazy unknown case.  Report the issue at the
11907         // location provided by the isIntegerConstantExpr failed check.
11908         Diag(Loc, diag::err_in_class_initializer_non_constant)
11909           << Init->getSourceRange();
11910         VDecl->setInvalidDecl();
11911       }
11912 
11913     // We allow foldable floating-point constants as an extension.
11914     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11915       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11916       // it anyway and provide a fixit to add the 'constexpr'.
11917       if (getLangOpts().CPlusPlus11) {
11918         Diag(VDecl->getLocation(),
11919              diag::ext_in_class_initializer_float_type_cxx11)
11920             << DclT << Init->getSourceRange();
11921         Diag(VDecl->getBeginLoc(),
11922              diag::note_in_class_initializer_float_type_cxx11)
11923             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11924       } else {
11925         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11926           << DclT << Init->getSourceRange();
11927 
11928         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11929           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11930             << Init->getSourceRange();
11931           VDecl->setInvalidDecl();
11932         }
11933       }
11934 
11935     // Suggest adding 'constexpr' in C++11 for literal types.
11936     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11937       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11938           << DclT << Init->getSourceRange()
11939           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11940       VDecl->setConstexpr(true);
11941 
11942     } else {
11943       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11944         << DclT << Init->getSourceRange();
11945       VDecl->setInvalidDecl();
11946     }
11947   } else if (VDecl->isFileVarDecl()) {
11948     // In C, extern is typically used to avoid tentative definitions when
11949     // declaring variables in headers, but adding an intializer makes it a
11950     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11951     // In C++, extern is often used to give implictly static const variables
11952     // external linkage, so don't warn in that case. If selectany is present,
11953     // this might be header code intended for C and C++ inclusion, so apply the
11954     // C++ rules.
11955     if (VDecl->getStorageClass() == SC_Extern &&
11956         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11957          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11958         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11959         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11960       Diag(VDecl->getLocation(), diag::warn_extern_init);
11961 
11962     // In Microsoft C++ mode, a const variable defined in namespace scope has
11963     // external linkage by default if the variable is declared with
11964     // __declspec(dllexport).
11965     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11966         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11967         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11968       VDecl->setStorageClass(SC_Extern);
11969 
11970     // C99 6.7.8p4. All file scoped initializers need to be constant.
11971     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11972       CheckForConstantInitializer(Init, DclT);
11973   }
11974 
11975   QualType InitType = Init->getType();
11976   if (!InitType.isNull() &&
11977       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11978        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
11979     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
11980 
11981   // We will represent direct-initialization similarly to copy-initialization:
11982   //    int x(1);  -as-> int x = 1;
11983   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11984   //
11985   // Clients that want to distinguish between the two forms, can check for
11986   // direct initializer using VarDecl::getInitStyle().
11987   // A major benefit is that clients that don't particularly care about which
11988   // exactly form was it (like the CodeGen) can handle both cases without
11989   // special case code.
11990 
11991   // C++ 8.5p11:
11992   // The form of initialization (using parentheses or '=') is generally
11993   // insignificant, but does matter when the entity being initialized has a
11994   // class type.
11995   if (CXXDirectInit) {
11996     assert(DirectInit && "Call-style initializer must be direct init.");
11997     VDecl->setInitStyle(VarDecl::CallInit);
11998   } else if (DirectInit) {
11999     // This must be list-initialization. No other way is direct-initialization.
12000     VDecl->setInitStyle(VarDecl::ListInit);
12001   }
12002 
12003   CheckCompleteVariableDeclaration(VDecl);
12004 }
12005 
12006 /// ActOnInitializerError - Given that there was an error parsing an
12007 /// initializer for the given declaration, try to return to some form
12008 /// of sanity.
12009 void Sema::ActOnInitializerError(Decl *D) {
12010   // Our main concern here is re-establishing invariants like "a
12011   // variable's type is either dependent or complete".
12012   if (!D || D->isInvalidDecl()) return;
12013 
12014   VarDecl *VD = dyn_cast<VarDecl>(D);
12015   if (!VD) return;
12016 
12017   // Bindings are not usable if we can't make sense of the initializer.
12018   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12019     for (auto *BD : DD->bindings())
12020       BD->setInvalidDecl();
12021 
12022   // Auto types are meaningless if we can't make sense of the initializer.
12023   if (ParsingInitForAutoVars.count(D)) {
12024     D->setInvalidDecl();
12025     return;
12026   }
12027 
12028   QualType Ty = VD->getType();
12029   if (Ty->isDependentType()) return;
12030 
12031   // Require a complete type.
12032   if (RequireCompleteType(VD->getLocation(),
12033                           Context.getBaseElementType(Ty),
12034                           diag::err_typecheck_decl_incomplete_type)) {
12035     VD->setInvalidDecl();
12036     return;
12037   }
12038 
12039   // Require a non-abstract type.
12040   if (RequireNonAbstractType(VD->getLocation(), Ty,
12041                              diag::err_abstract_type_in_decl,
12042                              AbstractVariableType)) {
12043     VD->setInvalidDecl();
12044     return;
12045   }
12046 
12047   // Don't bother complaining about constructors or destructors,
12048   // though.
12049 }
12050 
12051 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12052   // If there is no declaration, there was an error parsing it. Just ignore it.
12053   if (!RealDecl)
12054     return;
12055 
12056   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12057     QualType Type = Var->getType();
12058 
12059     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12060     if (isa<DecompositionDecl>(RealDecl)) {
12061       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12062       Var->setInvalidDecl();
12063       return;
12064     }
12065 
12066     if (Type->isUndeducedType() &&
12067         DeduceVariableDeclarationType(Var, false, nullptr))
12068       return;
12069 
12070     // C++11 [class.static.data]p3: A static data member can be declared with
12071     // the constexpr specifier; if so, its declaration shall specify
12072     // a brace-or-equal-initializer.
12073     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12074     // the definition of a variable [...] or the declaration of a static data
12075     // member.
12076     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12077         !Var->isThisDeclarationADemotedDefinition()) {
12078       if (Var->isStaticDataMember()) {
12079         // C++1z removes the relevant rule; the in-class declaration is always
12080         // a definition there.
12081         if (!getLangOpts().CPlusPlus17 &&
12082             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12083           Diag(Var->getLocation(),
12084                diag::err_constexpr_static_mem_var_requires_init)
12085             << Var->getDeclName();
12086           Var->setInvalidDecl();
12087           return;
12088         }
12089       } else {
12090         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12091         Var->setInvalidDecl();
12092         return;
12093       }
12094     }
12095 
12096     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12097     // be initialized.
12098     if (!Var->isInvalidDecl() &&
12099         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12100         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12101       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12102       Var->setInvalidDecl();
12103       return;
12104     }
12105 
12106     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12107     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12108         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12109       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12110                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12111 
12112 
12113     switch (DefKind) {
12114     case VarDecl::Definition:
12115       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12116         break;
12117 
12118       // We have an out-of-line definition of a static data member
12119       // that has an in-class initializer, so we type-check this like
12120       // a declaration.
12121       //
12122       LLVM_FALLTHROUGH;
12123 
12124     case VarDecl::DeclarationOnly:
12125       // It's only a declaration.
12126 
12127       // Block scope. C99 6.7p7: If an identifier for an object is
12128       // declared with no linkage (C99 6.2.2p6), the type for the
12129       // object shall be complete.
12130       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12131           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12132           RequireCompleteType(Var->getLocation(), Type,
12133                               diag::err_typecheck_decl_incomplete_type))
12134         Var->setInvalidDecl();
12135 
12136       // Make sure that the type is not abstract.
12137       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12138           RequireNonAbstractType(Var->getLocation(), Type,
12139                                  diag::err_abstract_type_in_decl,
12140                                  AbstractVariableType))
12141         Var->setInvalidDecl();
12142       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12143           Var->getStorageClass() == SC_PrivateExtern) {
12144         Diag(Var->getLocation(), diag::warn_private_extern);
12145         Diag(Var->getLocation(), diag::note_private_extern);
12146       }
12147 
12148       return;
12149 
12150     case VarDecl::TentativeDefinition:
12151       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12152       // object that has file scope without an initializer, and without a
12153       // storage-class specifier or with the storage-class specifier "static",
12154       // constitutes a tentative definition. Note: A tentative definition with
12155       // external linkage is valid (C99 6.2.2p5).
12156       if (!Var->isInvalidDecl()) {
12157         if (const IncompleteArrayType *ArrayT
12158                                     = Context.getAsIncompleteArrayType(Type)) {
12159           if (RequireCompleteType(Var->getLocation(),
12160                                   ArrayT->getElementType(),
12161                                   diag::err_illegal_decl_array_incomplete_type))
12162             Var->setInvalidDecl();
12163         } else if (Var->getStorageClass() == SC_Static) {
12164           // C99 6.9.2p3: If the declaration of an identifier for an object is
12165           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12166           // declared type shall not be an incomplete type.
12167           // NOTE: code such as the following
12168           //     static struct s;
12169           //     struct s { int a; };
12170           // is accepted by gcc. Hence here we issue a warning instead of
12171           // an error and we do not invalidate the static declaration.
12172           // NOTE: to avoid multiple warnings, only check the first declaration.
12173           if (Var->isFirstDecl())
12174             RequireCompleteType(Var->getLocation(), Type,
12175                                 diag::ext_typecheck_decl_incomplete_type);
12176         }
12177       }
12178 
12179       // Record the tentative definition; we're done.
12180       if (!Var->isInvalidDecl())
12181         TentativeDefinitions.push_back(Var);
12182       return;
12183     }
12184 
12185     // Provide a specific diagnostic for uninitialized variable
12186     // definitions with incomplete array type.
12187     if (Type->isIncompleteArrayType()) {
12188       Diag(Var->getLocation(),
12189            diag::err_typecheck_incomplete_array_needs_initializer);
12190       Var->setInvalidDecl();
12191       return;
12192     }
12193 
12194     // Provide a specific diagnostic for uninitialized variable
12195     // definitions with reference type.
12196     if (Type->isReferenceType()) {
12197       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12198         << Var->getDeclName()
12199         << SourceRange(Var->getLocation(), Var->getLocation());
12200       Var->setInvalidDecl();
12201       return;
12202     }
12203 
12204     // Do not attempt to type-check the default initializer for a
12205     // variable with dependent type.
12206     if (Type->isDependentType())
12207       return;
12208 
12209     if (Var->isInvalidDecl())
12210       return;
12211 
12212     if (!Var->hasAttr<AliasAttr>()) {
12213       if (RequireCompleteType(Var->getLocation(),
12214                               Context.getBaseElementType(Type),
12215                               diag::err_typecheck_decl_incomplete_type)) {
12216         Var->setInvalidDecl();
12217         return;
12218       }
12219     } else {
12220       return;
12221     }
12222 
12223     // The variable can not have an abstract class type.
12224     if (RequireNonAbstractType(Var->getLocation(), Type,
12225                                diag::err_abstract_type_in_decl,
12226                                AbstractVariableType)) {
12227       Var->setInvalidDecl();
12228       return;
12229     }
12230 
12231     // Check for jumps past the implicit initializer.  C++0x
12232     // clarifies that this applies to a "variable with automatic
12233     // storage duration", not a "local variable".
12234     // C++11 [stmt.dcl]p3
12235     //   A program that jumps from a point where a variable with automatic
12236     //   storage duration is not in scope to a point where it is in scope is
12237     //   ill-formed unless the variable has scalar type, class type with a
12238     //   trivial default constructor and a trivial destructor, a cv-qualified
12239     //   version of one of these types, or an array of one of the preceding
12240     //   types and is declared without an initializer.
12241     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12242       if (const RecordType *Record
12243             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12244         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12245         // Mark the function (if we're in one) for further checking even if the
12246         // looser rules of C++11 do not require such checks, so that we can
12247         // diagnose incompatibilities with C++98.
12248         if (!CXXRecord->isPOD())
12249           setFunctionHasBranchProtectedScope();
12250       }
12251     }
12252     // In OpenCL, we can't initialize objects in the __local address space,
12253     // even implicitly, so don't synthesize an implicit initializer.
12254     if (getLangOpts().OpenCL &&
12255         Var->getType().getAddressSpace() == LangAS::opencl_local)
12256       return;
12257     // C++03 [dcl.init]p9:
12258     //   If no initializer is specified for an object, and the
12259     //   object is of (possibly cv-qualified) non-POD class type (or
12260     //   array thereof), the object shall be default-initialized; if
12261     //   the object is of const-qualified type, the underlying class
12262     //   type shall have a user-declared default
12263     //   constructor. Otherwise, if no initializer is specified for
12264     //   a non- static object, the object and its subobjects, if
12265     //   any, have an indeterminate initial value); if the object
12266     //   or any of its subobjects are of const-qualified type, the
12267     //   program is ill-formed.
12268     // C++0x [dcl.init]p11:
12269     //   If no initializer is specified for an object, the object is
12270     //   default-initialized; [...].
12271     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12272     InitializationKind Kind
12273       = InitializationKind::CreateDefault(Var->getLocation());
12274 
12275     InitializationSequence InitSeq(*this, Entity, Kind, None);
12276     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12277     if (Init.isInvalid())
12278       Var->setInvalidDecl();
12279     else if (Init.get()) {
12280       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12281       // This is important for template substitution.
12282       Var->setInitStyle(VarDecl::CallInit);
12283     }
12284 
12285     CheckCompleteVariableDeclaration(Var);
12286   }
12287 }
12288 
12289 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12290   // If there is no declaration, there was an error parsing it. Ignore it.
12291   if (!D)
12292     return;
12293 
12294   VarDecl *VD = dyn_cast<VarDecl>(D);
12295   if (!VD) {
12296     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12297     D->setInvalidDecl();
12298     return;
12299   }
12300 
12301   VD->setCXXForRangeDecl(true);
12302 
12303   // for-range-declaration cannot be given a storage class specifier.
12304   int Error = -1;
12305   switch (VD->getStorageClass()) {
12306   case SC_None:
12307     break;
12308   case SC_Extern:
12309     Error = 0;
12310     break;
12311   case SC_Static:
12312     Error = 1;
12313     break;
12314   case SC_PrivateExtern:
12315     Error = 2;
12316     break;
12317   case SC_Auto:
12318     Error = 3;
12319     break;
12320   case SC_Register:
12321     Error = 4;
12322     break;
12323   }
12324   if (Error != -1) {
12325     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12326       << VD->getDeclName() << Error;
12327     D->setInvalidDecl();
12328   }
12329 }
12330 
12331 StmtResult
12332 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12333                                  IdentifierInfo *Ident,
12334                                  ParsedAttributes &Attrs,
12335                                  SourceLocation AttrEnd) {
12336   // C++1y [stmt.iter]p1:
12337   //   A range-based for statement of the form
12338   //      for ( for-range-identifier : for-range-initializer ) statement
12339   //   is equivalent to
12340   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12341   DeclSpec DS(Attrs.getPool().getFactory());
12342 
12343   const char *PrevSpec;
12344   unsigned DiagID;
12345   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12346                      getPrintingPolicy());
12347 
12348   Declarator D(DS, DeclaratorContext::ForContext);
12349   D.SetIdentifier(Ident, IdentLoc);
12350   D.takeAttributes(Attrs, AttrEnd);
12351 
12352   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12353                 IdentLoc);
12354   Decl *Var = ActOnDeclarator(S, D);
12355   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12356   FinalizeDeclaration(Var);
12357   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12358                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12359 }
12360 
12361 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12362   if (var->isInvalidDecl()) return;
12363 
12364   if (getLangOpts().OpenCL) {
12365     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12366     // initialiser
12367     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12368         !var->hasInit()) {
12369       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12370           << 1 /*Init*/;
12371       var->setInvalidDecl();
12372       return;
12373     }
12374   }
12375 
12376   // In Objective-C, don't allow jumps past the implicit initialization of a
12377   // local retaining variable.
12378   if (getLangOpts().ObjC &&
12379       var->hasLocalStorage()) {
12380     switch (var->getType().getObjCLifetime()) {
12381     case Qualifiers::OCL_None:
12382     case Qualifiers::OCL_ExplicitNone:
12383     case Qualifiers::OCL_Autoreleasing:
12384       break;
12385 
12386     case Qualifiers::OCL_Weak:
12387     case Qualifiers::OCL_Strong:
12388       setFunctionHasBranchProtectedScope();
12389       break;
12390     }
12391   }
12392 
12393   if (var->hasLocalStorage() &&
12394       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12395     setFunctionHasBranchProtectedScope();
12396 
12397   // Warn about externally-visible variables being defined without a
12398   // prior declaration.  We only want to do this for global
12399   // declarations, but we also specifically need to avoid doing it for
12400   // class members because the linkage of an anonymous class can
12401   // change if it's later given a typedef name.
12402   if (var->isThisDeclarationADefinition() &&
12403       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12404       var->isExternallyVisible() && var->hasLinkage() &&
12405       !var->isInline() && !var->getDescribedVarTemplate() &&
12406       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12407       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12408                                   var->getLocation())) {
12409     // Find a previous declaration that's not a definition.
12410     VarDecl *prev = var->getPreviousDecl();
12411     while (prev && prev->isThisDeclarationADefinition())
12412       prev = prev->getPreviousDecl();
12413 
12414     if (!prev) {
12415       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12416       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12417           << /* variable */ 0;
12418     }
12419   }
12420 
12421   // Cache the result of checking for constant initialization.
12422   Optional<bool> CacheHasConstInit;
12423   const Expr *CacheCulprit = nullptr;
12424   auto checkConstInit = [&]() mutable {
12425     if (!CacheHasConstInit)
12426       CacheHasConstInit = var->getInit()->isConstantInitializer(
12427             Context, var->getType()->isReferenceType(), &CacheCulprit);
12428     return *CacheHasConstInit;
12429   };
12430 
12431   if (var->getTLSKind() == VarDecl::TLS_Static) {
12432     if (var->getType().isDestructedType()) {
12433       // GNU C++98 edits for __thread, [basic.start.term]p3:
12434       //   The type of an object with thread storage duration shall not
12435       //   have a non-trivial destructor.
12436       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12437       if (getLangOpts().CPlusPlus11)
12438         Diag(var->getLocation(), diag::note_use_thread_local);
12439     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12440       if (!checkConstInit()) {
12441         // GNU C++98 edits for __thread, [basic.start.init]p4:
12442         //   An object of thread storage duration shall not require dynamic
12443         //   initialization.
12444         // FIXME: Need strict checking here.
12445         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12446           << CacheCulprit->getSourceRange();
12447         if (getLangOpts().CPlusPlus11)
12448           Diag(var->getLocation(), diag::note_use_thread_local);
12449       }
12450     }
12451   }
12452 
12453   // Apply section attributes and pragmas to global variables.
12454   bool GlobalStorage = var->hasGlobalStorage();
12455   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12456       !inTemplateInstantiation()) {
12457     PragmaStack<StringLiteral *> *Stack = nullptr;
12458     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12459     if (var->getType().isConstQualified())
12460       Stack = &ConstSegStack;
12461     else if (!var->getInit()) {
12462       Stack = &BSSSegStack;
12463       SectionFlags |= ASTContext::PSF_Write;
12464     } else {
12465       Stack = &DataSegStack;
12466       SectionFlags |= ASTContext::PSF_Write;
12467     }
12468     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12469       var->addAttr(SectionAttr::CreateImplicit(
12470           Context, Stack->CurrentValue->getString(),
12471           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12472           SectionAttr::Declspec_allocate));
12473     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12474       if (UnifySection(SA->getName(), SectionFlags, var))
12475         var->dropAttr<SectionAttr>();
12476 
12477     // Apply the init_seg attribute if this has an initializer.  If the
12478     // initializer turns out to not be dynamic, we'll end up ignoring this
12479     // attribute.
12480     if (CurInitSeg && var->getInit())
12481       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12482                                                CurInitSegLoc,
12483                                                AttributeCommonInfo::AS_Pragma));
12484   }
12485 
12486   // All the following checks are C++ only.
12487   if (!getLangOpts().CPlusPlus) {
12488       // If this variable must be emitted, add it as an initializer for the
12489       // current module.
12490      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12491        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12492      return;
12493   }
12494 
12495   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12496     CheckCompleteDecompositionDeclaration(DD);
12497 
12498   QualType type = var->getType();
12499   if (type->isDependentType()) return;
12500 
12501   if (var->hasAttr<BlocksAttr>())
12502     getCurFunction()->addByrefBlockVar(var);
12503 
12504   Expr *Init = var->getInit();
12505   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12506   QualType baseType = Context.getBaseElementType(type);
12507 
12508   if (Init && !Init->isValueDependent()) {
12509     if (var->isConstexpr()) {
12510       SmallVector<PartialDiagnosticAt, 8> Notes;
12511       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12512         SourceLocation DiagLoc = var->getLocation();
12513         // If the note doesn't add any useful information other than a source
12514         // location, fold it into the primary diagnostic.
12515         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12516               diag::note_invalid_subexpr_in_const_expr) {
12517           DiagLoc = Notes[0].first;
12518           Notes.clear();
12519         }
12520         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12521           << var << Init->getSourceRange();
12522         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12523           Diag(Notes[I].first, Notes[I].second);
12524       }
12525     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12526       // Check whether the initializer of a const variable of integral or
12527       // enumeration type is an ICE now, since we can't tell whether it was
12528       // initialized by a constant expression if we check later.
12529       var->checkInitIsICE();
12530     }
12531 
12532     // Don't emit further diagnostics about constexpr globals since they
12533     // were just diagnosed.
12534     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12535       // FIXME: Need strict checking in C++03 here.
12536       bool DiagErr = getLangOpts().CPlusPlus11
12537           ? !var->checkInitIsICE() : !checkConstInit();
12538       if (DiagErr) {
12539         auto *Attr = var->getAttr<ConstInitAttr>();
12540         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12541           << Init->getSourceRange();
12542         Diag(Attr->getLocation(),
12543              diag::note_declared_required_constant_init_here)
12544             << Attr->getRange() << Attr->isConstinit();
12545         if (getLangOpts().CPlusPlus11) {
12546           APValue Value;
12547           SmallVector<PartialDiagnosticAt, 8> Notes;
12548           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12549           for (auto &it : Notes)
12550             Diag(it.first, it.second);
12551         } else {
12552           Diag(CacheCulprit->getExprLoc(),
12553                diag::note_invalid_subexpr_in_const_expr)
12554               << CacheCulprit->getSourceRange();
12555         }
12556       }
12557     }
12558     else if (!var->isConstexpr() && IsGlobal &&
12559              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12560                                     var->getLocation())) {
12561       // Warn about globals which don't have a constant initializer.  Don't
12562       // warn about globals with a non-trivial destructor because we already
12563       // warned about them.
12564       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12565       if (!(RD && !RD->hasTrivialDestructor())) {
12566         if (!checkConstInit())
12567           Diag(var->getLocation(), diag::warn_global_constructor)
12568             << Init->getSourceRange();
12569       }
12570     }
12571   }
12572 
12573   // Require the destructor.
12574   if (const RecordType *recordType = baseType->getAs<RecordType>())
12575     FinalizeVarWithDestructor(var, recordType);
12576 
12577   // If this variable must be emitted, add it as an initializer for the current
12578   // module.
12579   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12580     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12581 }
12582 
12583 /// Determines if a variable's alignment is dependent.
12584 static bool hasDependentAlignment(VarDecl *VD) {
12585   if (VD->getType()->isDependentType())
12586     return true;
12587   for (auto *I : VD->specific_attrs<AlignedAttr>())
12588     if (I->isAlignmentDependent())
12589       return true;
12590   return false;
12591 }
12592 
12593 /// Check if VD needs to be dllexport/dllimport due to being in a
12594 /// dllexport/import function.
12595 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12596   assert(VD->isStaticLocal());
12597 
12598   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12599 
12600   // Find outermost function when VD is in lambda function.
12601   while (FD && !getDLLAttr(FD) &&
12602          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12603          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12604     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12605   }
12606 
12607   if (!FD)
12608     return;
12609 
12610   // Static locals inherit dll attributes from their function.
12611   if (Attr *A = getDLLAttr(FD)) {
12612     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12613     NewAttr->setInherited(true);
12614     VD->addAttr(NewAttr);
12615   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12616     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12617     NewAttr->setInherited(true);
12618     VD->addAttr(NewAttr);
12619 
12620     // Export this function to enforce exporting this static variable even
12621     // if it is not used in this compilation unit.
12622     if (!FD->hasAttr<DLLExportAttr>())
12623       FD->addAttr(NewAttr);
12624 
12625   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12626     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12627     NewAttr->setInherited(true);
12628     VD->addAttr(NewAttr);
12629   }
12630 }
12631 
12632 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12633 /// any semantic actions necessary after any initializer has been attached.
12634 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12635   // Note that we are no longer parsing the initializer for this declaration.
12636   ParsingInitForAutoVars.erase(ThisDecl);
12637 
12638   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12639   if (!VD)
12640     return;
12641 
12642   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12643   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12644       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12645     if (PragmaClangBSSSection.Valid)
12646       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12647           Context, PragmaClangBSSSection.SectionName,
12648           PragmaClangBSSSection.PragmaLocation,
12649           AttributeCommonInfo::AS_Pragma));
12650     if (PragmaClangDataSection.Valid)
12651       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12652           Context, PragmaClangDataSection.SectionName,
12653           PragmaClangDataSection.PragmaLocation,
12654           AttributeCommonInfo::AS_Pragma));
12655     if (PragmaClangRodataSection.Valid)
12656       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12657           Context, PragmaClangRodataSection.SectionName,
12658           PragmaClangRodataSection.PragmaLocation,
12659           AttributeCommonInfo::AS_Pragma));
12660     if (PragmaClangRelroSection.Valid)
12661       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12662           Context, PragmaClangRelroSection.SectionName,
12663           PragmaClangRelroSection.PragmaLocation,
12664           AttributeCommonInfo::AS_Pragma));
12665   }
12666 
12667   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12668     for (auto *BD : DD->bindings()) {
12669       FinalizeDeclaration(BD);
12670     }
12671   }
12672 
12673   checkAttributesAfterMerging(*this, *VD);
12674 
12675   // Perform TLS alignment check here after attributes attached to the variable
12676   // which may affect the alignment have been processed. Only perform the check
12677   // if the target has a maximum TLS alignment (zero means no constraints).
12678   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12679     // Protect the check so that it's not performed on dependent types and
12680     // dependent alignments (we can't determine the alignment in that case).
12681     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12682         !VD->isInvalidDecl()) {
12683       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12684       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12685         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12686           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12687           << (unsigned)MaxAlignChars.getQuantity();
12688       }
12689     }
12690   }
12691 
12692   if (VD->isStaticLocal()) {
12693     CheckStaticLocalForDllExport(VD);
12694 
12695     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12696       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12697       // function, only __shared__ variables or variables without any device
12698       // memory qualifiers may be declared with static storage class.
12699       // Note: It is unclear how a function-scope non-const static variable
12700       // without device memory qualifier is implemented, therefore only static
12701       // const variable without device memory qualifier is allowed.
12702       [&]() {
12703         if (!getLangOpts().CUDA)
12704           return;
12705         if (VD->hasAttr<CUDASharedAttr>())
12706           return;
12707         if (VD->getType().isConstQualified() &&
12708             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12709           return;
12710         if (CUDADiagIfDeviceCode(VD->getLocation(),
12711                                  diag::err_device_static_local_var)
12712             << CurrentCUDATarget())
12713           VD->setInvalidDecl();
12714       }();
12715     }
12716   }
12717 
12718   // Perform check for initializers of device-side global variables.
12719   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12720   // 7.5). We must also apply the same checks to all __shared__
12721   // variables whether they are local or not. CUDA also allows
12722   // constant initializers for __constant__ and __device__ variables.
12723   if (getLangOpts().CUDA)
12724     checkAllowedCUDAInitializer(VD);
12725 
12726   // Grab the dllimport or dllexport attribute off of the VarDecl.
12727   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12728 
12729   // Imported static data members cannot be defined out-of-line.
12730   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12731     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12732         VD->isThisDeclarationADefinition()) {
12733       // We allow definitions of dllimport class template static data members
12734       // with a warning.
12735       CXXRecordDecl *Context =
12736         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12737       bool IsClassTemplateMember =
12738           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12739           Context->getDescribedClassTemplate();
12740 
12741       Diag(VD->getLocation(),
12742            IsClassTemplateMember
12743                ? diag::warn_attribute_dllimport_static_field_definition
12744                : diag::err_attribute_dllimport_static_field_definition);
12745       Diag(IA->getLocation(), diag::note_attribute);
12746       if (!IsClassTemplateMember)
12747         VD->setInvalidDecl();
12748     }
12749   }
12750 
12751   // dllimport/dllexport variables cannot be thread local, their TLS index
12752   // isn't exported with the variable.
12753   if (DLLAttr && VD->getTLSKind()) {
12754     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12755     if (F && getDLLAttr(F)) {
12756       assert(VD->isStaticLocal());
12757       // But if this is a static local in a dlimport/dllexport function, the
12758       // function will never be inlined, which means the var would never be
12759       // imported, so having it marked import/export is safe.
12760     } else {
12761       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12762                                                                     << DLLAttr;
12763       VD->setInvalidDecl();
12764     }
12765   }
12766 
12767   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12768     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12769       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12770       VD->dropAttr<UsedAttr>();
12771     }
12772   }
12773 
12774   const DeclContext *DC = VD->getDeclContext();
12775   // If there's a #pragma GCC visibility in scope, and this isn't a class
12776   // member, set the visibility of this variable.
12777   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12778     AddPushedVisibilityAttribute(VD);
12779 
12780   // FIXME: Warn on unused var template partial specializations.
12781   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12782     MarkUnusedFileScopedDecl(VD);
12783 
12784   // Now we have parsed the initializer and can update the table of magic
12785   // tag values.
12786   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12787       !VD->getType()->isIntegralOrEnumerationType())
12788     return;
12789 
12790   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12791     const Expr *MagicValueExpr = VD->getInit();
12792     if (!MagicValueExpr) {
12793       continue;
12794     }
12795     llvm::APSInt MagicValueInt;
12796     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12797       Diag(I->getRange().getBegin(),
12798            diag::err_type_tag_for_datatype_not_ice)
12799         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12800       continue;
12801     }
12802     if (MagicValueInt.getActiveBits() > 64) {
12803       Diag(I->getRange().getBegin(),
12804            diag::err_type_tag_for_datatype_too_large)
12805         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12806       continue;
12807     }
12808     uint64_t MagicValue = MagicValueInt.getZExtValue();
12809     RegisterTypeTagForDatatype(I->getArgumentKind(),
12810                                MagicValue,
12811                                I->getMatchingCType(),
12812                                I->getLayoutCompatible(),
12813                                I->getMustBeNull());
12814   }
12815 }
12816 
12817 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12818   auto *VD = dyn_cast<VarDecl>(DD);
12819   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12820 }
12821 
12822 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12823                                                    ArrayRef<Decl *> Group) {
12824   SmallVector<Decl*, 8> Decls;
12825 
12826   if (DS.isTypeSpecOwned())
12827     Decls.push_back(DS.getRepAsDecl());
12828 
12829   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12830   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12831   bool DiagnosedMultipleDecomps = false;
12832   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12833   bool DiagnosedNonDeducedAuto = false;
12834 
12835   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12836     if (Decl *D = Group[i]) {
12837       // For declarators, there are some additional syntactic-ish checks we need
12838       // to perform.
12839       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12840         if (!FirstDeclaratorInGroup)
12841           FirstDeclaratorInGroup = DD;
12842         if (!FirstDecompDeclaratorInGroup)
12843           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12844         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12845             !hasDeducedAuto(DD))
12846           FirstNonDeducedAutoInGroup = DD;
12847 
12848         if (FirstDeclaratorInGroup != DD) {
12849           // A decomposition declaration cannot be combined with any other
12850           // declaration in the same group.
12851           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12852             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12853                  diag::err_decomp_decl_not_alone)
12854                 << FirstDeclaratorInGroup->getSourceRange()
12855                 << DD->getSourceRange();
12856             DiagnosedMultipleDecomps = true;
12857           }
12858 
12859           // A declarator that uses 'auto' in any way other than to declare a
12860           // variable with a deduced type cannot be combined with any other
12861           // declarator in the same group.
12862           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12863             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12864                  diag::err_auto_non_deduced_not_alone)
12865                 << FirstNonDeducedAutoInGroup->getType()
12866                        ->hasAutoForTrailingReturnType()
12867                 << FirstDeclaratorInGroup->getSourceRange()
12868                 << DD->getSourceRange();
12869             DiagnosedNonDeducedAuto = true;
12870           }
12871         }
12872       }
12873 
12874       Decls.push_back(D);
12875     }
12876   }
12877 
12878   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12879     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12880       handleTagNumbering(Tag, S);
12881       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12882           getLangOpts().CPlusPlus)
12883         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12884     }
12885   }
12886 
12887   return BuildDeclaratorGroup(Decls);
12888 }
12889 
12890 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12891 /// group, performing any necessary semantic checking.
12892 Sema::DeclGroupPtrTy
12893 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12894   // C++14 [dcl.spec.auto]p7: (DR1347)
12895   //   If the type that replaces the placeholder type is not the same in each
12896   //   deduction, the program is ill-formed.
12897   if (Group.size() > 1) {
12898     QualType Deduced;
12899     VarDecl *DeducedDecl = nullptr;
12900     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12901       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12902       if (!D || D->isInvalidDecl())
12903         break;
12904       DeducedType *DT = D->getType()->getContainedDeducedType();
12905       if (!DT || DT->getDeducedType().isNull())
12906         continue;
12907       if (Deduced.isNull()) {
12908         Deduced = DT->getDeducedType();
12909         DeducedDecl = D;
12910       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12911         auto *AT = dyn_cast<AutoType>(DT);
12912         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12913              diag::err_auto_different_deductions)
12914           << (AT ? (unsigned)AT->getKeyword() : 3)
12915           << Deduced << DeducedDecl->getDeclName()
12916           << DT->getDeducedType() << D->getDeclName()
12917           << DeducedDecl->getInit()->getSourceRange()
12918           << D->getInit()->getSourceRange();
12919         D->setInvalidDecl();
12920         break;
12921       }
12922     }
12923   }
12924 
12925   ActOnDocumentableDecls(Group);
12926 
12927   return DeclGroupPtrTy::make(
12928       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12929 }
12930 
12931 void Sema::ActOnDocumentableDecl(Decl *D) {
12932   ActOnDocumentableDecls(D);
12933 }
12934 
12935 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12936   // Don't parse the comment if Doxygen diagnostics are ignored.
12937   if (Group.empty() || !Group[0])
12938     return;
12939 
12940   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12941                       Group[0]->getLocation()) &&
12942       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12943                       Group[0]->getLocation()))
12944     return;
12945 
12946   if (Group.size() >= 2) {
12947     // This is a decl group.  Normally it will contain only declarations
12948     // produced from declarator list.  But in case we have any definitions or
12949     // additional declaration references:
12950     //   'typedef struct S {} S;'
12951     //   'typedef struct S *S;'
12952     //   'struct S *pS;'
12953     // FinalizeDeclaratorGroup adds these as separate declarations.
12954     Decl *MaybeTagDecl = Group[0];
12955     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12956       Group = Group.slice(1);
12957     }
12958   }
12959 
12960   // FIMXE: We assume every Decl in the group is in the same file.
12961   // This is false when preprocessor constructs the group from decls in
12962   // different files (e. g. macros or #include).
12963   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
12964 }
12965 
12966 /// Common checks for a parameter-declaration that should apply to both function
12967 /// parameters and non-type template parameters.
12968 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12969   // Check that there are no default arguments inside the type of this
12970   // parameter.
12971   if (getLangOpts().CPlusPlus)
12972     CheckExtraCXXDefaultArguments(D);
12973 
12974   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12975   if (D.getCXXScopeSpec().isSet()) {
12976     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12977       << D.getCXXScopeSpec().getRange();
12978   }
12979 
12980   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12981   // simple identifier except [...irrelevant cases...].
12982   switch (D.getName().getKind()) {
12983   case UnqualifiedIdKind::IK_Identifier:
12984     break;
12985 
12986   case UnqualifiedIdKind::IK_OperatorFunctionId:
12987   case UnqualifiedIdKind::IK_ConversionFunctionId:
12988   case UnqualifiedIdKind::IK_LiteralOperatorId:
12989   case UnqualifiedIdKind::IK_ConstructorName:
12990   case UnqualifiedIdKind::IK_DestructorName:
12991   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12992   case UnqualifiedIdKind::IK_DeductionGuideName:
12993     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12994       << GetNameForDeclarator(D).getName();
12995     break;
12996 
12997   case UnqualifiedIdKind::IK_TemplateId:
12998   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12999     // GetNameForDeclarator would not produce a useful name in this case.
13000     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13001     break;
13002   }
13003 }
13004 
13005 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13006 /// to introduce parameters into function prototype scope.
13007 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13008   const DeclSpec &DS = D.getDeclSpec();
13009 
13010   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13011 
13012   // C++03 [dcl.stc]p2 also permits 'auto'.
13013   StorageClass SC = SC_None;
13014   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13015     SC = SC_Register;
13016     // In C++11, the 'register' storage class specifier is deprecated.
13017     // In C++17, it is not allowed, but we tolerate it as an extension.
13018     if (getLangOpts().CPlusPlus11) {
13019       Diag(DS.getStorageClassSpecLoc(),
13020            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13021                                      : diag::warn_deprecated_register)
13022         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13023     }
13024   } else if (getLangOpts().CPlusPlus &&
13025              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13026     SC = SC_Auto;
13027   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13028     Diag(DS.getStorageClassSpecLoc(),
13029          diag::err_invalid_storage_class_in_func_decl);
13030     D.getMutableDeclSpec().ClearStorageClassSpecs();
13031   }
13032 
13033   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13034     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13035       << DeclSpec::getSpecifierName(TSCS);
13036   if (DS.isInlineSpecified())
13037     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13038         << getLangOpts().CPlusPlus17;
13039   if (DS.hasConstexprSpecifier())
13040     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13041         << 0 << D.getDeclSpec().getConstexprSpecifier();
13042 
13043   DiagnoseFunctionSpecifiers(DS);
13044 
13045   CheckFunctionOrTemplateParamDeclarator(S, D);
13046 
13047   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13048   QualType parmDeclType = TInfo->getType();
13049 
13050   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13051   IdentifierInfo *II = D.getIdentifier();
13052   if (II) {
13053     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13054                    ForVisibleRedeclaration);
13055     LookupName(R, S);
13056     if (R.isSingleResult()) {
13057       NamedDecl *PrevDecl = R.getFoundDecl();
13058       if (PrevDecl->isTemplateParameter()) {
13059         // Maybe we will complain about the shadowed template parameter.
13060         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13061         // Just pretend that we didn't see the previous declaration.
13062         PrevDecl = nullptr;
13063       } else if (S->isDeclScope(PrevDecl)) {
13064         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13065         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13066 
13067         // Recover by removing the name
13068         II = nullptr;
13069         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13070         D.setInvalidType(true);
13071       }
13072     }
13073   }
13074 
13075   // Temporarily put parameter variables in the translation unit, not
13076   // the enclosing context.  This prevents them from accidentally
13077   // looking like class members in C++.
13078   ParmVarDecl *New =
13079       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13080                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13081 
13082   if (D.isInvalidType())
13083     New->setInvalidDecl();
13084 
13085   assert(S->isFunctionPrototypeScope());
13086   assert(S->getFunctionPrototypeDepth() >= 1);
13087   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13088                     S->getNextFunctionPrototypeIndex());
13089 
13090   // Add the parameter declaration into this scope.
13091   S->AddDecl(New);
13092   if (II)
13093     IdResolver.AddDecl(New);
13094 
13095   ProcessDeclAttributes(S, New, D);
13096 
13097   if (D.getDeclSpec().isModulePrivateSpecified())
13098     Diag(New->getLocation(), diag::err_module_private_local)
13099       << 1 << New->getDeclName()
13100       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13101       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13102 
13103   if (New->hasAttr<BlocksAttr>()) {
13104     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13105   }
13106   return New;
13107 }
13108 
13109 /// Synthesizes a variable for a parameter arising from a
13110 /// typedef.
13111 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13112                                               SourceLocation Loc,
13113                                               QualType T) {
13114   /* FIXME: setting StartLoc == Loc.
13115      Would it be worth to modify callers so as to provide proper source
13116      location for the unnamed parameters, embedding the parameter's type? */
13117   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13118                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13119                                            SC_None, nullptr);
13120   Param->setImplicit();
13121   return Param;
13122 }
13123 
13124 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13125   // Don't diagnose unused-parameter errors in template instantiations; we
13126   // will already have done so in the template itself.
13127   if (inTemplateInstantiation())
13128     return;
13129 
13130   for (const ParmVarDecl *Parameter : Parameters) {
13131     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13132         !Parameter->hasAttr<UnusedAttr>()) {
13133       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13134         << Parameter->getDeclName();
13135     }
13136   }
13137 }
13138 
13139 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13140     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13141   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13142     return;
13143 
13144   // Warn if the return value is pass-by-value and larger than the specified
13145   // threshold.
13146   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13147     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13148     if (Size > LangOpts.NumLargeByValueCopy)
13149       Diag(D->getLocation(), diag::warn_return_value_size)
13150           << D->getDeclName() << Size;
13151   }
13152 
13153   // Warn if any parameter is pass-by-value and larger than the specified
13154   // threshold.
13155   for (const ParmVarDecl *Parameter : Parameters) {
13156     QualType T = Parameter->getType();
13157     if (T->isDependentType() || !T.isPODType(Context))
13158       continue;
13159     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13160     if (Size > LangOpts.NumLargeByValueCopy)
13161       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13162           << Parameter->getDeclName() << Size;
13163   }
13164 }
13165 
13166 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13167                                   SourceLocation NameLoc, IdentifierInfo *Name,
13168                                   QualType T, TypeSourceInfo *TSInfo,
13169                                   StorageClass SC) {
13170   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13171   if (getLangOpts().ObjCAutoRefCount &&
13172       T.getObjCLifetime() == Qualifiers::OCL_None &&
13173       T->isObjCLifetimeType()) {
13174 
13175     Qualifiers::ObjCLifetime lifetime;
13176 
13177     // Special cases for arrays:
13178     //   - if it's const, use __unsafe_unretained
13179     //   - otherwise, it's an error
13180     if (T->isArrayType()) {
13181       if (!T.isConstQualified()) {
13182         if (DelayedDiagnostics.shouldDelayDiagnostics())
13183           DelayedDiagnostics.add(
13184               sema::DelayedDiagnostic::makeForbiddenType(
13185               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13186         else
13187           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13188               << TSInfo->getTypeLoc().getSourceRange();
13189       }
13190       lifetime = Qualifiers::OCL_ExplicitNone;
13191     } else {
13192       lifetime = T->getObjCARCImplicitLifetime();
13193     }
13194     T = Context.getLifetimeQualifiedType(T, lifetime);
13195   }
13196 
13197   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13198                                          Context.getAdjustedParameterType(T),
13199                                          TSInfo, SC, nullptr);
13200 
13201   // Make a note if we created a new pack in the scope of a lambda, so that
13202   // we know that references to that pack must also be expanded within the
13203   // lambda scope.
13204   if (New->isParameterPack())
13205     if (auto *LSI = getEnclosingLambda())
13206       LSI->LocalPacks.push_back(New);
13207 
13208   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13209       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13210     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13211                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13212 
13213   // Parameters can not be abstract class types.
13214   // For record types, this is done by the AbstractClassUsageDiagnoser once
13215   // the class has been completely parsed.
13216   if (!CurContext->isRecord() &&
13217       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13218                              AbstractParamType))
13219     New->setInvalidDecl();
13220 
13221   // Parameter declarators cannot be interface types. All ObjC objects are
13222   // passed by reference.
13223   if (T->isObjCObjectType()) {
13224     SourceLocation TypeEndLoc =
13225         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13226     Diag(NameLoc,
13227          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13228       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13229     T = Context.getObjCObjectPointerType(T);
13230     New->setType(T);
13231   }
13232 
13233   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13234   // duration shall not be qualified by an address-space qualifier."
13235   // Since all parameters have automatic store duration, they can not have
13236   // an address space.
13237   if (T.getAddressSpace() != LangAS::Default &&
13238       // OpenCL allows function arguments declared to be an array of a type
13239       // to be qualified with an address space.
13240       !(getLangOpts().OpenCL &&
13241         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13242     Diag(NameLoc, diag::err_arg_with_address_space);
13243     New->setInvalidDecl();
13244   }
13245 
13246   return New;
13247 }
13248 
13249 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13250                                            SourceLocation LocAfterDecls) {
13251   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13252 
13253   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13254   // for a K&R function.
13255   if (!FTI.hasPrototype) {
13256     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13257       --i;
13258       if (FTI.Params[i].Param == nullptr) {
13259         SmallString<256> Code;
13260         llvm::raw_svector_ostream(Code)
13261             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13262         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13263             << FTI.Params[i].Ident
13264             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13265 
13266         // Implicitly declare the argument as type 'int' for lack of a better
13267         // type.
13268         AttributeFactory attrs;
13269         DeclSpec DS(attrs);
13270         const char* PrevSpec; // unused
13271         unsigned DiagID; // unused
13272         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13273                            DiagID, Context.getPrintingPolicy());
13274         // Use the identifier location for the type source range.
13275         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13276         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13277         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13278         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13279         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13280       }
13281     }
13282   }
13283 }
13284 
13285 Decl *
13286 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13287                               MultiTemplateParamsArg TemplateParameterLists,
13288                               SkipBodyInfo *SkipBody) {
13289   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13290   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13291   Scope *ParentScope = FnBodyScope->getParent();
13292 
13293   D.setFunctionDefinitionKind(FDK_Definition);
13294   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13295   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13296 }
13297 
13298 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13299   Consumer.HandleInlineFunctionDefinition(D);
13300 }
13301 
13302 static bool
13303 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13304                                 const FunctionDecl *&PossiblePrototype) {
13305   // Don't warn about invalid declarations.
13306   if (FD->isInvalidDecl())
13307     return false;
13308 
13309   // Or declarations that aren't global.
13310   if (!FD->isGlobal())
13311     return false;
13312 
13313   // Don't warn about C++ member functions.
13314   if (isa<CXXMethodDecl>(FD))
13315     return false;
13316 
13317   // Don't warn about 'main'.
13318   if (FD->isMain())
13319     return false;
13320 
13321   // Don't warn about inline functions.
13322   if (FD->isInlined())
13323     return false;
13324 
13325   // Don't warn about function templates.
13326   if (FD->getDescribedFunctionTemplate())
13327     return false;
13328 
13329   // Don't warn about function template specializations.
13330   if (FD->isFunctionTemplateSpecialization())
13331     return false;
13332 
13333   // Don't warn for OpenCL kernels.
13334   if (FD->hasAttr<OpenCLKernelAttr>())
13335     return false;
13336 
13337   // Don't warn on explicitly deleted functions.
13338   if (FD->isDeleted())
13339     return false;
13340 
13341   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13342        Prev; Prev = Prev->getPreviousDecl()) {
13343     // Ignore any declarations that occur in function or method
13344     // scope, because they aren't visible from the header.
13345     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13346       continue;
13347 
13348     PossiblePrototype = Prev;
13349     return Prev->getType()->isFunctionNoProtoType();
13350   }
13351 
13352   return true;
13353 }
13354 
13355 void
13356 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13357                                    const FunctionDecl *EffectiveDefinition,
13358                                    SkipBodyInfo *SkipBody) {
13359   const FunctionDecl *Definition = EffectiveDefinition;
13360   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13361     // If this is a friend function defined in a class template, it does not
13362     // have a body until it is used, nevertheless it is a definition, see
13363     // [temp.inst]p2:
13364     //
13365     // ... for the purpose of determining whether an instantiated redeclaration
13366     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13367     // corresponds to a definition in the template is considered to be a
13368     // definition.
13369     //
13370     // The following code must produce redefinition error:
13371     //
13372     //     template<typename T> struct C20 { friend void func_20() {} };
13373     //     C20<int> c20i;
13374     //     void func_20() {}
13375     //
13376     for (auto I : FD->redecls()) {
13377       if (I != FD && !I->isInvalidDecl() &&
13378           I->getFriendObjectKind() != Decl::FOK_None) {
13379         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13380           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13381             // A merged copy of the same function, instantiated as a member of
13382             // the same class, is OK.
13383             if (declaresSameEntity(OrigFD, Original) &&
13384                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13385                                    cast<Decl>(FD->getLexicalDeclContext())))
13386               continue;
13387           }
13388 
13389           if (Original->isThisDeclarationADefinition()) {
13390             Definition = I;
13391             break;
13392           }
13393         }
13394       }
13395     }
13396   }
13397 
13398   if (!Definition)
13399     // Similar to friend functions a friend function template may be a
13400     // definition and do not have a body if it is instantiated in a class
13401     // template.
13402     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13403       for (auto I : FTD->redecls()) {
13404         auto D = cast<FunctionTemplateDecl>(I);
13405         if (D != FTD) {
13406           assert(!D->isThisDeclarationADefinition() &&
13407                  "More than one definition in redeclaration chain");
13408           if (D->getFriendObjectKind() != Decl::FOK_None)
13409             if (FunctionTemplateDecl *FT =
13410                                        D->getInstantiatedFromMemberTemplate()) {
13411               if (FT->isThisDeclarationADefinition()) {
13412                 Definition = D->getTemplatedDecl();
13413                 break;
13414               }
13415             }
13416         }
13417       }
13418     }
13419 
13420   if (!Definition)
13421     return;
13422 
13423   if (canRedefineFunction(Definition, getLangOpts()))
13424     return;
13425 
13426   // Don't emit an error when this is redefinition of a typo-corrected
13427   // definition.
13428   if (TypoCorrectedFunctionDefinitions.count(Definition))
13429     return;
13430 
13431   // If we don't have a visible definition of the function, and it's inline or
13432   // a template, skip the new definition.
13433   if (SkipBody && !hasVisibleDefinition(Definition) &&
13434       (Definition->getFormalLinkage() == InternalLinkage ||
13435        Definition->isInlined() ||
13436        Definition->getDescribedFunctionTemplate() ||
13437        Definition->getNumTemplateParameterLists())) {
13438     SkipBody->ShouldSkip = true;
13439     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13440     if (auto *TD = Definition->getDescribedFunctionTemplate())
13441       makeMergedDefinitionVisible(TD);
13442     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13443     return;
13444   }
13445 
13446   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13447       Definition->getStorageClass() == SC_Extern)
13448     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13449         << FD->getDeclName() << getLangOpts().CPlusPlus;
13450   else
13451     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13452 
13453   Diag(Definition->getLocation(), diag::note_previous_definition);
13454   FD->setInvalidDecl();
13455 }
13456 
13457 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13458                                    Sema &S) {
13459   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13460 
13461   LambdaScopeInfo *LSI = S.PushLambdaScope();
13462   LSI->CallOperator = CallOperator;
13463   LSI->Lambda = LambdaClass;
13464   LSI->ReturnType = CallOperator->getReturnType();
13465   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13466 
13467   if (LCD == LCD_None)
13468     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13469   else if (LCD == LCD_ByCopy)
13470     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13471   else if (LCD == LCD_ByRef)
13472     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13473   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13474 
13475   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13476   LSI->Mutable = !CallOperator->isConst();
13477 
13478   // Add the captures to the LSI so they can be noted as already
13479   // captured within tryCaptureVar.
13480   auto I = LambdaClass->field_begin();
13481   for (const auto &C : LambdaClass->captures()) {
13482     if (C.capturesVariable()) {
13483       VarDecl *VD = C.getCapturedVar();
13484       if (VD->isInitCapture())
13485         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13486       QualType CaptureType = VD->getType();
13487       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13488       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13489           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13490           /*EllipsisLoc*/C.isPackExpansion()
13491                          ? C.getEllipsisLoc() : SourceLocation(),
13492           CaptureType, /*Invalid*/false);
13493 
13494     } else if (C.capturesThis()) {
13495       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13496                           C.getCaptureKind() == LCK_StarThis);
13497     } else {
13498       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13499                              I->getType());
13500     }
13501     ++I;
13502   }
13503 }
13504 
13505 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13506                                     SkipBodyInfo *SkipBody) {
13507   if (!D) {
13508     // Parsing the function declaration failed in some way. Push on a fake scope
13509     // anyway so we can try to parse the function body.
13510     PushFunctionScope();
13511     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13512     return D;
13513   }
13514 
13515   FunctionDecl *FD = nullptr;
13516 
13517   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13518     FD = FunTmpl->getTemplatedDecl();
13519   else
13520     FD = cast<FunctionDecl>(D);
13521 
13522   // Do not push if it is a lambda because one is already pushed when building
13523   // the lambda in ActOnStartOfLambdaDefinition().
13524   if (!isLambdaCallOperator(FD))
13525     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13526 
13527   // Check for defining attributes before the check for redefinition.
13528   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13529     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13530     FD->dropAttr<AliasAttr>();
13531     FD->setInvalidDecl();
13532   }
13533   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13534     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13535     FD->dropAttr<IFuncAttr>();
13536     FD->setInvalidDecl();
13537   }
13538 
13539   // See if this is a redefinition. If 'will have body' is already set, then
13540   // these checks were already performed when it was set.
13541   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13542     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13543 
13544     // If we're skipping the body, we're done. Don't enter the scope.
13545     if (SkipBody && SkipBody->ShouldSkip)
13546       return D;
13547   }
13548 
13549   // Mark this function as "will have a body eventually".  This lets users to
13550   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13551   // this function.
13552   FD->setWillHaveBody();
13553 
13554   // If we are instantiating a generic lambda call operator, push
13555   // a LambdaScopeInfo onto the function stack.  But use the information
13556   // that's already been calculated (ActOnLambdaExpr) to prime the current
13557   // LambdaScopeInfo.
13558   // When the template operator is being specialized, the LambdaScopeInfo,
13559   // has to be properly restored so that tryCaptureVariable doesn't try
13560   // and capture any new variables. In addition when calculating potential
13561   // captures during transformation of nested lambdas, it is necessary to
13562   // have the LSI properly restored.
13563   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13564     assert(inTemplateInstantiation() &&
13565            "There should be an active template instantiation on the stack "
13566            "when instantiating a generic lambda!");
13567     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13568   } else {
13569     // Enter a new function scope
13570     PushFunctionScope();
13571   }
13572 
13573   // Builtin functions cannot be defined.
13574   if (unsigned BuiltinID = FD->getBuiltinID()) {
13575     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13576         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13577       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13578       FD->setInvalidDecl();
13579     }
13580   }
13581 
13582   // The return type of a function definition must be complete
13583   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13584   QualType ResultType = FD->getReturnType();
13585   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13586       !FD->isInvalidDecl() &&
13587       RequireCompleteType(FD->getLocation(), ResultType,
13588                           diag::err_func_def_incomplete_result))
13589     FD->setInvalidDecl();
13590 
13591   if (FnBodyScope)
13592     PushDeclContext(FnBodyScope, FD);
13593 
13594   // Check the validity of our function parameters
13595   CheckParmsForFunctionDef(FD->parameters(),
13596                            /*CheckParameterNames=*/true);
13597 
13598   // Add non-parameter declarations already in the function to the current
13599   // scope.
13600   if (FnBodyScope) {
13601     for (Decl *NPD : FD->decls()) {
13602       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13603       if (!NonParmDecl)
13604         continue;
13605       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13606              "parameters should not be in newly created FD yet");
13607 
13608       // If the decl has a name, make it accessible in the current scope.
13609       if (NonParmDecl->getDeclName())
13610         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13611 
13612       // Similarly, dive into enums and fish their constants out, making them
13613       // accessible in this scope.
13614       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13615         for (auto *EI : ED->enumerators())
13616           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13617       }
13618     }
13619   }
13620 
13621   // Introduce our parameters into the function scope
13622   for (auto Param : FD->parameters()) {
13623     Param->setOwningFunction(FD);
13624 
13625     // If this has an identifier, add it to the scope stack.
13626     if (Param->getIdentifier() && FnBodyScope) {
13627       CheckShadow(FnBodyScope, Param);
13628 
13629       PushOnScopeChains(Param, FnBodyScope);
13630     }
13631   }
13632 
13633   // Ensure that the function's exception specification is instantiated.
13634   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13635     ResolveExceptionSpec(D->getLocation(), FPT);
13636 
13637   // dllimport cannot be applied to non-inline function definitions.
13638   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13639       !FD->isTemplateInstantiation()) {
13640     assert(!FD->hasAttr<DLLExportAttr>());
13641     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13642     FD->setInvalidDecl();
13643     return D;
13644   }
13645   // We want to attach documentation to original Decl (which might be
13646   // a function template).
13647   ActOnDocumentableDecl(D);
13648   if (getCurLexicalContext()->isObjCContainer() &&
13649       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13650       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13651     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13652 
13653   return D;
13654 }
13655 
13656 /// Given the set of return statements within a function body,
13657 /// compute the variables that are subject to the named return value
13658 /// optimization.
13659 ///
13660 /// Each of the variables that is subject to the named return value
13661 /// optimization will be marked as NRVO variables in the AST, and any
13662 /// return statement that has a marked NRVO variable as its NRVO candidate can
13663 /// use the named return value optimization.
13664 ///
13665 /// This function applies a very simplistic algorithm for NRVO: if every return
13666 /// statement in the scope of a variable has the same NRVO candidate, that
13667 /// candidate is an NRVO variable.
13668 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13669   ReturnStmt **Returns = Scope->Returns.data();
13670 
13671   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13672     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13673       if (!NRVOCandidate->isNRVOVariable())
13674         Returns[I]->setNRVOCandidate(nullptr);
13675     }
13676   }
13677 }
13678 
13679 bool Sema::canDelayFunctionBody(const Declarator &D) {
13680   // We can't delay parsing the body of a constexpr function template (yet).
13681   if (D.getDeclSpec().hasConstexprSpecifier())
13682     return false;
13683 
13684   // We can't delay parsing the body of a function template with a deduced
13685   // return type (yet).
13686   if (D.getDeclSpec().hasAutoTypeSpec()) {
13687     // If the placeholder introduces a non-deduced trailing return type,
13688     // we can still delay parsing it.
13689     if (D.getNumTypeObjects()) {
13690       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13691       if (Outer.Kind == DeclaratorChunk::Function &&
13692           Outer.Fun.hasTrailingReturnType()) {
13693         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13694         return Ty.isNull() || !Ty->isUndeducedType();
13695       }
13696     }
13697     return false;
13698   }
13699 
13700   return true;
13701 }
13702 
13703 bool Sema::canSkipFunctionBody(Decl *D) {
13704   // We cannot skip the body of a function (or function template) which is
13705   // constexpr, since we may need to evaluate its body in order to parse the
13706   // rest of the file.
13707   // We cannot skip the body of a function with an undeduced return type,
13708   // because any callers of that function need to know the type.
13709   if (const FunctionDecl *FD = D->getAsFunction()) {
13710     if (FD->isConstexpr())
13711       return false;
13712     // We can't simply call Type::isUndeducedType here, because inside template
13713     // auto can be deduced to a dependent type, which is not considered
13714     // "undeduced".
13715     if (FD->getReturnType()->getContainedDeducedType())
13716       return false;
13717   }
13718   return Consumer.shouldSkipFunctionBody(D);
13719 }
13720 
13721 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13722   if (!Decl)
13723     return nullptr;
13724   if (FunctionDecl *FD = Decl->getAsFunction())
13725     FD->setHasSkippedBody();
13726   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13727     MD->setHasSkippedBody();
13728   return Decl;
13729 }
13730 
13731 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13732   return ActOnFinishFunctionBody(D, BodyArg, false);
13733 }
13734 
13735 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13736 /// body.
13737 class ExitFunctionBodyRAII {
13738 public:
13739   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13740   ~ExitFunctionBodyRAII() {
13741     if (!IsLambda)
13742       S.PopExpressionEvaluationContext();
13743   }
13744 
13745 private:
13746   Sema &S;
13747   bool IsLambda = false;
13748 };
13749 
13750 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13751   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13752 
13753   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13754     if (EscapeInfo.count(BD))
13755       return EscapeInfo[BD];
13756 
13757     bool R = false;
13758     const BlockDecl *CurBD = BD;
13759 
13760     do {
13761       R = !CurBD->doesNotEscape();
13762       if (R)
13763         break;
13764       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13765     } while (CurBD);
13766 
13767     return EscapeInfo[BD] = R;
13768   };
13769 
13770   // If the location where 'self' is implicitly retained is inside a escaping
13771   // block, emit a diagnostic.
13772   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13773        S.ImplicitlyRetainedSelfLocs)
13774     if (IsOrNestedInEscapingBlock(P.second))
13775       S.Diag(P.first, diag::warn_implicitly_retains_self)
13776           << FixItHint::CreateInsertion(P.first, "self->");
13777 }
13778 
13779 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13780                                     bool IsInstantiation) {
13781   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13782 
13783   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13784   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13785 
13786   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13787     CheckCompletedCoroutineBody(FD, Body);
13788 
13789   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13790   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13791   // meant to pop the context added in ActOnStartOfFunctionDef().
13792   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13793 
13794   if (FD) {
13795     FD->setBody(Body);
13796     FD->setWillHaveBody(false);
13797 
13798     if (getLangOpts().CPlusPlus14) {
13799       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13800           FD->getReturnType()->isUndeducedType()) {
13801         // If the function has a deduced result type but contains no 'return'
13802         // statements, the result type as written must be exactly 'auto', and
13803         // the deduced result type is 'void'.
13804         if (!FD->getReturnType()->getAs<AutoType>()) {
13805           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13806               << FD->getReturnType();
13807           FD->setInvalidDecl();
13808         } else {
13809           // Substitute 'void' for the 'auto' in the type.
13810           TypeLoc ResultType = getReturnTypeLoc(FD);
13811           Context.adjustDeducedFunctionResultType(
13812               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13813         }
13814       }
13815     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13816       // In C++11, we don't use 'auto' deduction rules for lambda call
13817       // operators because we don't support return type deduction.
13818       auto *LSI = getCurLambda();
13819       if (LSI->HasImplicitReturnType) {
13820         deduceClosureReturnType(*LSI);
13821 
13822         // C++11 [expr.prim.lambda]p4:
13823         //   [...] if there are no return statements in the compound-statement
13824         //   [the deduced type is] the type void
13825         QualType RetType =
13826             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13827 
13828         // Update the return type to the deduced type.
13829         const FunctionProtoType *Proto =
13830             FD->getType()->getAs<FunctionProtoType>();
13831         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13832                                             Proto->getExtProtoInfo()));
13833       }
13834     }
13835 
13836     // If the function implicitly returns zero (like 'main') or is naked,
13837     // don't complain about missing return statements.
13838     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13839       WP.disableCheckFallThrough();
13840 
13841     // MSVC permits the use of pure specifier (=0) on function definition,
13842     // defined at class scope, warn about this non-standard construct.
13843     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13844       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13845 
13846     if (!FD->isInvalidDecl()) {
13847       // Don't diagnose unused parameters of defaulted or deleted functions.
13848       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13849         DiagnoseUnusedParameters(FD->parameters());
13850       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13851                                              FD->getReturnType(), FD);
13852 
13853       // If this is a structor, we need a vtable.
13854       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13855         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13856       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13857         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13858 
13859       // Try to apply the named return value optimization. We have to check
13860       // if we can do this here because lambdas keep return statements around
13861       // to deduce an implicit return type.
13862       if (FD->getReturnType()->isRecordType() &&
13863           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13864         computeNRVO(Body, getCurFunction());
13865     }
13866 
13867     // GNU warning -Wmissing-prototypes:
13868     //   Warn if a global function is defined without a previous
13869     //   prototype declaration. This warning is issued even if the
13870     //   definition itself provides a prototype. The aim is to detect
13871     //   global functions that fail to be declared in header files.
13872     const FunctionDecl *PossiblePrototype = nullptr;
13873     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13874       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13875 
13876       if (PossiblePrototype) {
13877         // We found a declaration that is not a prototype,
13878         // but that could be a zero-parameter prototype
13879         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13880           TypeLoc TL = TI->getTypeLoc();
13881           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13882             Diag(PossiblePrototype->getLocation(),
13883                  diag::note_declaration_not_a_prototype)
13884                 << (FD->getNumParams() != 0)
13885                 << (FD->getNumParams() == 0
13886                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13887                         : FixItHint{});
13888         }
13889       } else {
13890         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13891             << /* function */ 1
13892             << (FD->getStorageClass() == SC_None
13893                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13894                                                  "static ")
13895                     : FixItHint{});
13896       }
13897 
13898       // GNU warning -Wstrict-prototypes
13899       //   Warn if K&R function is defined without a previous declaration.
13900       //   This warning is issued only if the definition itself does not provide
13901       //   a prototype. Only K&R definitions do not provide a prototype.
13902       //   An empty list in a function declarator that is part of a definition
13903       //   of that function specifies that the function has no parameters
13904       //   (C99 6.7.5.3p14)
13905       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13906           !LangOpts.CPlusPlus) {
13907         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13908         TypeLoc TL = TI->getTypeLoc();
13909         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13910         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13911       }
13912     }
13913 
13914     // Warn on CPUDispatch with an actual body.
13915     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13916       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13917         if (!CmpndBody->body_empty())
13918           Diag(CmpndBody->body_front()->getBeginLoc(),
13919                diag::warn_dispatch_body_ignored);
13920 
13921     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13922       const CXXMethodDecl *KeyFunction;
13923       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13924           MD->isVirtual() &&
13925           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13926           MD == KeyFunction->getCanonicalDecl()) {
13927         // Update the key-function state if necessary for this ABI.
13928         if (FD->isInlined() &&
13929             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13930           Context.setNonKeyFunction(MD);
13931 
13932           // If the newly-chosen key function is already defined, then we
13933           // need to mark the vtable as used retroactively.
13934           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13935           const FunctionDecl *Definition;
13936           if (KeyFunction && KeyFunction->isDefined(Definition))
13937             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13938         } else {
13939           // We just defined they key function; mark the vtable as used.
13940           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13941         }
13942       }
13943     }
13944 
13945     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13946            "Function parsing confused");
13947   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13948     assert(MD == getCurMethodDecl() && "Method parsing confused");
13949     MD->setBody(Body);
13950     if (!MD->isInvalidDecl()) {
13951       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13952                                              MD->getReturnType(), MD);
13953 
13954       if (Body)
13955         computeNRVO(Body, getCurFunction());
13956     }
13957     if (getCurFunction()->ObjCShouldCallSuper) {
13958       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13959           << MD->getSelector().getAsString();
13960       getCurFunction()->ObjCShouldCallSuper = false;
13961     }
13962     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13963       const ObjCMethodDecl *InitMethod = nullptr;
13964       bool isDesignated =
13965           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13966       assert(isDesignated && InitMethod);
13967       (void)isDesignated;
13968 
13969       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13970         auto IFace = MD->getClassInterface();
13971         if (!IFace)
13972           return false;
13973         auto SuperD = IFace->getSuperClass();
13974         if (!SuperD)
13975           return false;
13976         return SuperD->getIdentifier() ==
13977             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13978       };
13979       // Don't issue this warning for unavailable inits or direct subclasses
13980       // of NSObject.
13981       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13982         Diag(MD->getLocation(),
13983              diag::warn_objc_designated_init_missing_super_call);
13984         Diag(InitMethod->getLocation(),
13985              diag::note_objc_designated_init_marked_here);
13986       }
13987       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13988     }
13989     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13990       // Don't issue this warning for unavaialable inits.
13991       if (!MD->isUnavailable())
13992         Diag(MD->getLocation(),
13993              diag::warn_objc_secondary_init_missing_init_call);
13994       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13995     }
13996 
13997     diagnoseImplicitlyRetainedSelf(*this);
13998   } else {
13999     // Parsing the function declaration failed in some way. Pop the fake scope
14000     // we pushed on.
14001     PopFunctionScopeInfo(ActivePolicy, dcl);
14002     return nullptr;
14003   }
14004 
14005   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14006     DiagnoseUnguardedAvailabilityViolations(dcl);
14007 
14008   assert(!getCurFunction()->ObjCShouldCallSuper &&
14009          "This should only be set for ObjC methods, which should have been "
14010          "handled in the block above.");
14011 
14012   // Verify and clean out per-function state.
14013   if (Body && (!FD || !FD->isDefaulted())) {
14014     // C++ constructors that have function-try-blocks can't have return
14015     // statements in the handlers of that block. (C++ [except.handle]p14)
14016     // Verify this.
14017     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14018       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14019 
14020     // Verify that gotos and switch cases don't jump into scopes illegally.
14021     if (getCurFunction()->NeedsScopeChecking() &&
14022         !PP.isCodeCompletionEnabled())
14023       DiagnoseInvalidJumps(Body);
14024 
14025     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14026       if (!Destructor->getParent()->isDependentType())
14027         CheckDestructor(Destructor);
14028 
14029       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14030                                              Destructor->getParent());
14031     }
14032 
14033     // If any errors have occurred, clear out any temporaries that may have
14034     // been leftover. This ensures that these temporaries won't be picked up for
14035     // deletion in some later function.
14036     if (getDiagnostics().hasErrorOccurred() ||
14037         getDiagnostics().getSuppressAllDiagnostics()) {
14038       DiscardCleanupsInEvaluationContext();
14039     }
14040     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14041         !isa<FunctionTemplateDecl>(dcl)) {
14042       // Since the body is valid, issue any analysis-based warnings that are
14043       // enabled.
14044       ActivePolicy = &WP;
14045     }
14046 
14047     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14048         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14049       FD->setInvalidDecl();
14050 
14051     if (FD && FD->hasAttr<NakedAttr>()) {
14052       for (const Stmt *S : Body->children()) {
14053         // Allow local register variables without initializer as they don't
14054         // require prologue.
14055         bool RegisterVariables = false;
14056         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14057           for (const auto *Decl : DS->decls()) {
14058             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14059               RegisterVariables =
14060                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14061               if (!RegisterVariables)
14062                 break;
14063             }
14064           }
14065         }
14066         if (RegisterVariables)
14067           continue;
14068         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14069           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14070           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14071           FD->setInvalidDecl();
14072           break;
14073         }
14074       }
14075     }
14076 
14077     assert(ExprCleanupObjects.size() ==
14078                ExprEvalContexts.back().NumCleanupObjects &&
14079            "Leftover temporaries in function");
14080     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14081     assert(MaybeODRUseExprs.empty() &&
14082            "Leftover expressions for odr-use checking");
14083   }
14084 
14085   if (!IsInstantiation)
14086     PopDeclContext();
14087 
14088   PopFunctionScopeInfo(ActivePolicy, dcl);
14089   // If any errors have occurred, clear out any temporaries that may have
14090   // been leftover. This ensures that these temporaries won't be picked up for
14091   // deletion in some later function.
14092   if (getDiagnostics().hasErrorOccurred()) {
14093     DiscardCleanupsInEvaluationContext();
14094   }
14095 
14096   return dcl;
14097 }
14098 
14099 /// When we finish delayed parsing of an attribute, we must attach it to the
14100 /// relevant Decl.
14101 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14102                                        ParsedAttributes &Attrs) {
14103   // Always attach attributes to the underlying decl.
14104   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14105     D = TD->getTemplatedDecl();
14106   ProcessDeclAttributeList(S, D, Attrs);
14107 
14108   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14109     if (Method->isStatic())
14110       checkThisInStaticMemberFunctionAttributes(Method);
14111 }
14112 
14113 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14114 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14115 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14116                                           IdentifierInfo &II, Scope *S) {
14117   // Find the scope in which the identifier is injected and the corresponding
14118   // DeclContext.
14119   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14120   // In that case, we inject the declaration into the translation unit scope
14121   // instead.
14122   Scope *BlockScope = S;
14123   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14124     BlockScope = BlockScope->getParent();
14125 
14126   Scope *ContextScope = BlockScope;
14127   while (!ContextScope->getEntity())
14128     ContextScope = ContextScope->getParent();
14129   ContextRAII SavedContext(*this, ContextScope->getEntity());
14130 
14131   // Before we produce a declaration for an implicitly defined
14132   // function, see whether there was a locally-scoped declaration of
14133   // this name as a function or variable. If so, use that
14134   // (non-visible) declaration, and complain about it.
14135   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14136   if (ExternCPrev) {
14137     // We still need to inject the function into the enclosing block scope so
14138     // that later (non-call) uses can see it.
14139     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14140 
14141     // C89 footnote 38:
14142     //   If in fact it is not defined as having type "function returning int",
14143     //   the behavior is undefined.
14144     if (!isa<FunctionDecl>(ExternCPrev) ||
14145         !Context.typesAreCompatible(
14146             cast<FunctionDecl>(ExternCPrev)->getType(),
14147             Context.getFunctionNoProtoType(Context.IntTy))) {
14148       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14149           << ExternCPrev << !getLangOpts().C99;
14150       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14151       return ExternCPrev;
14152     }
14153   }
14154 
14155   // Extension in C99.  Legal in C90, but warn about it.
14156   unsigned diag_id;
14157   if (II.getName().startswith("__builtin_"))
14158     diag_id = diag::warn_builtin_unknown;
14159   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14160   else if (getLangOpts().OpenCL)
14161     diag_id = diag::err_opencl_implicit_function_decl;
14162   else if (getLangOpts().C99)
14163     diag_id = diag::ext_implicit_function_decl;
14164   else
14165     diag_id = diag::warn_implicit_function_decl;
14166   Diag(Loc, diag_id) << &II;
14167 
14168   // If we found a prior declaration of this function, don't bother building
14169   // another one. We've already pushed that one into scope, so there's nothing
14170   // more to do.
14171   if (ExternCPrev)
14172     return ExternCPrev;
14173 
14174   // Because typo correction is expensive, only do it if the implicit
14175   // function declaration is going to be treated as an error.
14176   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14177     TypoCorrection Corrected;
14178     DeclFilterCCC<FunctionDecl> CCC{};
14179     if (S && (Corrected =
14180                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14181                               S, nullptr, CCC, CTK_NonError)))
14182       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14183                    /*ErrorRecovery*/false);
14184   }
14185 
14186   // Set a Declarator for the implicit definition: int foo();
14187   const char *Dummy;
14188   AttributeFactory attrFactory;
14189   DeclSpec DS(attrFactory);
14190   unsigned DiagID;
14191   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14192                                   Context.getPrintingPolicy());
14193   (void)Error; // Silence warning.
14194   assert(!Error && "Error setting up implicit decl!");
14195   SourceLocation NoLoc;
14196   Declarator D(DS, DeclaratorContext::BlockContext);
14197   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14198                                              /*IsAmbiguous=*/false,
14199                                              /*LParenLoc=*/NoLoc,
14200                                              /*Params=*/nullptr,
14201                                              /*NumParams=*/0,
14202                                              /*EllipsisLoc=*/NoLoc,
14203                                              /*RParenLoc=*/NoLoc,
14204                                              /*RefQualifierIsLvalueRef=*/true,
14205                                              /*RefQualifierLoc=*/NoLoc,
14206                                              /*MutableLoc=*/NoLoc, EST_None,
14207                                              /*ESpecRange=*/SourceRange(),
14208                                              /*Exceptions=*/nullptr,
14209                                              /*ExceptionRanges=*/nullptr,
14210                                              /*NumExceptions=*/0,
14211                                              /*NoexceptExpr=*/nullptr,
14212                                              /*ExceptionSpecTokens=*/nullptr,
14213                                              /*DeclsInPrototype=*/None, Loc,
14214                                              Loc, D),
14215                 std::move(DS.getAttributes()), SourceLocation());
14216   D.SetIdentifier(&II, Loc);
14217 
14218   // Insert this function into the enclosing block scope.
14219   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14220   FD->setImplicit();
14221 
14222   AddKnownFunctionAttributes(FD);
14223 
14224   return FD;
14225 }
14226 
14227 /// Adds any function attributes that we know a priori based on
14228 /// the declaration of this function.
14229 ///
14230 /// These attributes can apply both to implicitly-declared builtins
14231 /// (like __builtin___printf_chk) or to library-declared functions
14232 /// like NSLog or printf.
14233 ///
14234 /// We need to check for duplicate attributes both here and where user-written
14235 /// attributes are applied to declarations.
14236 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14237   if (FD->isInvalidDecl())
14238     return;
14239 
14240   // If this is a built-in function, map its builtin attributes to
14241   // actual attributes.
14242   if (unsigned BuiltinID = FD->getBuiltinID()) {
14243     // Handle printf-formatting attributes.
14244     unsigned FormatIdx;
14245     bool HasVAListArg;
14246     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14247       if (!FD->hasAttr<FormatAttr>()) {
14248         const char *fmt = "printf";
14249         unsigned int NumParams = FD->getNumParams();
14250         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14251             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14252           fmt = "NSString";
14253         FD->addAttr(FormatAttr::CreateImplicit(Context,
14254                                                &Context.Idents.get(fmt),
14255                                                FormatIdx+1,
14256                                                HasVAListArg ? 0 : FormatIdx+2,
14257                                                FD->getLocation()));
14258       }
14259     }
14260     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14261                                              HasVAListArg)) {
14262      if (!FD->hasAttr<FormatAttr>())
14263        FD->addAttr(FormatAttr::CreateImplicit(Context,
14264                                               &Context.Idents.get("scanf"),
14265                                               FormatIdx+1,
14266                                               HasVAListArg ? 0 : FormatIdx+2,
14267                                               FD->getLocation()));
14268     }
14269 
14270     // Handle automatically recognized callbacks.
14271     SmallVector<int, 4> Encoding;
14272     if (!FD->hasAttr<CallbackAttr>() &&
14273         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14274       FD->addAttr(CallbackAttr::CreateImplicit(
14275           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14276 
14277     // Mark const if we don't care about errno and that is the only thing
14278     // preventing the function from being const. This allows IRgen to use LLVM
14279     // intrinsics for such functions.
14280     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14281         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14282       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14283 
14284     // We make "fma" on some platforms const because we know it does not set
14285     // errno in those environments even though it could set errno based on the
14286     // C standard.
14287     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14288     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14289         !FD->hasAttr<ConstAttr>()) {
14290       switch (BuiltinID) {
14291       case Builtin::BI__builtin_fma:
14292       case Builtin::BI__builtin_fmaf:
14293       case Builtin::BI__builtin_fmal:
14294       case Builtin::BIfma:
14295       case Builtin::BIfmaf:
14296       case Builtin::BIfmal:
14297         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14298         break;
14299       default:
14300         break;
14301       }
14302     }
14303 
14304     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14305         !FD->hasAttr<ReturnsTwiceAttr>())
14306       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14307                                          FD->getLocation()));
14308     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14309       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14310     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14311       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14312     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14313       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14314     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14315         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14316       // Add the appropriate attribute, depending on the CUDA compilation mode
14317       // and which target the builtin belongs to. For example, during host
14318       // compilation, aux builtins are __device__, while the rest are __host__.
14319       if (getLangOpts().CUDAIsDevice !=
14320           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14321         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14322       else
14323         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14324     }
14325   }
14326 
14327   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14328   // throw, add an implicit nothrow attribute to any extern "C" function we come
14329   // across.
14330   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14331       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14332     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14333     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14334       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14335   }
14336 
14337   IdentifierInfo *Name = FD->getIdentifier();
14338   if (!Name)
14339     return;
14340   if ((!getLangOpts().CPlusPlus &&
14341        FD->getDeclContext()->isTranslationUnit()) ||
14342       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14343        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14344        LinkageSpecDecl::lang_c)) {
14345     // Okay: this could be a libc/libm/Objective-C function we know
14346     // about.
14347   } else
14348     return;
14349 
14350   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14351     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14352     // target-specific builtins, perhaps?
14353     if (!FD->hasAttr<FormatAttr>())
14354       FD->addAttr(FormatAttr::CreateImplicit(Context,
14355                                              &Context.Idents.get("printf"), 2,
14356                                              Name->isStr("vasprintf") ? 0 : 3,
14357                                              FD->getLocation()));
14358   }
14359 
14360   if (Name->isStr("__CFStringMakeConstantString")) {
14361     // We already have a __builtin___CFStringMakeConstantString,
14362     // but builds that use -fno-constant-cfstrings don't go through that.
14363     if (!FD->hasAttr<FormatArgAttr>())
14364       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14365                                                 FD->getLocation()));
14366   }
14367 }
14368 
14369 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14370                                     TypeSourceInfo *TInfo) {
14371   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14372   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14373 
14374   if (!TInfo) {
14375     assert(D.isInvalidType() && "no declarator info for valid type");
14376     TInfo = Context.getTrivialTypeSourceInfo(T);
14377   }
14378 
14379   // Scope manipulation handled by caller.
14380   TypedefDecl *NewTD =
14381       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14382                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14383 
14384   // Bail out immediately if we have an invalid declaration.
14385   if (D.isInvalidType()) {
14386     NewTD->setInvalidDecl();
14387     return NewTD;
14388   }
14389 
14390   if (D.getDeclSpec().isModulePrivateSpecified()) {
14391     if (CurContext->isFunctionOrMethod())
14392       Diag(NewTD->getLocation(), diag::err_module_private_local)
14393         << 2 << NewTD->getDeclName()
14394         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14395         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14396     else
14397       NewTD->setModulePrivate();
14398   }
14399 
14400   // C++ [dcl.typedef]p8:
14401   //   If the typedef declaration defines an unnamed class (or
14402   //   enum), the first typedef-name declared by the declaration
14403   //   to be that class type (or enum type) is used to denote the
14404   //   class type (or enum type) for linkage purposes only.
14405   // We need to check whether the type was declared in the declaration.
14406   switch (D.getDeclSpec().getTypeSpecType()) {
14407   case TST_enum:
14408   case TST_struct:
14409   case TST_interface:
14410   case TST_union:
14411   case TST_class: {
14412     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14413     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14414     break;
14415   }
14416 
14417   default:
14418     break;
14419   }
14420 
14421   return NewTD;
14422 }
14423 
14424 /// Check that this is a valid underlying type for an enum declaration.
14425 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14426   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14427   QualType T = TI->getType();
14428 
14429   if (T->isDependentType())
14430     return false;
14431 
14432   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14433     if (BT->isInteger())
14434       return false;
14435 
14436   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14437   return true;
14438 }
14439 
14440 /// Check whether this is a valid redeclaration of a previous enumeration.
14441 /// \return true if the redeclaration was invalid.
14442 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14443                                   QualType EnumUnderlyingTy, bool IsFixed,
14444                                   const EnumDecl *Prev) {
14445   if (IsScoped != Prev->isScoped()) {
14446     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14447       << Prev->isScoped();
14448     Diag(Prev->getLocation(), diag::note_previous_declaration);
14449     return true;
14450   }
14451 
14452   if (IsFixed && Prev->isFixed()) {
14453     if (!EnumUnderlyingTy->isDependentType() &&
14454         !Prev->getIntegerType()->isDependentType() &&
14455         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14456                                         Prev->getIntegerType())) {
14457       // TODO: Highlight the underlying type of the redeclaration.
14458       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14459         << EnumUnderlyingTy << Prev->getIntegerType();
14460       Diag(Prev->getLocation(), diag::note_previous_declaration)
14461           << Prev->getIntegerTypeRange();
14462       return true;
14463     }
14464   } else if (IsFixed != Prev->isFixed()) {
14465     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14466       << Prev->isFixed();
14467     Diag(Prev->getLocation(), diag::note_previous_declaration);
14468     return true;
14469   }
14470 
14471   return false;
14472 }
14473 
14474 /// Get diagnostic %select index for tag kind for
14475 /// redeclaration diagnostic message.
14476 /// WARNING: Indexes apply to particular diagnostics only!
14477 ///
14478 /// \returns diagnostic %select index.
14479 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14480   switch (Tag) {
14481   case TTK_Struct: return 0;
14482   case TTK_Interface: return 1;
14483   case TTK_Class:  return 2;
14484   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14485   }
14486 }
14487 
14488 /// Determine if tag kind is a class-key compatible with
14489 /// class for redeclaration (class, struct, or __interface).
14490 ///
14491 /// \returns true iff the tag kind is compatible.
14492 static bool isClassCompatTagKind(TagTypeKind Tag)
14493 {
14494   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14495 }
14496 
14497 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14498                                              TagTypeKind TTK) {
14499   if (isa<TypedefDecl>(PrevDecl))
14500     return NTK_Typedef;
14501   else if (isa<TypeAliasDecl>(PrevDecl))
14502     return NTK_TypeAlias;
14503   else if (isa<ClassTemplateDecl>(PrevDecl))
14504     return NTK_Template;
14505   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14506     return NTK_TypeAliasTemplate;
14507   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14508     return NTK_TemplateTemplateArgument;
14509   switch (TTK) {
14510   case TTK_Struct:
14511   case TTK_Interface:
14512   case TTK_Class:
14513     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14514   case TTK_Union:
14515     return NTK_NonUnion;
14516   case TTK_Enum:
14517     return NTK_NonEnum;
14518   }
14519   llvm_unreachable("invalid TTK");
14520 }
14521 
14522 /// Determine whether a tag with a given kind is acceptable
14523 /// as a redeclaration of the given tag declaration.
14524 ///
14525 /// \returns true if the new tag kind is acceptable, false otherwise.
14526 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14527                                         TagTypeKind NewTag, bool isDefinition,
14528                                         SourceLocation NewTagLoc,
14529                                         const IdentifierInfo *Name) {
14530   // C++ [dcl.type.elab]p3:
14531   //   The class-key or enum keyword present in the
14532   //   elaborated-type-specifier shall agree in kind with the
14533   //   declaration to which the name in the elaborated-type-specifier
14534   //   refers. This rule also applies to the form of
14535   //   elaborated-type-specifier that declares a class-name or
14536   //   friend class since it can be construed as referring to the
14537   //   definition of the class. Thus, in any
14538   //   elaborated-type-specifier, the enum keyword shall be used to
14539   //   refer to an enumeration (7.2), the union class-key shall be
14540   //   used to refer to a union (clause 9), and either the class or
14541   //   struct class-key shall be used to refer to a class (clause 9)
14542   //   declared using the class or struct class-key.
14543   TagTypeKind OldTag = Previous->getTagKind();
14544   if (OldTag != NewTag &&
14545       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14546     return false;
14547 
14548   // Tags are compatible, but we might still want to warn on mismatched tags.
14549   // Non-class tags can't be mismatched at this point.
14550   if (!isClassCompatTagKind(NewTag))
14551     return true;
14552 
14553   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14554   // by our warning analysis. We don't want to warn about mismatches with (eg)
14555   // declarations in system headers that are designed to be specialized, but if
14556   // a user asks us to warn, we should warn if their code contains mismatched
14557   // declarations.
14558   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14559     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14560                                       Loc);
14561   };
14562   if (IsIgnoredLoc(NewTagLoc))
14563     return true;
14564 
14565   auto IsIgnored = [&](const TagDecl *Tag) {
14566     return IsIgnoredLoc(Tag->getLocation());
14567   };
14568   while (IsIgnored(Previous)) {
14569     Previous = Previous->getPreviousDecl();
14570     if (!Previous)
14571       return true;
14572     OldTag = Previous->getTagKind();
14573   }
14574 
14575   bool isTemplate = false;
14576   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14577     isTemplate = Record->getDescribedClassTemplate();
14578 
14579   if (inTemplateInstantiation()) {
14580     if (OldTag != NewTag) {
14581       // In a template instantiation, do not offer fix-its for tag mismatches
14582       // since they usually mess up the template instead of fixing the problem.
14583       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14584         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14585         << getRedeclDiagFromTagKind(OldTag);
14586       // FIXME: Note previous location?
14587     }
14588     return true;
14589   }
14590 
14591   if (isDefinition) {
14592     // On definitions, check all previous tags and issue a fix-it for each
14593     // one that doesn't match the current tag.
14594     if (Previous->getDefinition()) {
14595       // Don't suggest fix-its for redefinitions.
14596       return true;
14597     }
14598 
14599     bool previousMismatch = false;
14600     for (const TagDecl *I : Previous->redecls()) {
14601       if (I->getTagKind() != NewTag) {
14602         // Ignore previous declarations for which the warning was disabled.
14603         if (IsIgnored(I))
14604           continue;
14605 
14606         if (!previousMismatch) {
14607           previousMismatch = true;
14608           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14609             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14610             << getRedeclDiagFromTagKind(I->getTagKind());
14611         }
14612         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14613           << getRedeclDiagFromTagKind(NewTag)
14614           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14615                TypeWithKeyword::getTagTypeKindName(NewTag));
14616       }
14617     }
14618     return true;
14619   }
14620 
14621   // Identify the prevailing tag kind: this is the kind of the definition (if
14622   // there is a non-ignored definition), or otherwise the kind of the prior
14623   // (non-ignored) declaration.
14624   const TagDecl *PrevDef = Previous->getDefinition();
14625   if (PrevDef && IsIgnored(PrevDef))
14626     PrevDef = nullptr;
14627   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14628   if (Redecl->getTagKind() != NewTag) {
14629     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14630       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14631       << getRedeclDiagFromTagKind(OldTag);
14632     Diag(Redecl->getLocation(), diag::note_previous_use);
14633 
14634     // If there is a previous definition, suggest a fix-it.
14635     if (PrevDef) {
14636       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14637         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14638         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14639              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14640     }
14641   }
14642 
14643   return true;
14644 }
14645 
14646 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14647 /// from an outer enclosing namespace or file scope inside a friend declaration.
14648 /// This should provide the commented out code in the following snippet:
14649 ///   namespace N {
14650 ///     struct X;
14651 ///     namespace M {
14652 ///       struct Y { friend struct /*N::*/ X; };
14653 ///     }
14654 ///   }
14655 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14656                                          SourceLocation NameLoc) {
14657   // While the decl is in a namespace, do repeated lookup of that name and see
14658   // if we get the same namespace back.  If we do not, continue until
14659   // translation unit scope, at which point we have a fully qualified NNS.
14660   SmallVector<IdentifierInfo *, 4> Namespaces;
14661   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14662   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14663     // This tag should be declared in a namespace, which can only be enclosed by
14664     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14665     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14666     if (!Namespace || Namespace->isAnonymousNamespace())
14667       return FixItHint();
14668     IdentifierInfo *II = Namespace->getIdentifier();
14669     Namespaces.push_back(II);
14670     NamedDecl *Lookup = SemaRef.LookupSingleName(
14671         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14672     if (Lookup == Namespace)
14673       break;
14674   }
14675 
14676   // Once we have all the namespaces, reverse them to go outermost first, and
14677   // build an NNS.
14678   SmallString<64> Insertion;
14679   llvm::raw_svector_ostream OS(Insertion);
14680   if (DC->isTranslationUnit())
14681     OS << "::";
14682   std::reverse(Namespaces.begin(), Namespaces.end());
14683   for (auto *II : Namespaces)
14684     OS << II->getName() << "::";
14685   return FixItHint::CreateInsertion(NameLoc, Insertion);
14686 }
14687 
14688 /// Determine whether a tag originally declared in context \p OldDC can
14689 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14690 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14691 /// using-declaration).
14692 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14693                                          DeclContext *NewDC) {
14694   OldDC = OldDC->getRedeclContext();
14695   NewDC = NewDC->getRedeclContext();
14696 
14697   if (OldDC->Equals(NewDC))
14698     return true;
14699 
14700   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14701   // encloses the other).
14702   if (S.getLangOpts().MSVCCompat &&
14703       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14704     return true;
14705 
14706   return false;
14707 }
14708 
14709 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14710 /// former case, Name will be non-null.  In the later case, Name will be null.
14711 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14712 /// reference/declaration/definition of a tag.
14713 ///
14714 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14715 /// trailing-type-specifier) other than one in an alias-declaration.
14716 ///
14717 /// \param SkipBody If non-null, will be set to indicate if the caller should
14718 /// skip the definition of this tag and treat it as if it were a declaration.
14719 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14720                      SourceLocation KWLoc, CXXScopeSpec &SS,
14721                      IdentifierInfo *Name, SourceLocation NameLoc,
14722                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14723                      SourceLocation ModulePrivateLoc,
14724                      MultiTemplateParamsArg TemplateParameterLists,
14725                      bool &OwnedDecl, bool &IsDependent,
14726                      SourceLocation ScopedEnumKWLoc,
14727                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14728                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14729                      SkipBodyInfo *SkipBody) {
14730   // If this is not a definition, it must have a name.
14731   IdentifierInfo *OrigName = Name;
14732   assert((Name != nullptr || TUK == TUK_Definition) &&
14733          "Nameless record must be a definition!");
14734   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14735 
14736   OwnedDecl = false;
14737   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14738   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14739 
14740   // FIXME: Check member specializations more carefully.
14741   bool isMemberSpecialization = false;
14742   bool Invalid = false;
14743 
14744   // We only need to do this matching if we have template parameters
14745   // or a scope specifier, which also conveniently avoids this work
14746   // for non-C++ cases.
14747   if (TemplateParameterLists.size() > 0 ||
14748       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14749     if (TemplateParameterList *TemplateParams =
14750             MatchTemplateParametersToScopeSpecifier(
14751                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14752                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14753       if (Kind == TTK_Enum) {
14754         Diag(KWLoc, diag::err_enum_template);
14755         return nullptr;
14756       }
14757 
14758       if (TemplateParams->size() > 0) {
14759         // This is a declaration or definition of a class template (which may
14760         // be a member of another template).
14761 
14762         if (Invalid)
14763           return nullptr;
14764 
14765         OwnedDecl = false;
14766         DeclResult Result = CheckClassTemplate(
14767             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14768             AS, ModulePrivateLoc,
14769             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14770             TemplateParameterLists.data(), SkipBody);
14771         return Result.get();
14772       } else {
14773         // The "template<>" header is extraneous.
14774         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14775           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14776         isMemberSpecialization = true;
14777       }
14778     }
14779   }
14780 
14781   // Figure out the underlying type if this a enum declaration. We need to do
14782   // this early, because it's needed to detect if this is an incompatible
14783   // redeclaration.
14784   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14785   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14786 
14787   if (Kind == TTK_Enum) {
14788     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14789       // No underlying type explicitly specified, or we failed to parse the
14790       // type, default to int.
14791       EnumUnderlying = Context.IntTy.getTypePtr();
14792     } else if (UnderlyingType.get()) {
14793       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14794       // integral type; any cv-qualification is ignored.
14795       TypeSourceInfo *TI = nullptr;
14796       GetTypeFromParser(UnderlyingType.get(), &TI);
14797       EnumUnderlying = TI;
14798 
14799       if (CheckEnumUnderlyingType(TI))
14800         // Recover by falling back to int.
14801         EnumUnderlying = Context.IntTy.getTypePtr();
14802 
14803       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14804                                           UPPC_FixedUnderlyingType))
14805         EnumUnderlying = Context.IntTy.getTypePtr();
14806 
14807     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14808       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14809       // of 'int'. However, if this is an unfixed forward declaration, don't set
14810       // the underlying type unless the user enables -fms-compatibility. This
14811       // makes unfixed forward declared enums incomplete and is more conforming.
14812       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14813         EnumUnderlying = Context.IntTy.getTypePtr();
14814     }
14815   }
14816 
14817   DeclContext *SearchDC = CurContext;
14818   DeclContext *DC = CurContext;
14819   bool isStdBadAlloc = false;
14820   bool isStdAlignValT = false;
14821 
14822   RedeclarationKind Redecl = forRedeclarationInCurContext();
14823   if (TUK == TUK_Friend || TUK == TUK_Reference)
14824     Redecl = NotForRedeclaration;
14825 
14826   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14827   /// implemented asks for structural equivalence checking, the returned decl
14828   /// here is passed back to the parser, allowing the tag body to be parsed.
14829   auto createTagFromNewDecl = [&]() -> TagDecl * {
14830     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14831     // If there is an identifier, use the location of the identifier as the
14832     // location of the decl, otherwise use the location of the struct/union
14833     // keyword.
14834     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14835     TagDecl *New = nullptr;
14836 
14837     if (Kind == TTK_Enum) {
14838       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14839                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14840       // If this is an undefined enum, bail.
14841       if (TUK != TUK_Definition && !Invalid)
14842         return nullptr;
14843       if (EnumUnderlying) {
14844         EnumDecl *ED = cast<EnumDecl>(New);
14845         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14846           ED->setIntegerTypeSourceInfo(TI);
14847         else
14848           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14849         ED->setPromotionType(ED->getIntegerType());
14850       }
14851     } else { // struct/union
14852       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14853                                nullptr);
14854     }
14855 
14856     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14857       // Add alignment attributes if necessary; these attributes are checked
14858       // when the ASTContext lays out the structure.
14859       //
14860       // It is important for implementing the correct semantics that this
14861       // happen here (in ActOnTag). The #pragma pack stack is
14862       // maintained as a result of parser callbacks which can occur at
14863       // many points during the parsing of a struct declaration (because
14864       // the #pragma tokens are effectively skipped over during the
14865       // parsing of the struct).
14866       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14867         AddAlignmentAttributesForRecord(RD);
14868         AddMsStructLayoutForRecord(RD);
14869       }
14870     }
14871     New->setLexicalDeclContext(CurContext);
14872     return New;
14873   };
14874 
14875   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14876   if (Name && SS.isNotEmpty()) {
14877     // We have a nested-name tag ('struct foo::bar').
14878 
14879     // Check for invalid 'foo::'.
14880     if (SS.isInvalid()) {
14881       Name = nullptr;
14882       goto CreateNewDecl;
14883     }
14884 
14885     // If this is a friend or a reference to a class in a dependent
14886     // context, don't try to make a decl for it.
14887     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14888       DC = computeDeclContext(SS, false);
14889       if (!DC) {
14890         IsDependent = true;
14891         return nullptr;
14892       }
14893     } else {
14894       DC = computeDeclContext(SS, true);
14895       if (!DC) {
14896         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14897           << SS.getRange();
14898         return nullptr;
14899       }
14900     }
14901 
14902     if (RequireCompleteDeclContext(SS, DC))
14903       return nullptr;
14904 
14905     SearchDC = DC;
14906     // Look-up name inside 'foo::'.
14907     LookupQualifiedName(Previous, DC);
14908 
14909     if (Previous.isAmbiguous())
14910       return nullptr;
14911 
14912     if (Previous.empty()) {
14913       // Name lookup did not find anything. However, if the
14914       // nested-name-specifier refers to the current instantiation,
14915       // and that current instantiation has any dependent base
14916       // classes, we might find something at instantiation time: treat
14917       // this as a dependent elaborated-type-specifier.
14918       // But this only makes any sense for reference-like lookups.
14919       if (Previous.wasNotFoundInCurrentInstantiation() &&
14920           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14921         IsDependent = true;
14922         return nullptr;
14923       }
14924 
14925       // A tag 'foo::bar' must already exist.
14926       Diag(NameLoc, diag::err_not_tag_in_scope)
14927         << Kind << Name << DC << SS.getRange();
14928       Name = nullptr;
14929       Invalid = true;
14930       goto CreateNewDecl;
14931     }
14932   } else if (Name) {
14933     // C++14 [class.mem]p14:
14934     //   If T is the name of a class, then each of the following shall have a
14935     //   name different from T:
14936     //    -- every member of class T that is itself a type
14937     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14938         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14939       return nullptr;
14940 
14941     // If this is a named struct, check to see if there was a previous forward
14942     // declaration or definition.
14943     // FIXME: We're looking into outer scopes here, even when we
14944     // shouldn't be. Doing so can result in ambiguities that we
14945     // shouldn't be diagnosing.
14946     LookupName(Previous, S);
14947 
14948     // When declaring or defining a tag, ignore ambiguities introduced
14949     // by types using'ed into this scope.
14950     if (Previous.isAmbiguous() &&
14951         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14952       LookupResult::Filter F = Previous.makeFilter();
14953       while (F.hasNext()) {
14954         NamedDecl *ND = F.next();
14955         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14956                 SearchDC->getRedeclContext()))
14957           F.erase();
14958       }
14959       F.done();
14960     }
14961 
14962     // C++11 [namespace.memdef]p3:
14963     //   If the name in a friend declaration is neither qualified nor
14964     //   a template-id and the declaration is a function or an
14965     //   elaborated-type-specifier, the lookup to determine whether
14966     //   the entity has been previously declared shall not consider
14967     //   any scopes outside the innermost enclosing namespace.
14968     //
14969     // MSVC doesn't implement the above rule for types, so a friend tag
14970     // declaration may be a redeclaration of a type declared in an enclosing
14971     // scope.  They do implement this rule for friend functions.
14972     //
14973     // Does it matter that this should be by scope instead of by
14974     // semantic context?
14975     if (!Previous.empty() && TUK == TUK_Friend) {
14976       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14977       LookupResult::Filter F = Previous.makeFilter();
14978       bool FriendSawTagOutsideEnclosingNamespace = false;
14979       while (F.hasNext()) {
14980         NamedDecl *ND = F.next();
14981         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14982         if (DC->isFileContext() &&
14983             !EnclosingNS->Encloses(ND->getDeclContext())) {
14984           if (getLangOpts().MSVCCompat)
14985             FriendSawTagOutsideEnclosingNamespace = true;
14986           else
14987             F.erase();
14988         }
14989       }
14990       F.done();
14991 
14992       // Diagnose this MSVC extension in the easy case where lookup would have
14993       // unambiguously found something outside the enclosing namespace.
14994       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14995         NamedDecl *ND = Previous.getFoundDecl();
14996         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14997             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14998       }
14999     }
15000 
15001     // Note:  there used to be some attempt at recovery here.
15002     if (Previous.isAmbiguous())
15003       return nullptr;
15004 
15005     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15006       // FIXME: This makes sure that we ignore the contexts associated
15007       // with C structs, unions, and enums when looking for a matching
15008       // tag declaration or definition. See the similar lookup tweak
15009       // in Sema::LookupName; is there a better way to deal with this?
15010       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15011         SearchDC = SearchDC->getParent();
15012     }
15013   }
15014 
15015   if (Previous.isSingleResult() &&
15016       Previous.getFoundDecl()->isTemplateParameter()) {
15017     // Maybe we will complain about the shadowed template parameter.
15018     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15019     // Just pretend that we didn't see the previous declaration.
15020     Previous.clear();
15021   }
15022 
15023   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15024       DC->Equals(getStdNamespace())) {
15025     if (Name->isStr("bad_alloc")) {
15026       // This is a declaration of or a reference to "std::bad_alloc".
15027       isStdBadAlloc = true;
15028 
15029       // If std::bad_alloc has been implicitly declared (but made invisible to
15030       // name lookup), fill in this implicit declaration as the previous
15031       // declaration, so that the declarations get chained appropriately.
15032       if (Previous.empty() && StdBadAlloc)
15033         Previous.addDecl(getStdBadAlloc());
15034     } else if (Name->isStr("align_val_t")) {
15035       isStdAlignValT = true;
15036       if (Previous.empty() && StdAlignValT)
15037         Previous.addDecl(getStdAlignValT());
15038     }
15039   }
15040 
15041   // If we didn't find a previous declaration, and this is a reference
15042   // (or friend reference), move to the correct scope.  In C++, we
15043   // also need to do a redeclaration lookup there, just in case
15044   // there's a shadow friend decl.
15045   if (Name && Previous.empty() &&
15046       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15047     if (Invalid) goto CreateNewDecl;
15048     assert(SS.isEmpty());
15049 
15050     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15051       // C++ [basic.scope.pdecl]p5:
15052       //   -- for an elaborated-type-specifier of the form
15053       //
15054       //          class-key identifier
15055       //
15056       //      if the elaborated-type-specifier is used in the
15057       //      decl-specifier-seq or parameter-declaration-clause of a
15058       //      function defined in namespace scope, the identifier is
15059       //      declared as a class-name in the namespace that contains
15060       //      the declaration; otherwise, except as a friend
15061       //      declaration, the identifier is declared in the smallest
15062       //      non-class, non-function-prototype scope that contains the
15063       //      declaration.
15064       //
15065       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15066       // C structs and unions.
15067       //
15068       // It is an error in C++ to declare (rather than define) an enum
15069       // type, including via an elaborated type specifier.  We'll
15070       // diagnose that later; for now, declare the enum in the same
15071       // scope as we would have picked for any other tag type.
15072       //
15073       // GNU C also supports this behavior as part of its incomplete
15074       // enum types extension, while GNU C++ does not.
15075       //
15076       // Find the context where we'll be declaring the tag.
15077       // FIXME: We would like to maintain the current DeclContext as the
15078       // lexical context,
15079       SearchDC = getTagInjectionContext(SearchDC);
15080 
15081       // Find the scope where we'll be declaring the tag.
15082       S = getTagInjectionScope(S, getLangOpts());
15083     } else {
15084       assert(TUK == TUK_Friend);
15085       // C++ [namespace.memdef]p3:
15086       //   If a friend declaration in a non-local class first declares a
15087       //   class or function, the friend class or function is a member of
15088       //   the innermost enclosing namespace.
15089       SearchDC = SearchDC->getEnclosingNamespaceContext();
15090     }
15091 
15092     // In C++, we need to do a redeclaration lookup to properly
15093     // diagnose some problems.
15094     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15095     // hidden declaration so that we don't get ambiguity errors when using a
15096     // type declared by an elaborated-type-specifier.  In C that is not correct
15097     // and we should instead merge compatible types found by lookup.
15098     if (getLangOpts().CPlusPlus) {
15099       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15100       LookupQualifiedName(Previous, SearchDC);
15101     } else {
15102       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15103       LookupName(Previous, S);
15104     }
15105   }
15106 
15107   // If we have a known previous declaration to use, then use it.
15108   if (Previous.empty() && SkipBody && SkipBody->Previous)
15109     Previous.addDecl(SkipBody->Previous);
15110 
15111   if (!Previous.empty()) {
15112     NamedDecl *PrevDecl = Previous.getFoundDecl();
15113     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15114 
15115     // It's okay to have a tag decl in the same scope as a typedef
15116     // which hides a tag decl in the same scope.  Finding this
15117     // insanity with a redeclaration lookup can only actually happen
15118     // in C++.
15119     //
15120     // This is also okay for elaborated-type-specifiers, which is
15121     // technically forbidden by the current standard but which is
15122     // okay according to the likely resolution of an open issue;
15123     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15124     if (getLangOpts().CPlusPlus) {
15125       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15126         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15127           TagDecl *Tag = TT->getDecl();
15128           if (Tag->getDeclName() == Name &&
15129               Tag->getDeclContext()->getRedeclContext()
15130                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15131             PrevDecl = Tag;
15132             Previous.clear();
15133             Previous.addDecl(Tag);
15134             Previous.resolveKind();
15135           }
15136         }
15137       }
15138     }
15139 
15140     // If this is a redeclaration of a using shadow declaration, it must
15141     // declare a tag in the same context. In MSVC mode, we allow a
15142     // redefinition if either context is within the other.
15143     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15144       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15145       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15146           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15147           !(OldTag && isAcceptableTagRedeclContext(
15148                           *this, OldTag->getDeclContext(), SearchDC))) {
15149         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15150         Diag(Shadow->getTargetDecl()->getLocation(),
15151              diag::note_using_decl_target);
15152         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15153             << 0;
15154         // Recover by ignoring the old declaration.
15155         Previous.clear();
15156         goto CreateNewDecl;
15157       }
15158     }
15159 
15160     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15161       // If this is a use of a previous tag, or if the tag is already declared
15162       // in the same scope (so that the definition/declaration completes or
15163       // rementions the tag), reuse the decl.
15164       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15165           isDeclInScope(DirectPrevDecl, SearchDC, S,
15166                         SS.isNotEmpty() || isMemberSpecialization)) {
15167         // Make sure that this wasn't declared as an enum and now used as a
15168         // struct or something similar.
15169         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15170                                           TUK == TUK_Definition, KWLoc,
15171                                           Name)) {
15172           bool SafeToContinue
15173             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15174                Kind != TTK_Enum);
15175           if (SafeToContinue)
15176             Diag(KWLoc, diag::err_use_with_wrong_tag)
15177               << Name
15178               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15179                                               PrevTagDecl->getKindName());
15180           else
15181             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15182           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15183 
15184           if (SafeToContinue)
15185             Kind = PrevTagDecl->getTagKind();
15186           else {
15187             // Recover by making this an anonymous redefinition.
15188             Name = nullptr;
15189             Previous.clear();
15190             Invalid = true;
15191           }
15192         }
15193 
15194         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15195           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15196 
15197           // If this is an elaborated-type-specifier for a scoped enumeration,
15198           // the 'class' keyword is not necessary and not permitted.
15199           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15200             if (ScopedEnum)
15201               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15202                 << PrevEnum->isScoped()
15203                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15204             return PrevTagDecl;
15205           }
15206 
15207           QualType EnumUnderlyingTy;
15208           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15209             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15210           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15211             EnumUnderlyingTy = QualType(T, 0);
15212 
15213           // All conflicts with previous declarations are recovered by
15214           // returning the previous declaration, unless this is a definition,
15215           // in which case we want the caller to bail out.
15216           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15217                                      ScopedEnum, EnumUnderlyingTy,
15218                                      IsFixed, PrevEnum))
15219             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15220         }
15221 
15222         // C++11 [class.mem]p1:
15223         //   A member shall not be declared twice in the member-specification,
15224         //   except that a nested class or member class template can be declared
15225         //   and then later defined.
15226         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15227             S->isDeclScope(PrevDecl)) {
15228           Diag(NameLoc, diag::ext_member_redeclared);
15229           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15230         }
15231 
15232         if (!Invalid) {
15233           // If this is a use, just return the declaration we found, unless
15234           // we have attributes.
15235           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15236             if (!Attrs.empty()) {
15237               // FIXME: Diagnose these attributes. For now, we create a new
15238               // declaration to hold them.
15239             } else if (TUK == TUK_Reference &&
15240                        (PrevTagDecl->getFriendObjectKind() ==
15241                             Decl::FOK_Undeclared ||
15242                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15243                        SS.isEmpty()) {
15244               // This declaration is a reference to an existing entity, but
15245               // has different visibility from that entity: it either makes
15246               // a friend visible or it makes a type visible in a new module.
15247               // In either case, create a new declaration. We only do this if
15248               // the declaration would have meant the same thing if no prior
15249               // declaration were found, that is, if it was found in the same
15250               // scope where we would have injected a declaration.
15251               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15252                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15253                 return PrevTagDecl;
15254               // This is in the injected scope, create a new declaration in
15255               // that scope.
15256               S = getTagInjectionScope(S, getLangOpts());
15257             } else {
15258               return PrevTagDecl;
15259             }
15260           }
15261 
15262           // Diagnose attempts to redefine a tag.
15263           if (TUK == TUK_Definition) {
15264             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15265               // If we're defining a specialization and the previous definition
15266               // is from an implicit instantiation, don't emit an error
15267               // here; we'll catch this in the general case below.
15268               bool IsExplicitSpecializationAfterInstantiation = false;
15269               if (isMemberSpecialization) {
15270                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15271                   IsExplicitSpecializationAfterInstantiation =
15272                     RD->getTemplateSpecializationKind() !=
15273                     TSK_ExplicitSpecialization;
15274                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15275                   IsExplicitSpecializationAfterInstantiation =
15276                     ED->getTemplateSpecializationKind() !=
15277                     TSK_ExplicitSpecialization;
15278               }
15279 
15280               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15281               // not keep more that one definition around (merge them). However,
15282               // ensure the decl passes the structural compatibility check in
15283               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15284               NamedDecl *Hidden = nullptr;
15285               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15286                 // There is a definition of this tag, but it is not visible. We
15287                 // explicitly make use of C++'s one definition rule here, and
15288                 // assume that this definition is identical to the hidden one
15289                 // we already have. Make the existing definition visible and
15290                 // use it in place of this one.
15291                 if (!getLangOpts().CPlusPlus) {
15292                   // Postpone making the old definition visible until after we
15293                   // complete parsing the new one and do the structural
15294                   // comparison.
15295                   SkipBody->CheckSameAsPrevious = true;
15296                   SkipBody->New = createTagFromNewDecl();
15297                   SkipBody->Previous = Def;
15298                   return Def;
15299                 } else {
15300                   SkipBody->ShouldSkip = true;
15301                   SkipBody->Previous = Def;
15302                   makeMergedDefinitionVisible(Hidden);
15303                   // Carry on and handle it like a normal definition. We'll
15304                   // skip starting the definitiion later.
15305                 }
15306               } else if (!IsExplicitSpecializationAfterInstantiation) {
15307                 // A redeclaration in function prototype scope in C isn't
15308                 // visible elsewhere, so merely issue a warning.
15309                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15310                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15311                 else
15312                   Diag(NameLoc, diag::err_redefinition) << Name;
15313                 notePreviousDefinition(Def,
15314                                        NameLoc.isValid() ? NameLoc : KWLoc);
15315                 // If this is a redefinition, recover by making this
15316                 // struct be anonymous, which will make any later
15317                 // references get the previous definition.
15318                 Name = nullptr;
15319                 Previous.clear();
15320                 Invalid = true;
15321               }
15322             } else {
15323               // If the type is currently being defined, complain
15324               // about a nested redefinition.
15325               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15326               if (TD->isBeingDefined()) {
15327                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15328                 Diag(PrevTagDecl->getLocation(),
15329                      diag::note_previous_definition);
15330                 Name = nullptr;
15331                 Previous.clear();
15332                 Invalid = true;
15333               }
15334             }
15335 
15336             // Okay, this is definition of a previously declared or referenced
15337             // tag. We're going to create a new Decl for it.
15338           }
15339 
15340           // Okay, we're going to make a redeclaration.  If this is some kind
15341           // of reference, make sure we build the redeclaration in the same DC
15342           // as the original, and ignore the current access specifier.
15343           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15344             SearchDC = PrevTagDecl->getDeclContext();
15345             AS = AS_none;
15346           }
15347         }
15348         // If we get here we have (another) forward declaration or we
15349         // have a definition.  Just create a new decl.
15350 
15351       } else {
15352         // If we get here, this is a definition of a new tag type in a nested
15353         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15354         // new decl/type.  We set PrevDecl to NULL so that the entities
15355         // have distinct types.
15356         Previous.clear();
15357       }
15358       // If we get here, we're going to create a new Decl. If PrevDecl
15359       // is non-NULL, it's a definition of the tag declared by
15360       // PrevDecl. If it's NULL, we have a new definition.
15361 
15362     // Otherwise, PrevDecl is not a tag, but was found with tag
15363     // lookup.  This is only actually possible in C++, where a few
15364     // things like templates still live in the tag namespace.
15365     } else {
15366       // Use a better diagnostic if an elaborated-type-specifier
15367       // found the wrong kind of type on the first
15368       // (non-redeclaration) lookup.
15369       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15370           !Previous.isForRedeclaration()) {
15371         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15372         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15373                                                        << Kind;
15374         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15375         Invalid = true;
15376 
15377       // Otherwise, only diagnose if the declaration is in scope.
15378       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15379                                 SS.isNotEmpty() || isMemberSpecialization)) {
15380         // do nothing
15381 
15382       // Diagnose implicit declarations introduced by elaborated types.
15383       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15384         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15385         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15386         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15387         Invalid = true;
15388 
15389       // Otherwise it's a declaration.  Call out a particularly common
15390       // case here.
15391       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15392         unsigned Kind = 0;
15393         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15394         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15395           << Name << Kind << TND->getUnderlyingType();
15396         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15397         Invalid = true;
15398 
15399       // Otherwise, diagnose.
15400       } else {
15401         // The tag name clashes with something else in the target scope,
15402         // issue an error and recover by making this tag be anonymous.
15403         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15404         notePreviousDefinition(PrevDecl, NameLoc);
15405         Name = nullptr;
15406         Invalid = true;
15407       }
15408 
15409       // The existing declaration isn't relevant to us; we're in a
15410       // new scope, so clear out the previous declaration.
15411       Previous.clear();
15412     }
15413   }
15414 
15415 CreateNewDecl:
15416 
15417   TagDecl *PrevDecl = nullptr;
15418   if (Previous.isSingleResult())
15419     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15420 
15421   // If there is an identifier, use the location of the identifier as the
15422   // location of the decl, otherwise use the location of the struct/union
15423   // keyword.
15424   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15425 
15426   // Otherwise, create a new declaration. If there is a previous
15427   // declaration of the same entity, the two will be linked via
15428   // PrevDecl.
15429   TagDecl *New;
15430 
15431   if (Kind == TTK_Enum) {
15432     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15433     // enum X { A, B, C } D;    D should chain to X.
15434     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15435                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15436                            ScopedEnumUsesClassTag, IsFixed);
15437 
15438     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15439       StdAlignValT = cast<EnumDecl>(New);
15440 
15441     // If this is an undefined enum, warn.
15442     if (TUK != TUK_Definition && !Invalid) {
15443       TagDecl *Def;
15444       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15445         // C++0x: 7.2p2: opaque-enum-declaration.
15446         // Conflicts are diagnosed above. Do nothing.
15447       }
15448       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15449         Diag(Loc, diag::ext_forward_ref_enum_def)
15450           << New;
15451         Diag(Def->getLocation(), diag::note_previous_definition);
15452       } else {
15453         unsigned DiagID = diag::ext_forward_ref_enum;
15454         if (getLangOpts().MSVCCompat)
15455           DiagID = diag::ext_ms_forward_ref_enum;
15456         else if (getLangOpts().CPlusPlus)
15457           DiagID = diag::err_forward_ref_enum;
15458         Diag(Loc, DiagID);
15459       }
15460     }
15461 
15462     if (EnumUnderlying) {
15463       EnumDecl *ED = cast<EnumDecl>(New);
15464       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15465         ED->setIntegerTypeSourceInfo(TI);
15466       else
15467         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15468       ED->setPromotionType(ED->getIntegerType());
15469       assert(ED->isComplete() && "enum with type should be complete");
15470     }
15471   } else {
15472     // struct/union/class
15473 
15474     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15475     // struct X { int A; } D;    D should chain to X.
15476     if (getLangOpts().CPlusPlus) {
15477       // FIXME: Look for a way to use RecordDecl for simple structs.
15478       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15479                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15480 
15481       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15482         StdBadAlloc = cast<CXXRecordDecl>(New);
15483     } else
15484       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15485                                cast_or_null<RecordDecl>(PrevDecl));
15486   }
15487 
15488   // C++11 [dcl.type]p3:
15489   //   A type-specifier-seq shall not define a class or enumeration [...].
15490   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15491       TUK == TUK_Definition) {
15492     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15493       << Context.getTagDeclType(New);
15494     Invalid = true;
15495   }
15496 
15497   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15498       DC->getDeclKind() == Decl::Enum) {
15499     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15500       << Context.getTagDeclType(New);
15501     Invalid = true;
15502   }
15503 
15504   // Maybe add qualifier info.
15505   if (SS.isNotEmpty()) {
15506     if (SS.isSet()) {
15507       // If this is either a declaration or a definition, check the
15508       // nested-name-specifier against the current context.
15509       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15510           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15511                                        isMemberSpecialization))
15512         Invalid = true;
15513 
15514       New->setQualifierInfo(SS.getWithLocInContext(Context));
15515       if (TemplateParameterLists.size() > 0) {
15516         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15517       }
15518     }
15519     else
15520       Invalid = true;
15521   }
15522 
15523   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15524     // Add alignment attributes if necessary; these attributes are checked when
15525     // the ASTContext lays out the structure.
15526     //
15527     // It is important for implementing the correct semantics that this
15528     // happen here (in ActOnTag). The #pragma pack stack is
15529     // maintained as a result of parser callbacks which can occur at
15530     // many points during the parsing of a struct declaration (because
15531     // the #pragma tokens are effectively skipped over during the
15532     // parsing of the struct).
15533     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15534       AddAlignmentAttributesForRecord(RD);
15535       AddMsStructLayoutForRecord(RD);
15536     }
15537   }
15538 
15539   if (ModulePrivateLoc.isValid()) {
15540     if (isMemberSpecialization)
15541       Diag(New->getLocation(), diag::err_module_private_specialization)
15542         << 2
15543         << FixItHint::CreateRemoval(ModulePrivateLoc);
15544     // __module_private__ does not apply to local classes. However, we only
15545     // diagnose this as an error when the declaration specifiers are
15546     // freestanding. Here, we just ignore the __module_private__.
15547     else if (!SearchDC->isFunctionOrMethod())
15548       New->setModulePrivate();
15549   }
15550 
15551   // If this is a specialization of a member class (of a class template),
15552   // check the specialization.
15553   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15554     Invalid = true;
15555 
15556   // If we're declaring or defining a tag in function prototype scope in C,
15557   // note that this type can only be used within the function and add it to
15558   // the list of decls to inject into the function definition scope.
15559   if ((Name || Kind == TTK_Enum) &&
15560       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15561     if (getLangOpts().CPlusPlus) {
15562       // C++ [dcl.fct]p6:
15563       //   Types shall not be defined in return or parameter types.
15564       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15565         Diag(Loc, diag::err_type_defined_in_param_type)
15566             << Name;
15567         Invalid = true;
15568       }
15569     } else if (!PrevDecl) {
15570       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15571     }
15572   }
15573 
15574   if (Invalid)
15575     New->setInvalidDecl();
15576 
15577   // Set the lexical context. If the tag has a C++ scope specifier, the
15578   // lexical context will be different from the semantic context.
15579   New->setLexicalDeclContext(CurContext);
15580 
15581   // Mark this as a friend decl if applicable.
15582   // In Microsoft mode, a friend declaration also acts as a forward
15583   // declaration so we always pass true to setObjectOfFriendDecl to make
15584   // the tag name visible.
15585   if (TUK == TUK_Friend)
15586     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15587 
15588   // Set the access specifier.
15589   if (!Invalid && SearchDC->isRecord())
15590     SetMemberAccessSpecifier(New, PrevDecl, AS);
15591 
15592   if (PrevDecl)
15593     CheckRedeclarationModuleOwnership(New, PrevDecl);
15594 
15595   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15596     New->startDefinition();
15597 
15598   ProcessDeclAttributeList(S, New, Attrs);
15599   AddPragmaAttributes(S, New);
15600 
15601   // If this has an identifier, add it to the scope stack.
15602   if (TUK == TUK_Friend) {
15603     // We might be replacing an existing declaration in the lookup tables;
15604     // if so, borrow its access specifier.
15605     if (PrevDecl)
15606       New->setAccess(PrevDecl->getAccess());
15607 
15608     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15609     DC->makeDeclVisibleInContext(New);
15610     if (Name) // can be null along some error paths
15611       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15612         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15613   } else if (Name) {
15614     S = getNonFieldDeclScope(S);
15615     PushOnScopeChains(New, S, true);
15616   } else {
15617     CurContext->addDecl(New);
15618   }
15619 
15620   // If this is the C FILE type, notify the AST context.
15621   if (IdentifierInfo *II = New->getIdentifier())
15622     if (!New->isInvalidDecl() &&
15623         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15624         II->isStr("FILE"))
15625       Context.setFILEDecl(New);
15626 
15627   if (PrevDecl)
15628     mergeDeclAttributes(New, PrevDecl);
15629 
15630   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15631     inferGslOwnerPointerAttribute(CXXRD);
15632 
15633   // If there's a #pragma GCC visibility in scope, set the visibility of this
15634   // record.
15635   AddPushedVisibilityAttribute(New);
15636 
15637   if (isMemberSpecialization && !New->isInvalidDecl())
15638     CompleteMemberSpecialization(New, Previous);
15639 
15640   OwnedDecl = true;
15641   // In C++, don't return an invalid declaration. We can't recover well from
15642   // the cases where we make the type anonymous.
15643   if (Invalid && getLangOpts().CPlusPlus) {
15644     if (New->isBeingDefined())
15645       if (auto RD = dyn_cast<RecordDecl>(New))
15646         RD->completeDefinition();
15647     return nullptr;
15648   } else if (SkipBody && SkipBody->ShouldSkip) {
15649     return SkipBody->Previous;
15650   } else {
15651     return New;
15652   }
15653 }
15654 
15655 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15656   AdjustDeclIfTemplate(TagD);
15657   TagDecl *Tag = cast<TagDecl>(TagD);
15658 
15659   // Enter the tag context.
15660   PushDeclContext(S, Tag);
15661 
15662   ActOnDocumentableDecl(TagD);
15663 
15664   // If there's a #pragma GCC visibility in scope, set the visibility of this
15665   // record.
15666   AddPushedVisibilityAttribute(Tag);
15667 }
15668 
15669 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15670                                     SkipBodyInfo &SkipBody) {
15671   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15672     return false;
15673 
15674   // Make the previous decl visible.
15675   makeMergedDefinitionVisible(SkipBody.Previous);
15676   return true;
15677 }
15678 
15679 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15680   assert(isa<ObjCContainerDecl>(IDecl) &&
15681          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15682   DeclContext *OCD = cast<DeclContext>(IDecl);
15683   assert(getContainingDC(OCD) == CurContext &&
15684       "The next DeclContext should be lexically contained in the current one.");
15685   CurContext = OCD;
15686   return IDecl;
15687 }
15688 
15689 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15690                                            SourceLocation FinalLoc,
15691                                            bool IsFinalSpelledSealed,
15692                                            SourceLocation LBraceLoc) {
15693   AdjustDeclIfTemplate(TagD);
15694   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15695 
15696   FieldCollector->StartClass();
15697 
15698   if (!Record->getIdentifier())
15699     return;
15700 
15701   if (FinalLoc.isValid())
15702     Record->addAttr(FinalAttr::Create(
15703         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15704         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15705 
15706   // C++ [class]p2:
15707   //   [...] The class-name is also inserted into the scope of the
15708   //   class itself; this is known as the injected-class-name. For
15709   //   purposes of access checking, the injected-class-name is treated
15710   //   as if it were a public member name.
15711   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15712       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15713       Record->getLocation(), Record->getIdentifier(),
15714       /*PrevDecl=*/nullptr,
15715       /*DelayTypeCreation=*/true);
15716   Context.getTypeDeclType(InjectedClassName, Record);
15717   InjectedClassName->setImplicit();
15718   InjectedClassName->setAccess(AS_public);
15719   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15720       InjectedClassName->setDescribedClassTemplate(Template);
15721   PushOnScopeChains(InjectedClassName, S);
15722   assert(InjectedClassName->isInjectedClassName() &&
15723          "Broken injected-class-name");
15724 }
15725 
15726 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15727                                     SourceRange BraceRange) {
15728   AdjustDeclIfTemplate(TagD);
15729   TagDecl *Tag = cast<TagDecl>(TagD);
15730   Tag->setBraceRange(BraceRange);
15731 
15732   // Make sure we "complete" the definition even it is invalid.
15733   if (Tag->isBeingDefined()) {
15734     assert(Tag->isInvalidDecl() && "We should already have completed it");
15735     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15736       RD->completeDefinition();
15737   }
15738 
15739   if (isa<CXXRecordDecl>(Tag)) {
15740     FieldCollector->FinishClass();
15741   }
15742 
15743   // Exit this scope of this tag's definition.
15744   PopDeclContext();
15745 
15746   if (getCurLexicalContext()->isObjCContainer() &&
15747       Tag->getDeclContext()->isFileContext())
15748     Tag->setTopLevelDeclInObjCContainer();
15749 
15750   // Notify the consumer that we've defined a tag.
15751   if (!Tag->isInvalidDecl())
15752     Consumer.HandleTagDeclDefinition(Tag);
15753 }
15754 
15755 void Sema::ActOnObjCContainerFinishDefinition() {
15756   // Exit this scope of this interface definition.
15757   PopDeclContext();
15758 }
15759 
15760 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15761   assert(DC == CurContext && "Mismatch of container contexts");
15762   OriginalLexicalContext = DC;
15763   ActOnObjCContainerFinishDefinition();
15764 }
15765 
15766 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15767   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15768   OriginalLexicalContext = nullptr;
15769 }
15770 
15771 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15772   AdjustDeclIfTemplate(TagD);
15773   TagDecl *Tag = cast<TagDecl>(TagD);
15774   Tag->setInvalidDecl();
15775 
15776   // Make sure we "complete" the definition even it is invalid.
15777   if (Tag->isBeingDefined()) {
15778     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15779       RD->completeDefinition();
15780   }
15781 
15782   // We're undoing ActOnTagStartDefinition here, not
15783   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15784   // the FieldCollector.
15785 
15786   PopDeclContext();
15787 }
15788 
15789 // Note that FieldName may be null for anonymous bitfields.
15790 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15791                                 IdentifierInfo *FieldName,
15792                                 QualType FieldTy, bool IsMsStruct,
15793                                 Expr *BitWidth, bool *ZeroWidth) {
15794   // Default to true; that shouldn't confuse checks for emptiness
15795   if (ZeroWidth)
15796     *ZeroWidth = true;
15797 
15798   // C99 6.7.2.1p4 - verify the field type.
15799   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15800   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15801     // Handle incomplete types with specific error.
15802     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15803       return ExprError();
15804     if (FieldName)
15805       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15806         << FieldName << FieldTy << BitWidth->getSourceRange();
15807     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15808       << FieldTy << BitWidth->getSourceRange();
15809   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15810                                              UPPC_BitFieldWidth))
15811     return ExprError();
15812 
15813   // If the bit-width is type- or value-dependent, don't try to check
15814   // it now.
15815   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15816     return BitWidth;
15817 
15818   llvm::APSInt Value;
15819   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15820   if (ICE.isInvalid())
15821     return ICE;
15822   BitWidth = ICE.get();
15823 
15824   if (Value != 0 && ZeroWidth)
15825     *ZeroWidth = false;
15826 
15827   // Zero-width bitfield is ok for anonymous field.
15828   if (Value == 0 && FieldName)
15829     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15830 
15831   if (Value.isSigned() && Value.isNegative()) {
15832     if (FieldName)
15833       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15834                << FieldName << Value.toString(10);
15835     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15836       << Value.toString(10);
15837   }
15838 
15839   if (!FieldTy->isDependentType()) {
15840     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15841     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15842     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15843 
15844     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15845     // ABI.
15846     bool CStdConstraintViolation =
15847         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15848     bool MSBitfieldViolation =
15849         Value.ugt(TypeStorageSize) &&
15850         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15851     if (CStdConstraintViolation || MSBitfieldViolation) {
15852       unsigned DiagWidth =
15853           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15854       if (FieldName)
15855         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15856                << FieldName << (unsigned)Value.getZExtValue()
15857                << !CStdConstraintViolation << DiagWidth;
15858 
15859       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15860              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15861              << DiagWidth;
15862     }
15863 
15864     // Warn on types where the user might conceivably expect to get all
15865     // specified bits as value bits: that's all integral types other than
15866     // 'bool'.
15867     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15868       if (FieldName)
15869         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15870             << FieldName << (unsigned)Value.getZExtValue()
15871             << (unsigned)TypeWidth;
15872       else
15873         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15874             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15875     }
15876   }
15877 
15878   return BitWidth;
15879 }
15880 
15881 /// ActOnField - Each field of a C struct/union is passed into this in order
15882 /// to create a FieldDecl object for it.
15883 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15884                        Declarator &D, Expr *BitfieldWidth) {
15885   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15886                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15887                                /*InitStyle=*/ICIS_NoInit, AS_public);
15888   return Res;
15889 }
15890 
15891 /// HandleField - Analyze a field of a C struct or a C++ data member.
15892 ///
15893 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15894                              SourceLocation DeclStart,
15895                              Declarator &D, Expr *BitWidth,
15896                              InClassInitStyle InitStyle,
15897                              AccessSpecifier AS) {
15898   if (D.isDecompositionDeclarator()) {
15899     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15900     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15901       << Decomp.getSourceRange();
15902     return nullptr;
15903   }
15904 
15905   IdentifierInfo *II = D.getIdentifier();
15906   SourceLocation Loc = DeclStart;
15907   if (II) Loc = D.getIdentifierLoc();
15908 
15909   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15910   QualType T = TInfo->getType();
15911   if (getLangOpts().CPlusPlus) {
15912     CheckExtraCXXDefaultArguments(D);
15913 
15914     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15915                                         UPPC_DataMemberType)) {
15916       D.setInvalidType();
15917       T = Context.IntTy;
15918       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15919     }
15920   }
15921 
15922   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15923 
15924   if (D.getDeclSpec().isInlineSpecified())
15925     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15926         << getLangOpts().CPlusPlus17;
15927   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15928     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15929          diag::err_invalid_thread)
15930       << DeclSpec::getSpecifierName(TSCS);
15931 
15932   // Check to see if this name was declared as a member previously
15933   NamedDecl *PrevDecl = nullptr;
15934   LookupResult Previous(*this, II, Loc, LookupMemberName,
15935                         ForVisibleRedeclaration);
15936   LookupName(Previous, S);
15937   switch (Previous.getResultKind()) {
15938     case LookupResult::Found:
15939     case LookupResult::FoundUnresolvedValue:
15940       PrevDecl = Previous.getAsSingle<NamedDecl>();
15941       break;
15942 
15943     case LookupResult::FoundOverloaded:
15944       PrevDecl = Previous.getRepresentativeDecl();
15945       break;
15946 
15947     case LookupResult::NotFound:
15948     case LookupResult::NotFoundInCurrentInstantiation:
15949     case LookupResult::Ambiguous:
15950       break;
15951   }
15952   Previous.suppressDiagnostics();
15953 
15954   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15955     // Maybe we will complain about the shadowed template parameter.
15956     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15957     // Just pretend that we didn't see the previous declaration.
15958     PrevDecl = nullptr;
15959   }
15960 
15961   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15962     PrevDecl = nullptr;
15963 
15964   bool Mutable
15965     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15966   SourceLocation TSSL = D.getBeginLoc();
15967   FieldDecl *NewFD
15968     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15969                      TSSL, AS, PrevDecl, &D);
15970 
15971   if (NewFD->isInvalidDecl())
15972     Record->setInvalidDecl();
15973 
15974   if (D.getDeclSpec().isModulePrivateSpecified())
15975     NewFD->setModulePrivate();
15976 
15977   if (NewFD->isInvalidDecl() && PrevDecl) {
15978     // Don't introduce NewFD into scope; there's already something
15979     // with the same name in the same scope.
15980   } else if (II) {
15981     PushOnScopeChains(NewFD, S);
15982   } else
15983     Record->addDecl(NewFD);
15984 
15985   return NewFD;
15986 }
15987 
15988 /// Build a new FieldDecl and check its well-formedness.
15989 ///
15990 /// This routine builds a new FieldDecl given the fields name, type,
15991 /// record, etc. \p PrevDecl should refer to any previous declaration
15992 /// with the same name and in the same scope as the field to be
15993 /// created.
15994 ///
15995 /// \returns a new FieldDecl.
15996 ///
15997 /// \todo The Declarator argument is a hack. It will be removed once
15998 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15999                                 TypeSourceInfo *TInfo,
16000                                 RecordDecl *Record, SourceLocation Loc,
16001                                 bool Mutable, Expr *BitWidth,
16002                                 InClassInitStyle InitStyle,
16003                                 SourceLocation TSSL,
16004                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16005                                 Declarator *D) {
16006   IdentifierInfo *II = Name.getAsIdentifierInfo();
16007   bool InvalidDecl = false;
16008   if (D) InvalidDecl = D->isInvalidType();
16009 
16010   // If we receive a broken type, recover by assuming 'int' and
16011   // marking this declaration as invalid.
16012   if (T.isNull()) {
16013     InvalidDecl = true;
16014     T = Context.IntTy;
16015   }
16016 
16017   QualType EltTy = Context.getBaseElementType(T);
16018   if (!EltTy->isDependentType()) {
16019     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16020       // Fields of incomplete type force their record to be invalid.
16021       Record->setInvalidDecl();
16022       InvalidDecl = true;
16023     } else {
16024       NamedDecl *Def;
16025       EltTy->isIncompleteType(&Def);
16026       if (Def && Def->isInvalidDecl()) {
16027         Record->setInvalidDecl();
16028         InvalidDecl = true;
16029       }
16030     }
16031   }
16032 
16033   // TR 18037 does not allow fields to be declared with address space
16034   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
16035       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16036     Diag(Loc, diag::err_field_with_address_space);
16037     Record->setInvalidDecl();
16038     InvalidDecl = true;
16039   }
16040 
16041   if (LangOpts.OpenCL) {
16042     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16043     // used as structure or union field: image, sampler, event or block types.
16044     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16045         T->isBlockPointerType()) {
16046       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16047       Record->setInvalidDecl();
16048       InvalidDecl = true;
16049     }
16050     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16051     if (BitWidth) {
16052       Diag(Loc, diag::err_opencl_bitfields);
16053       InvalidDecl = true;
16054     }
16055   }
16056 
16057   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16058   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16059       T.hasQualifiers()) {
16060     InvalidDecl = true;
16061     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16062   }
16063 
16064   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16065   // than a variably modified type.
16066   if (!InvalidDecl && T->isVariablyModifiedType()) {
16067     bool SizeIsNegative;
16068     llvm::APSInt Oversized;
16069 
16070     TypeSourceInfo *FixedTInfo =
16071       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16072                                                     SizeIsNegative,
16073                                                     Oversized);
16074     if (FixedTInfo) {
16075       Diag(Loc, diag::warn_illegal_constant_array_size);
16076       TInfo = FixedTInfo;
16077       T = FixedTInfo->getType();
16078     } else {
16079       if (SizeIsNegative)
16080         Diag(Loc, diag::err_typecheck_negative_array_size);
16081       else if (Oversized.getBoolValue())
16082         Diag(Loc, diag::err_array_too_large)
16083           << Oversized.toString(10);
16084       else
16085         Diag(Loc, diag::err_typecheck_field_variable_size);
16086       InvalidDecl = true;
16087     }
16088   }
16089 
16090   // Fields can not have abstract class types
16091   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16092                                              diag::err_abstract_type_in_decl,
16093                                              AbstractFieldType))
16094     InvalidDecl = true;
16095 
16096   bool ZeroWidth = false;
16097   if (InvalidDecl)
16098     BitWidth = nullptr;
16099   // If this is declared as a bit-field, check the bit-field.
16100   if (BitWidth) {
16101     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16102                               &ZeroWidth).get();
16103     if (!BitWidth) {
16104       InvalidDecl = true;
16105       BitWidth = nullptr;
16106       ZeroWidth = false;
16107     }
16108   }
16109 
16110   // Check that 'mutable' is consistent with the type of the declaration.
16111   if (!InvalidDecl && Mutable) {
16112     unsigned DiagID = 0;
16113     if (T->isReferenceType())
16114       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16115                                         : diag::err_mutable_reference;
16116     else if (T.isConstQualified())
16117       DiagID = diag::err_mutable_const;
16118 
16119     if (DiagID) {
16120       SourceLocation ErrLoc = Loc;
16121       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16122         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16123       Diag(ErrLoc, DiagID);
16124       if (DiagID != diag::ext_mutable_reference) {
16125         Mutable = false;
16126         InvalidDecl = true;
16127       }
16128     }
16129   }
16130 
16131   // C++11 [class.union]p8 (DR1460):
16132   //   At most one variant member of a union may have a
16133   //   brace-or-equal-initializer.
16134   if (InitStyle != ICIS_NoInit)
16135     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16136 
16137   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16138                                        BitWidth, Mutable, InitStyle);
16139   if (InvalidDecl)
16140     NewFD->setInvalidDecl();
16141 
16142   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16143     Diag(Loc, diag::err_duplicate_member) << II;
16144     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16145     NewFD->setInvalidDecl();
16146   }
16147 
16148   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16149     if (Record->isUnion()) {
16150       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16151         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16152         if (RDecl->getDefinition()) {
16153           // C++ [class.union]p1: An object of a class with a non-trivial
16154           // constructor, a non-trivial copy constructor, a non-trivial
16155           // destructor, or a non-trivial copy assignment operator
16156           // cannot be a member of a union, nor can an array of such
16157           // objects.
16158           if (CheckNontrivialField(NewFD))
16159             NewFD->setInvalidDecl();
16160         }
16161       }
16162 
16163       // C++ [class.union]p1: If a union contains a member of reference type,
16164       // the program is ill-formed, except when compiling with MSVC extensions
16165       // enabled.
16166       if (EltTy->isReferenceType()) {
16167         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16168                                     diag::ext_union_member_of_reference_type :
16169                                     diag::err_union_member_of_reference_type)
16170           << NewFD->getDeclName() << EltTy;
16171         if (!getLangOpts().MicrosoftExt)
16172           NewFD->setInvalidDecl();
16173       }
16174     }
16175   }
16176 
16177   // FIXME: We need to pass in the attributes given an AST
16178   // representation, not a parser representation.
16179   if (D) {
16180     // FIXME: The current scope is almost... but not entirely... correct here.
16181     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16182 
16183     if (NewFD->hasAttrs())
16184       CheckAlignasUnderalignment(NewFD);
16185   }
16186 
16187   // In auto-retain/release, infer strong retension for fields of
16188   // retainable type.
16189   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16190     NewFD->setInvalidDecl();
16191 
16192   if (T.isObjCGCWeak())
16193     Diag(Loc, diag::warn_attribute_weak_on_field);
16194 
16195   NewFD->setAccess(AS);
16196   return NewFD;
16197 }
16198 
16199 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16200   assert(FD);
16201   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16202 
16203   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16204     return false;
16205 
16206   QualType EltTy = Context.getBaseElementType(FD->getType());
16207   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16208     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16209     if (RDecl->getDefinition()) {
16210       // We check for copy constructors before constructors
16211       // because otherwise we'll never get complaints about
16212       // copy constructors.
16213 
16214       CXXSpecialMember member = CXXInvalid;
16215       // We're required to check for any non-trivial constructors. Since the
16216       // implicit default constructor is suppressed if there are any
16217       // user-declared constructors, we just need to check that there is a
16218       // trivial default constructor and a trivial copy constructor. (We don't
16219       // worry about move constructors here, since this is a C++98 check.)
16220       if (RDecl->hasNonTrivialCopyConstructor())
16221         member = CXXCopyConstructor;
16222       else if (!RDecl->hasTrivialDefaultConstructor())
16223         member = CXXDefaultConstructor;
16224       else if (RDecl->hasNonTrivialCopyAssignment())
16225         member = CXXCopyAssignment;
16226       else if (RDecl->hasNonTrivialDestructor())
16227         member = CXXDestructor;
16228 
16229       if (member != CXXInvalid) {
16230         if (!getLangOpts().CPlusPlus11 &&
16231             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16232           // Objective-C++ ARC: it is an error to have a non-trivial field of
16233           // a union. However, system headers in Objective-C programs
16234           // occasionally have Objective-C lifetime objects within unions,
16235           // and rather than cause the program to fail, we make those
16236           // members unavailable.
16237           SourceLocation Loc = FD->getLocation();
16238           if (getSourceManager().isInSystemHeader(Loc)) {
16239             if (!FD->hasAttr<UnavailableAttr>())
16240               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16241                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16242             return false;
16243           }
16244         }
16245 
16246         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16247                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16248                diag::err_illegal_union_or_anon_struct_member)
16249           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16250         DiagnoseNontrivial(RDecl, member);
16251         return !getLangOpts().CPlusPlus11;
16252       }
16253     }
16254   }
16255 
16256   return false;
16257 }
16258 
16259 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16260 ///  AST enum value.
16261 static ObjCIvarDecl::AccessControl
16262 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16263   switch (ivarVisibility) {
16264   default: llvm_unreachable("Unknown visitibility kind");
16265   case tok::objc_private: return ObjCIvarDecl::Private;
16266   case tok::objc_public: return ObjCIvarDecl::Public;
16267   case tok::objc_protected: return ObjCIvarDecl::Protected;
16268   case tok::objc_package: return ObjCIvarDecl::Package;
16269   }
16270 }
16271 
16272 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16273 /// in order to create an IvarDecl object for it.
16274 Decl *Sema::ActOnIvar(Scope *S,
16275                                 SourceLocation DeclStart,
16276                                 Declarator &D, Expr *BitfieldWidth,
16277                                 tok::ObjCKeywordKind Visibility) {
16278 
16279   IdentifierInfo *II = D.getIdentifier();
16280   Expr *BitWidth = (Expr*)BitfieldWidth;
16281   SourceLocation Loc = DeclStart;
16282   if (II) Loc = D.getIdentifierLoc();
16283 
16284   // FIXME: Unnamed fields can be handled in various different ways, for
16285   // example, unnamed unions inject all members into the struct namespace!
16286 
16287   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16288   QualType T = TInfo->getType();
16289 
16290   if (BitWidth) {
16291     // 6.7.2.1p3, 6.7.2.1p4
16292     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16293     if (!BitWidth)
16294       D.setInvalidType();
16295   } else {
16296     // Not a bitfield.
16297 
16298     // validate II.
16299 
16300   }
16301   if (T->isReferenceType()) {
16302     Diag(Loc, diag::err_ivar_reference_type);
16303     D.setInvalidType();
16304   }
16305   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16306   // than a variably modified type.
16307   else if (T->isVariablyModifiedType()) {
16308     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16309     D.setInvalidType();
16310   }
16311 
16312   // Get the visibility (access control) for this ivar.
16313   ObjCIvarDecl::AccessControl ac =
16314     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16315                                         : ObjCIvarDecl::None;
16316   // Must set ivar's DeclContext to its enclosing interface.
16317   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16318   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16319     return nullptr;
16320   ObjCContainerDecl *EnclosingContext;
16321   if (ObjCImplementationDecl *IMPDecl =
16322       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16323     if (LangOpts.ObjCRuntime.isFragile()) {
16324     // Case of ivar declared in an implementation. Context is that of its class.
16325       EnclosingContext = IMPDecl->getClassInterface();
16326       assert(EnclosingContext && "Implementation has no class interface!");
16327     }
16328     else
16329       EnclosingContext = EnclosingDecl;
16330   } else {
16331     if (ObjCCategoryDecl *CDecl =
16332         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16333       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16334         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16335         return nullptr;
16336       }
16337     }
16338     EnclosingContext = EnclosingDecl;
16339   }
16340 
16341   // Construct the decl.
16342   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16343                                              DeclStart, Loc, II, T,
16344                                              TInfo, ac, (Expr *)BitfieldWidth);
16345 
16346   if (II) {
16347     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16348                                            ForVisibleRedeclaration);
16349     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16350         && !isa<TagDecl>(PrevDecl)) {
16351       Diag(Loc, diag::err_duplicate_member) << II;
16352       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16353       NewID->setInvalidDecl();
16354     }
16355   }
16356 
16357   // Process attributes attached to the ivar.
16358   ProcessDeclAttributes(S, NewID, D);
16359 
16360   if (D.isInvalidType())
16361     NewID->setInvalidDecl();
16362 
16363   // In ARC, infer 'retaining' for ivars of retainable type.
16364   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16365     NewID->setInvalidDecl();
16366 
16367   if (D.getDeclSpec().isModulePrivateSpecified())
16368     NewID->setModulePrivate();
16369 
16370   if (II) {
16371     // FIXME: When interfaces are DeclContexts, we'll need to add
16372     // these to the interface.
16373     S->AddDecl(NewID);
16374     IdResolver.AddDecl(NewID);
16375   }
16376 
16377   if (LangOpts.ObjCRuntime.isNonFragile() &&
16378       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16379     Diag(Loc, diag::warn_ivars_in_interface);
16380 
16381   return NewID;
16382 }
16383 
16384 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16385 /// class and class extensions. For every class \@interface and class
16386 /// extension \@interface, if the last ivar is a bitfield of any type,
16387 /// then add an implicit `char :0` ivar to the end of that interface.
16388 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16389                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16390   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16391     return;
16392 
16393   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16394   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16395 
16396   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16397     return;
16398   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16399   if (!ID) {
16400     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16401       if (!CD->IsClassExtension())
16402         return;
16403     }
16404     // No need to add this to end of @implementation.
16405     else
16406       return;
16407   }
16408   // All conditions are met. Add a new bitfield to the tail end of ivars.
16409   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16410   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16411 
16412   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16413                               DeclLoc, DeclLoc, nullptr,
16414                               Context.CharTy,
16415                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16416                                                                DeclLoc),
16417                               ObjCIvarDecl::Private, BW,
16418                               true);
16419   AllIvarDecls.push_back(Ivar);
16420 }
16421 
16422 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16423                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16424                        SourceLocation RBrac,
16425                        const ParsedAttributesView &Attrs) {
16426   assert(EnclosingDecl && "missing record or interface decl");
16427 
16428   // If this is an Objective-C @implementation or category and we have
16429   // new fields here we should reset the layout of the interface since
16430   // it will now change.
16431   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16432     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16433     switch (DC->getKind()) {
16434     default: break;
16435     case Decl::ObjCCategory:
16436       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16437       break;
16438     case Decl::ObjCImplementation:
16439       Context.
16440         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16441       break;
16442     }
16443   }
16444 
16445   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16446   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16447 
16448   // Start counting up the number of named members; make sure to include
16449   // members of anonymous structs and unions in the total.
16450   unsigned NumNamedMembers = 0;
16451   if (Record) {
16452     for (const auto *I : Record->decls()) {
16453       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16454         if (IFD->getDeclName())
16455           ++NumNamedMembers;
16456     }
16457   }
16458 
16459   // Verify that all the fields are okay.
16460   SmallVector<FieldDecl*, 32> RecFields;
16461 
16462   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16463        i != end; ++i) {
16464     FieldDecl *FD = cast<FieldDecl>(*i);
16465 
16466     // Get the type for the field.
16467     const Type *FDTy = FD->getType().getTypePtr();
16468 
16469     if (!FD->isAnonymousStructOrUnion()) {
16470       // Remember all fields written by the user.
16471       RecFields.push_back(FD);
16472     }
16473 
16474     // If the field is already invalid for some reason, don't emit more
16475     // diagnostics about it.
16476     if (FD->isInvalidDecl()) {
16477       EnclosingDecl->setInvalidDecl();
16478       continue;
16479     }
16480 
16481     // C99 6.7.2.1p2:
16482     //   A structure or union shall not contain a member with
16483     //   incomplete or function type (hence, a structure shall not
16484     //   contain an instance of itself, but may contain a pointer to
16485     //   an instance of itself), except that the last member of a
16486     //   structure with more than one named member may have incomplete
16487     //   array type; such a structure (and any union containing,
16488     //   possibly recursively, a member that is such a structure)
16489     //   shall not be a member of a structure or an element of an
16490     //   array.
16491     bool IsLastField = (i + 1 == Fields.end());
16492     if (FDTy->isFunctionType()) {
16493       // Field declared as a function.
16494       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16495         << FD->getDeclName();
16496       FD->setInvalidDecl();
16497       EnclosingDecl->setInvalidDecl();
16498       continue;
16499     } else if (FDTy->isIncompleteArrayType() &&
16500                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16501       if (Record) {
16502         // Flexible array member.
16503         // Microsoft and g++ is more permissive regarding flexible array.
16504         // It will accept flexible array in union and also
16505         // as the sole element of a struct/class.
16506         unsigned DiagID = 0;
16507         if (!Record->isUnion() && !IsLastField) {
16508           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16509             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16510           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16511           FD->setInvalidDecl();
16512           EnclosingDecl->setInvalidDecl();
16513           continue;
16514         } else if (Record->isUnion())
16515           DiagID = getLangOpts().MicrosoftExt
16516                        ? diag::ext_flexible_array_union_ms
16517                        : getLangOpts().CPlusPlus
16518                              ? diag::ext_flexible_array_union_gnu
16519                              : diag::err_flexible_array_union;
16520         else if (NumNamedMembers < 1)
16521           DiagID = getLangOpts().MicrosoftExt
16522                        ? diag::ext_flexible_array_empty_aggregate_ms
16523                        : getLangOpts().CPlusPlus
16524                              ? diag::ext_flexible_array_empty_aggregate_gnu
16525                              : diag::err_flexible_array_empty_aggregate;
16526 
16527         if (DiagID)
16528           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16529                                           << Record->getTagKind();
16530         // While the layout of types that contain virtual bases is not specified
16531         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16532         // virtual bases after the derived members.  This would make a flexible
16533         // array member declared at the end of an object not adjacent to the end
16534         // of the type.
16535         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16536           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16537               << FD->getDeclName() << Record->getTagKind();
16538         if (!getLangOpts().C99)
16539           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16540             << FD->getDeclName() << Record->getTagKind();
16541 
16542         // If the element type has a non-trivial destructor, we would not
16543         // implicitly destroy the elements, so disallow it for now.
16544         //
16545         // FIXME: GCC allows this. We should probably either implicitly delete
16546         // the destructor of the containing class, or just allow this.
16547         QualType BaseElem = Context.getBaseElementType(FD->getType());
16548         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16549           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16550             << FD->getDeclName() << FD->getType();
16551           FD->setInvalidDecl();
16552           EnclosingDecl->setInvalidDecl();
16553           continue;
16554         }
16555         // Okay, we have a legal flexible array member at the end of the struct.
16556         Record->setHasFlexibleArrayMember(true);
16557       } else {
16558         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16559         // unless they are followed by another ivar. That check is done
16560         // elsewhere, after synthesized ivars are known.
16561       }
16562     } else if (!FDTy->isDependentType() &&
16563                RequireCompleteType(FD->getLocation(), FD->getType(),
16564                                    diag::err_field_incomplete)) {
16565       // Incomplete type
16566       FD->setInvalidDecl();
16567       EnclosingDecl->setInvalidDecl();
16568       continue;
16569     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16570       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16571         // A type which contains a flexible array member is considered to be a
16572         // flexible array member.
16573         Record->setHasFlexibleArrayMember(true);
16574         if (!Record->isUnion()) {
16575           // If this is a struct/class and this is not the last element, reject
16576           // it.  Note that GCC supports variable sized arrays in the middle of
16577           // structures.
16578           if (!IsLastField)
16579             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16580               << FD->getDeclName() << FD->getType();
16581           else {
16582             // We support flexible arrays at the end of structs in
16583             // other structs as an extension.
16584             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16585               << FD->getDeclName();
16586           }
16587         }
16588       }
16589       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16590           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16591                                  diag::err_abstract_type_in_decl,
16592                                  AbstractIvarType)) {
16593         // Ivars can not have abstract class types
16594         FD->setInvalidDecl();
16595       }
16596       if (Record && FDTTy->getDecl()->hasObjectMember())
16597         Record->setHasObjectMember(true);
16598       if (Record && FDTTy->getDecl()->hasVolatileMember())
16599         Record->setHasVolatileMember(true);
16600     } else if (FDTy->isObjCObjectType()) {
16601       /// A field cannot be an Objective-c object
16602       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16603         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16604       QualType T = Context.getObjCObjectPointerType(FD->getType());
16605       FD->setType(T);
16606     } else if (Record && Record->isUnion() &&
16607                FD->getType().hasNonTrivialObjCLifetime() &&
16608                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16609                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16610                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16611                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16612       // For backward compatibility, fields of C unions declared in system
16613       // headers that have non-trivial ObjC ownership qualifications are marked
16614       // as unavailable unless the qualifier is explicit and __strong. This can
16615       // break ABI compatibility between programs compiled with ARC and MRR, but
16616       // is a better option than rejecting programs using those unions under
16617       // ARC.
16618       FD->addAttr(UnavailableAttr::CreateImplicit(
16619           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16620           FD->getLocation()));
16621     } else if (getLangOpts().ObjC &&
16622                getLangOpts().getGC() != LangOptions::NonGC &&
16623                Record && !Record->hasObjectMember()) {
16624       if (FD->getType()->isObjCObjectPointerType() ||
16625           FD->getType().isObjCGCStrong())
16626         Record->setHasObjectMember(true);
16627       else if (Context.getAsArrayType(FD->getType())) {
16628         QualType BaseType = Context.getBaseElementType(FD->getType());
16629         if (BaseType->isRecordType() &&
16630             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16631           Record->setHasObjectMember(true);
16632         else if (BaseType->isObjCObjectPointerType() ||
16633                  BaseType.isObjCGCStrong())
16634                Record->setHasObjectMember(true);
16635       }
16636     }
16637 
16638     if (Record && !getLangOpts().CPlusPlus &&
16639         !shouldIgnoreForRecordTriviality(FD)) {
16640       QualType FT = FD->getType();
16641       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16642         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16643         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16644             Record->isUnion())
16645           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16646       }
16647       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16648       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16649         Record->setNonTrivialToPrimitiveCopy(true);
16650         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16651           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16652       }
16653       if (FT.isDestructedType()) {
16654         Record->setNonTrivialToPrimitiveDestroy(true);
16655         Record->setParamDestroyedInCallee(true);
16656         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16657           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16658       }
16659 
16660       if (const auto *RT = FT->getAs<RecordType>()) {
16661         if (RT->getDecl()->getArgPassingRestrictions() ==
16662             RecordDecl::APK_CanNeverPassInRegs)
16663           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16664       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16665         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16666     }
16667 
16668     if (Record && FD->getType().isVolatileQualified())
16669       Record->setHasVolatileMember(true);
16670     // Keep track of the number of named members.
16671     if (FD->getIdentifier())
16672       ++NumNamedMembers;
16673   }
16674 
16675   // Okay, we successfully defined 'Record'.
16676   if (Record) {
16677     bool Completed = false;
16678     if (CXXRecord) {
16679       if (!CXXRecord->isInvalidDecl()) {
16680         // Set access bits correctly on the directly-declared conversions.
16681         for (CXXRecordDecl::conversion_iterator
16682                I = CXXRecord->conversion_begin(),
16683                E = CXXRecord->conversion_end(); I != E; ++I)
16684           I.setAccess((*I)->getAccess());
16685       }
16686 
16687       if (!CXXRecord->isDependentType()) {
16688         // Add any implicitly-declared members to this class.
16689         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16690 
16691         if (!CXXRecord->isInvalidDecl()) {
16692           // If we have virtual base classes, we may end up finding multiple
16693           // final overriders for a given virtual function. Check for this
16694           // problem now.
16695           if (CXXRecord->getNumVBases()) {
16696             CXXFinalOverriderMap FinalOverriders;
16697             CXXRecord->getFinalOverriders(FinalOverriders);
16698 
16699             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16700                                              MEnd = FinalOverriders.end();
16701                  M != MEnd; ++M) {
16702               for (OverridingMethods::iterator SO = M->second.begin(),
16703                                             SOEnd = M->second.end();
16704                    SO != SOEnd; ++SO) {
16705                 assert(SO->second.size() > 0 &&
16706                        "Virtual function without overriding functions?");
16707                 if (SO->second.size() == 1)
16708                   continue;
16709 
16710                 // C++ [class.virtual]p2:
16711                 //   In a derived class, if a virtual member function of a base
16712                 //   class subobject has more than one final overrider the
16713                 //   program is ill-formed.
16714                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16715                   << (const NamedDecl *)M->first << Record;
16716                 Diag(M->first->getLocation(),
16717                      diag::note_overridden_virtual_function);
16718                 for (OverridingMethods::overriding_iterator
16719                           OM = SO->second.begin(),
16720                        OMEnd = SO->second.end();
16721                      OM != OMEnd; ++OM)
16722                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16723                     << (const NamedDecl *)M->first << OM->Method->getParent();
16724 
16725                 Record->setInvalidDecl();
16726               }
16727             }
16728             CXXRecord->completeDefinition(&FinalOverriders);
16729             Completed = true;
16730           }
16731         }
16732       }
16733     }
16734 
16735     if (!Completed)
16736       Record->completeDefinition();
16737 
16738     // Handle attributes before checking the layout.
16739     ProcessDeclAttributeList(S, Record, Attrs);
16740 
16741     // We may have deferred checking for a deleted destructor. Check now.
16742     if (CXXRecord) {
16743       auto *Dtor = CXXRecord->getDestructor();
16744       if (Dtor && Dtor->isImplicit() &&
16745           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16746         CXXRecord->setImplicitDestructorIsDeleted();
16747         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16748       }
16749     }
16750 
16751     if (Record->hasAttrs()) {
16752       CheckAlignasUnderalignment(Record);
16753 
16754       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16755         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16756                                            IA->getRange(), IA->getBestCase(),
16757                                            IA->getSemanticSpelling());
16758     }
16759 
16760     // Check if the structure/union declaration is a type that can have zero
16761     // size in C. For C this is a language extension, for C++ it may cause
16762     // compatibility problems.
16763     bool CheckForZeroSize;
16764     if (!getLangOpts().CPlusPlus) {
16765       CheckForZeroSize = true;
16766     } else {
16767       // For C++ filter out types that cannot be referenced in C code.
16768       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16769       CheckForZeroSize =
16770           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16771           !CXXRecord->isDependentType() &&
16772           CXXRecord->isCLike();
16773     }
16774     if (CheckForZeroSize) {
16775       bool ZeroSize = true;
16776       bool IsEmpty = true;
16777       unsigned NonBitFields = 0;
16778       for (RecordDecl::field_iterator I = Record->field_begin(),
16779                                       E = Record->field_end();
16780            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16781         IsEmpty = false;
16782         if (I->isUnnamedBitfield()) {
16783           if (!I->isZeroLengthBitField(Context))
16784             ZeroSize = false;
16785         } else {
16786           ++NonBitFields;
16787           QualType FieldType = I->getType();
16788           if (FieldType->isIncompleteType() ||
16789               !Context.getTypeSizeInChars(FieldType).isZero())
16790             ZeroSize = false;
16791         }
16792       }
16793 
16794       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16795       // allowed in C++, but warn if its declaration is inside
16796       // extern "C" block.
16797       if (ZeroSize) {
16798         Diag(RecLoc, getLangOpts().CPlusPlus ?
16799                          diag::warn_zero_size_struct_union_in_extern_c :
16800                          diag::warn_zero_size_struct_union_compat)
16801           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16802       }
16803 
16804       // Structs without named members are extension in C (C99 6.7.2.1p7),
16805       // but are accepted by GCC.
16806       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16807         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16808                                diag::ext_no_named_members_in_struct_union)
16809           << Record->isUnion();
16810       }
16811     }
16812   } else {
16813     ObjCIvarDecl **ClsFields =
16814       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16815     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16816       ID->setEndOfDefinitionLoc(RBrac);
16817       // Add ivar's to class's DeclContext.
16818       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16819         ClsFields[i]->setLexicalDeclContext(ID);
16820         ID->addDecl(ClsFields[i]);
16821       }
16822       // Must enforce the rule that ivars in the base classes may not be
16823       // duplicates.
16824       if (ID->getSuperClass())
16825         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16826     } else if (ObjCImplementationDecl *IMPDecl =
16827                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16828       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16829       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16830         // Ivar declared in @implementation never belongs to the implementation.
16831         // Only it is in implementation's lexical context.
16832         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16833       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16834       IMPDecl->setIvarLBraceLoc(LBrac);
16835       IMPDecl->setIvarRBraceLoc(RBrac);
16836     } else if (ObjCCategoryDecl *CDecl =
16837                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16838       // case of ivars in class extension; all other cases have been
16839       // reported as errors elsewhere.
16840       // FIXME. Class extension does not have a LocEnd field.
16841       // CDecl->setLocEnd(RBrac);
16842       // Add ivar's to class extension's DeclContext.
16843       // Diagnose redeclaration of private ivars.
16844       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16845       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16846         if (IDecl) {
16847           if (const ObjCIvarDecl *ClsIvar =
16848               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16849             Diag(ClsFields[i]->getLocation(),
16850                  diag::err_duplicate_ivar_declaration);
16851             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16852             continue;
16853           }
16854           for (const auto *Ext : IDecl->known_extensions()) {
16855             if (const ObjCIvarDecl *ClsExtIvar
16856                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16857               Diag(ClsFields[i]->getLocation(),
16858                    diag::err_duplicate_ivar_declaration);
16859               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16860               continue;
16861             }
16862           }
16863         }
16864         ClsFields[i]->setLexicalDeclContext(CDecl);
16865         CDecl->addDecl(ClsFields[i]);
16866       }
16867       CDecl->setIvarLBraceLoc(LBrac);
16868       CDecl->setIvarRBraceLoc(RBrac);
16869     }
16870   }
16871 }
16872 
16873 /// Determine whether the given integral value is representable within
16874 /// the given type T.
16875 static bool isRepresentableIntegerValue(ASTContext &Context,
16876                                         llvm::APSInt &Value,
16877                                         QualType T) {
16878   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16879          "Integral type required!");
16880   unsigned BitWidth = Context.getIntWidth(T);
16881 
16882   if (Value.isUnsigned() || Value.isNonNegative()) {
16883     if (T->isSignedIntegerOrEnumerationType())
16884       --BitWidth;
16885     return Value.getActiveBits() <= BitWidth;
16886   }
16887   return Value.getMinSignedBits() <= BitWidth;
16888 }
16889 
16890 // Given an integral type, return the next larger integral type
16891 // (or a NULL type of no such type exists).
16892 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16893   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16894   // enum checking below.
16895   assert((T->isIntegralType(Context) ||
16896          T->isEnumeralType()) && "Integral type required!");
16897   const unsigned NumTypes = 4;
16898   QualType SignedIntegralTypes[NumTypes] = {
16899     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16900   };
16901   QualType UnsignedIntegralTypes[NumTypes] = {
16902     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16903     Context.UnsignedLongLongTy
16904   };
16905 
16906   unsigned BitWidth = Context.getTypeSize(T);
16907   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16908                                                         : UnsignedIntegralTypes;
16909   for (unsigned I = 0; I != NumTypes; ++I)
16910     if (Context.getTypeSize(Types[I]) > BitWidth)
16911       return Types[I];
16912 
16913   return QualType();
16914 }
16915 
16916 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16917                                           EnumConstantDecl *LastEnumConst,
16918                                           SourceLocation IdLoc,
16919                                           IdentifierInfo *Id,
16920                                           Expr *Val) {
16921   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16922   llvm::APSInt EnumVal(IntWidth);
16923   QualType EltTy;
16924 
16925   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16926     Val = nullptr;
16927 
16928   if (Val)
16929     Val = DefaultLvalueConversion(Val).get();
16930 
16931   if (Val) {
16932     if (Enum->isDependentType() || Val->isTypeDependent())
16933       EltTy = Context.DependentTy;
16934     else {
16935       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
16936         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16937         // constant-expression in the enumerator-definition shall be a converted
16938         // constant expression of the underlying type.
16939         EltTy = Enum->getIntegerType();
16940         ExprResult Converted =
16941           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16942                                            CCEK_Enumerator);
16943         if (Converted.isInvalid())
16944           Val = nullptr;
16945         else
16946           Val = Converted.get();
16947       } else if (!Val->isValueDependent() &&
16948                  !(Val = VerifyIntegerConstantExpression(Val,
16949                                                          &EnumVal).get())) {
16950         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16951       } else {
16952         if (Enum->isComplete()) {
16953           EltTy = Enum->getIntegerType();
16954 
16955           // In Obj-C and Microsoft mode, require the enumeration value to be
16956           // representable in the underlying type of the enumeration. In C++11,
16957           // we perform a non-narrowing conversion as part of converted constant
16958           // expression checking.
16959           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16960             if (Context.getTargetInfo()
16961                     .getTriple()
16962                     .isWindowsMSVCEnvironment()) {
16963               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16964             } else {
16965               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16966             }
16967           }
16968 
16969           // Cast to the underlying type.
16970           Val = ImpCastExprToType(Val, EltTy,
16971                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
16972                                                          : CK_IntegralCast)
16973                     .get();
16974         } else if (getLangOpts().CPlusPlus) {
16975           // C++11 [dcl.enum]p5:
16976           //   If the underlying type is not fixed, the type of each enumerator
16977           //   is the type of its initializing value:
16978           //     - If an initializer is specified for an enumerator, the
16979           //       initializing value has the same type as the expression.
16980           EltTy = Val->getType();
16981         } else {
16982           // C99 6.7.2.2p2:
16983           //   The expression that defines the value of an enumeration constant
16984           //   shall be an integer constant expression that has a value
16985           //   representable as an int.
16986 
16987           // Complain if the value is not representable in an int.
16988           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16989             Diag(IdLoc, diag::ext_enum_value_not_int)
16990               << EnumVal.toString(10) << Val->getSourceRange()
16991               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16992           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16993             // Force the type of the expression to 'int'.
16994             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16995           }
16996           EltTy = Val->getType();
16997         }
16998       }
16999     }
17000   }
17001 
17002   if (!Val) {
17003     if (Enum->isDependentType())
17004       EltTy = Context.DependentTy;
17005     else if (!LastEnumConst) {
17006       // C++0x [dcl.enum]p5:
17007       //   If the underlying type is not fixed, the type of each enumerator
17008       //   is the type of its initializing value:
17009       //     - If no initializer is specified for the first enumerator, the
17010       //       initializing value has an unspecified integral type.
17011       //
17012       // GCC uses 'int' for its unspecified integral type, as does
17013       // C99 6.7.2.2p3.
17014       if (Enum->isFixed()) {
17015         EltTy = Enum->getIntegerType();
17016       }
17017       else {
17018         EltTy = Context.IntTy;
17019       }
17020     } else {
17021       // Assign the last value + 1.
17022       EnumVal = LastEnumConst->getInitVal();
17023       ++EnumVal;
17024       EltTy = LastEnumConst->getType();
17025 
17026       // Check for overflow on increment.
17027       if (EnumVal < LastEnumConst->getInitVal()) {
17028         // C++0x [dcl.enum]p5:
17029         //   If the underlying type is not fixed, the type of each enumerator
17030         //   is the type of its initializing value:
17031         //
17032         //     - Otherwise the type of the initializing value is the same as
17033         //       the type of the initializing value of the preceding enumerator
17034         //       unless the incremented value is not representable in that type,
17035         //       in which case the type is an unspecified integral type
17036         //       sufficient to contain the incremented value. If no such type
17037         //       exists, the program is ill-formed.
17038         QualType T = getNextLargerIntegralType(Context, EltTy);
17039         if (T.isNull() || Enum->isFixed()) {
17040           // There is no integral type larger enough to represent this
17041           // value. Complain, then allow the value to wrap around.
17042           EnumVal = LastEnumConst->getInitVal();
17043           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17044           ++EnumVal;
17045           if (Enum->isFixed())
17046             // When the underlying type is fixed, this is ill-formed.
17047             Diag(IdLoc, diag::err_enumerator_wrapped)
17048               << EnumVal.toString(10)
17049               << EltTy;
17050           else
17051             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17052               << EnumVal.toString(10);
17053         } else {
17054           EltTy = T;
17055         }
17056 
17057         // Retrieve the last enumerator's value, extent that type to the
17058         // type that is supposed to be large enough to represent the incremented
17059         // value, then increment.
17060         EnumVal = LastEnumConst->getInitVal();
17061         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17062         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17063         ++EnumVal;
17064 
17065         // If we're not in C++, diagnose the overflow of enumerator values,
17066         // which in C99 means that the enumerator value is not representable in
17067         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17068         // permits enumerator values that are representable in some larger
17069         // integral type.
17070         if (!getLangOpts().CPlusPlus && !T.isNull())
17071           Diag(IdLoc, diag::warn_enum_value_overflow);
17072       } else if (!getLangOpts().CPlusPlus &&
17073                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17074         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17075         Diag(IdLoc, diag::ext_enum_value_not_int)
17076           << EnumVal.toString(10) << 1;
17077       }
17078     }
17079   }
17080 
17081   if (!EltTy->isDependentType()) {
17082     // Make the enumerator value match the signedness and size of the
17083     // enumerator's type.
17084     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17085     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17086   }
17087 
17088   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17089                                   Val, EnumVal);
17090 }
17091 
17092 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17093                                                 SourceLocation IILoc) {
17094   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17095       !getLangOpts().CPlusPlus)
17096     return SkipBodyInfo();
17097 
17098   // We have an anonymous enum definition. Look up the first enumerator to
17099   // determine if we should merge the definition with an existing one and
17100   // skip the body.
17101   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17102                                          forRedeclarationInCurContext());
17103   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17104   if (!PrevECD)
17105     return SkipBodyInfo();
17106 
17107   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17108   NamedDecl *Hidden;
17109   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17110     SkipBodyInfo Skip;
17111     Skip.Previous = Hidden;
17112     return Skip;
17113   }
17114 
17115   return SkipBodyInfo();
17116 }
17117 
17118 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17119                               SourceLocation IdLoc, IdentifierInfo *Id,
17120                               const ParsedAttributesView &Attrs,
17121                               SourceLocation EqualLoc, Expr *Val) {
17122   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17123   EnumConstantDecl *LastEnumConst =
17124     cast_or_null<EnumConstantDecl>(lastEnumConst);
17125 
17126   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17127   // we find one that is.
17128   S = getNonFieldDeclScope(S);
17129 
17130   // Verify that there isn't already something declared with this name in this
17131   // scope.
17132   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17133   LookupName(R, S);
17134   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17135 
17136   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17137     // Maybe we will complain about the shadowed template parameter.
17138     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17139     // Just pretend that we didn't see the previous declaration.
17140     PrevDecl = nullptr;
17141   }
17142 
17143   // C++ [class.mem]p15:
17144   // If T is the name of a class, then each of the following shall have a name
17145   // different from T:
17146   // - every enumerator of every member of class T that is an unscoped
17147   // enumerated type
17148   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17149     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17150                             DeclarationNameInfo(Id, IdLoc));
17151 
17152   EnumConstantDecl *New =
17153     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17154   if (!New)
17155     return nullptr;
17156 
17157   if (PrevDecl) {
17158     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17159       // Check for other kinds of shadowing not already handled.
17160       CheckShadow(New, PrevDecl, R);
17161     }
17162 
17163     // When in C++, we may get a TagDecl with the same name; in this case the
17164     // enum constant will 'hide' the tag.
17165     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17166            "Received TagDecl when not in C++!");
17167     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17168       if (isa<EnumConstantDecl>(PrevDecl))
17169         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17170       else
17171         Diag(IdLoc, diag::err_redefinition) << Id;
17172       notePreviousDefinition(PrevDecl, IdLoc);
17173       return nullptr;
17174     }
17175   }
17176 
17177   // Process attributes.
17178   ProcessDeclAttributeList(S, New, Attrs);
17179   AddPragmaAttributes(S, New);
17180 
17181   // Register this decl in the current scope stack.
17182   New->setAccess(TheEnumDecl->getAccess());
17183   PushOnScopeChains(New, S);
17184 
17185   ActOnDocumentableDecl(New);
17186 
17187   return New;
17188 }
17189 
17190 // Returns true when the enum initial expression does not trigger the
17191 // duplicate enum warning.  A few common cases are exempted as follows:
17192 // Element2 = Element1
17193 // Element2 = Element1 + 1
17194 // Element2 = Element1 - 1
17195 // Where Element2 and Element1 are from the same enum.
17196 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17197   Expr *InitExpr = ECD->getInitExpr();
17198   if (!InitExpr)
17199     return true;
17200   InitExpr = InitExpr->IgnoreImpCasts();
17201 
17202   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17203     if (!BO->isAdditiveOp())
17204       return true;
17205     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17206     if (!IL)
17207       return true;
17208     if (IL->getValue() != 1)
17209       return true;
17210 
17211     InitExpr = BO->getLHS();
17212   }
17213 
17214   // This checks if the elements are from the same enum.
17215   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17216   if (!DRE)
17217     return true;
17218 
17219   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17220   if (!EnumConstant)
17221     return true;
17222 
17223   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17224       Enum)
17225     return true;
17226 
17227   return false;
17228 }
17229 
17230 // Emits a warning when an element is implicitly set a value that
17231 // a previous element has already been set to.
17232 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17233                                         EnumDecl *Enum, QualType EnumType) {
17234   // Avoid anonymous enums
17235   if (!Enum->getIdentifier())
17236     return;
17237 
17238   // Only check for small enums.
17239   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17240     return;
17241 
17242   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17243     return;
17244 
17245   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17246   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17247 
17248   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17249   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17250 
17251   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17252   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17253     llvm::APSInt Val = D->getInitVal();
17254     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17255   };
17256 
17257   DuplicatesVector DupVector;
17258   ValueToVectorMap EnumMap;
17259 
17260   // Populate the EnumMap with all values represented by enum constants without
17261   // an initializer.
17262   for (auto *Element : Elements) {
17263     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17264 
17265     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17266     // this constant.  Skip this enum since it may be ill-formed.
17267     if (!ECD) {
17268       return;
17269     }
17270 
17271     // Constants with initalizers are handled in the next loop.
17272     if (ECD->getInitExpr())
17273       continue;
17274 
17275     // Duplicate values are handled in the next loop.
17276     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17277   }
17278 
17279   if (EnumMap.size() == 0)
17280     return;
17281 
17282   // Create vectors for any values that has duplicates.
17283   for (auto *Element : Elements) {
17284     // The last loop returned if any constant was null.
17285     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17286     if (!ValidDuplicateEnum(ECD, Enum))
17287       continue;
17288 
17289     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17290     if (Iter == EnumMap.end())
17291       continue;
17292 
17293     DeclOrVector& Entry = Iter->second;
17294     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17295       // Ensure constants are different.
17296       if (D == ECD)
17297         continue;
17298 
17299       // Create new vector and push values onto it.
17300       auto Vec = std::make_unique<ECDVector>();
17301       Vec->push_back(D);
17302       Vec->push_back(ECD);
17303 
17304       // Update entry to point to the duplicates vector.
17305       Entry = Vec.get();
17306 
17307       // Store the vector somewhere we can consult later for quick emission of
17308       // diagnostics.
17309       DupVector.emplace_back(std::move(Vec));
17310       continue;
17311     }
17312 
17313     ECDVector *Vec = Entry.get<ECDVector*>();
17314     // Make sure constants are not added more than once.
17315     if (*Vec->begin() == ECD)
17316       continue;
17317 
17318     Vec->push_back(ECD);
17319   }
17320 
17321   // Emit diagnostics.
17322   for (const auto &Vec : DupVector) {
17323     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17324 
17325     // Emit warning for one enum constant.
17326     auto *FirstECD = Vec->front();
17327     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17328       << FirstECD << FirstECD->getInitVal().toString(10)
17329       << FirstECD->getSourceRange();
17330 
17331     // Emit one note for each of the remaining enum constants with
17332     // the same value.
17333     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17334       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17335         << ECD << ECD->getInitVal().toString(10)
17336         << ECD->getSourceRange();
17337   }
17338 }
17339 
17340 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17341                              bool AllowMask) const {
17342   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17343   assert(ED->isCompleteDefinition() && "expected enum definition");
17344 
17345   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17346   llvm::APInt &FlagBits = R.first->second;
17347 
17348   if (R.second) {
17349     for (auto *E : ED->enumerators()) {
17350       const auto &EVal = E->getInitVal();
17351       // Only single-bit enumerators introduce new flag values.
17352       if (EVal.isPowerOf2())
17353         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17354     }
17355   }
17356 
17357   // A value is in a flag enum if either its bits are a subset of the enum's
17358   // flag bits (the first condition) or we are allowing masks and the same is
17359   // true of its complement (the second condition). When masks are allowed, we
17360   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17361   //
17362   // While it's true that any value could be used as a mask, the assumption is
17363   // that a mask will have all of the insignificant bits set. Anything else is
17364   // likely a logic error.
17365   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17366   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17367 }
17368 
17369 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17370                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17371                          const ParsedAttributesView &Attrs) {
17372   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17373   QualType EnumType = Context.getTypeDeclType(Enum);
17374 
17375   ProcessDeclAttributeList(S, Enum, Attrs);
17376 
17377   if (Enum->isDependentType()) {
17378     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17379       EnumConstantDecl *ECD =
17380         cast_or_null<EnumConstantDecl>(Elements[i]);
17381       if (!ECD) continue;
17382 
17383       ECD->setType(EnumType);
17384     }
17385 
17386     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17387     return;
17388   }
17389 
17390   // TODO: If the result value doesn't fit in an int, it must be a long or long
17391   // long value.  ISO C does not support this, but GCC does as an extension,
17392   // emit a warning.
17393   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17394   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17395   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17396 
17397   // Verify that all the values are okay, compute the size of the values, and
17398   // reverse the list.
17399   unsigned NumNegativeBits = 0;
17400   unsigned NumPositiveBits = 0;
17401 
17402   // Keep track of whether all elements have type int.
17403   bool AllElementsInt = true;
17404 
17405   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17406     EnumConstantDecl *ECD =
17407       cast_or_null<EnumConstantDecl>(Elements[i]);
17408     if (!ECD) continue;  // Already issued a diagnostic.
17409 
17410     const llvm::APSInt &InitVal = ECD->getInitVal();
17411 
17412     // Keep track of the size of positive and negative values.
17413     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17414       NumPositiveBits = std::max(NumPositiveBits,
17415                                  (unsigned)InitVal.getActiveBits());
17416     else
17417       NumNegativeBits = std::max(NumNegativeBits,
17418                                  (unsigned)InitVal.getMinSignedBits());
17419 
17420     // Keep track of whether every enum element has type int (very common).
17421     if (AllElementsInt)
17422       AllElementsInt = ECD->getType() == Context.IntTy;
17423   }
17424 
17425   // Figure out the type that should be used for this enum.
17426   QualType BestType;
17427   unsigned BestWidth;
17428 
17429   // C++0x N3000 [conv.prom]p3:
17430   //   An rvalue of an unscoped enumeration type whose underlying
17431   //   type is not fixed can be converted to an rvalue of the first
17432   //   of the following types that can represent all the values of
17433   //   the enumeration: int, unsigned int, long int, unsigned long
17434   //   int, long long int, or unsigned long long int.
17435   // C99 6.4.4.3p2:
17436   //   An identifier declared as an enumeration constant has type int.
17437   // The C99 rule is modified by a gcc extension
17438   QualType BestPromotionType;
17439 
17440   bool Packed = Enum->hasAttr<PackedAttr>();
17441   // -fshort-enums is the equivalent to specifying the packed attribute on all
17442   // enum definitions.
17443   if (LangOpts.ShortEnums)
17444     Packed = true;
17445 
17446   // If the enum already has a type because it is fixed or dictated by the
17447   // target, promote that type instead of analyzing the enumerators.
17448   if (Enum->isComplete()) {
17449     BestType = Enum->getIntegerType();
17450     if (BestType->isPromotableIntegerType())
17451       BestPromotionType = Context.getPromotedIntegerType(BestType);
17452     else
17453       BestPromotionType = BestType;
17454 
17455     BestWidth = Context.getIntWidth(BestType);
17456   }
17457   else if (NumNegativeBits) {
17458     // If there is a negative value, figure out the smallest integer type (of
17459     // int/long/longlong) that fits.
17460     // If it's packed, check also if it fits a char or a short.
17461     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17462       BestType = Context.SignedCharTy;
17463       BestWidth = CharWidth;
17464     } else if (Packed && NumNegativeBits <= ShortWidth &&
17465                NumPositiveBits < ShortWidth) {
17466       BestType = Context.ShortTy;
17467       BestWidth = ShortWidth;
17468     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17469       BestType = Context.IntTy;
17470       BestWidth = IntWidth;
17471     } else {
17472       BestWidth = Context.getTargetInfo().getLongWidth();
17473 
17474       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17475         BestType = Context.LongTy;
17476       } else {
17477         BestWidth = Context.getTargetInfo().getLongLongWidth();
17478 
17479         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17480           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17481         BestType = Context.LongLongTy;
17482       }
17483     }
17484     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17485   } else {
17486     // If there is no negative value, figure out the smallest type that fits
17487     // all of the enumerator values.
17488     // If it's packed, check also if it fits a char or a short.
17489     if (Packed && NumPositiveBits <= CharWidth) {
17490       BestType = Context.UnsignedCharTy;
17491       BestPromotionType = Context.IntTy;
17492       BestWidth = CharWidth;
17493     } else if (Packed && NumPositiveBits <= ShortWidth) {
17494       BestType = Context.UnsignedShortTy;
17495       BestPromotionType = Context.IntTy;
17496       BestWidth = ShortWidth;
17497     } else if (NumPositiveBits <= IntWidth) {
17498       BestType = Context.UnsignedIntTy;
17499       BestWidth = IntWidth;
17500       BestPromotionType
17501         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17502                            ? Context.UnsignedIntTy : Context.IntTy;
17503     } else if (NumPositiveBits <=
17504                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17505       BestType = Context.UnsignedLongTy;
17506       BestPromotionType
17507         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17508                            ? Context.UnsignedLongTy : Context.LongTy;
17509     } else {
17510       BestWidth = Context.getTargetInfo().getLongLongWidth();
17511       assert(NumPositiveBits <= BestWidth &&
17512              "How could an initializer get larger than ULL?");
17513       BestType = Context.UnsignedLongLongTy;
17514       BestPromotionType
17515         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17516                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17517     }
17518   }
17519 
17520   // Loop over all of the enumerator constants, changing their types to match
17521   // the type of the enum if needed.
17522   for (auto *D : Elements) {
17523     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17524     if (!ECD) continue;  // Already issued a diagnostic.
17525 
17526     // Standard C says the enumerators have int type, but we allow, as an
17527     // extension, the enumerators to be larger than int size.  If each
17528     // enumerator value fits in an int, type it as an int, otherwise type it the
17529     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17530     // that X has type 'int', not 'unsigned'.
17531 
17532     // Determine whether the value fits into an int.
17533     llvm::APSInt InitVal = ECD->getInitVal();
17534 
17535     // If it fits into an integer type, force it.  Otherwise force it to match
17536     // the enum decl type.
17537     QualType NewTy;
17538     unsigned NewWidth;
17539     bool NewSign;
17540     if (!getLangOpts().CPlusPlus &&
17541         !Enum->isFixed() &&
17542         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17543       NewTy = Context.IntTy;
17544       NewWidth = IntWidth;
17545       NewSign = true;
17546     } else if (ECD->getType() == BestType) {
17547       // Already the right type!
17548       if (getLangOpts().CPlusPlus)
17549         // C++ [dcl.enum]p4: Following the closing brace of an
17550         // enum-specifier, each enumerator has the type of its
17551         // enumeration.
17552         ECD->setType(EnumType);
17553       continue;
17554     } else {
17555       NewTy = BestType;
17556       NewWidth = BestWidth;
17557       NewSign = BestType->isSignedIntegerOrEnumerationType();
17558     }
17559 
17560     // Adjust the APSInt value.
17561     InitVal = InitVal.extOrTrunc(NewWidth);
17562     InitVal.setIsSigned(NewSign);
17563     ECD->setInitVal(InitVal);
17564 
17565     // Adjust the Expr initializer and type.
17566     if (ECD->getInitExpr() &&
17567         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17568       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17569                                                 CK_IntegralCast,
17570                                                 ECD->getInitExpr(),
17571                                                 /*base paths*/ nullptr,
17572                                                 VK_RValue));
17573     if (getLangOpts().CPlusPlus)
17574       // C++ [dcl.enum]p4: Following the closing brace of an
17575       // enum-specifier, each enumerator has the type of its
17576       // enumeration.
17577       ECD->setType(EnumType);
17578     else
17579       ECD->setType(NewTy);
17580   }
17581 
17582   Enum->completeDefinition(BestType, BestPromotionType,
17583                            NumPositiveBits, NumNegativeBits);
17584 
17585   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17586 
17587   if (Enum->isClosedFlag()) {
17588     for (Decl *D : Elements) {
17589       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17590       if (!ECD) continue;  // Already issued a diagnostic.
17591 
17592       llvm::APSInt InitVal = ECD->getInitVal();
17593       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17594           !IsValueInFlagEnum(Enum, InitVal, true))
17595         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17596           << ECD << Enum;
17597     }
17598   }
17599 
17600   // Now that the enum type is defined, ensure it's not been underaligned.
17601   if (Enum->hasAttrs())
17602     CheckAlignasUnderalignment(Enum);
17603 }
17604 
17605 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17606                                   SourceLocation StartLoc,
17607                                   SourceLocation EndLoc) {
17608   StringLiteral *AsmString = cast<StringLiteral>(expr);
17609 
17610   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17611                                                    AsmString, StartLoc,
17612                                                    EndLoc);
17613   CurContext->addDecl(New);
17614   return New;
17615 }
17616 
17617 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17618                                       IdentifierInfo* AliasName,
17619                                       SourceLocation PragmaLoc,
17620                                       SourceLocation NameLoc,
17621                                       SourceLocation AliasNameLoc) {
17622   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17623                                          LookupOrdinaryName);
17624   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17625                            AttributeCommonInfo::AS_Pragma);
17626   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17627       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17628 
17629   // If a declaration that:
17630   // 1) declares a function or a variable
17631   // 2) has external linkage
17632   // already exists, add a label attribute to it.
17633   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17634     if (isDeclExternC(PrevDecl))
17635       PrevDecl->addAttr(Attr);
17636     else
17637       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17638           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17639   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17640   } else
17641     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17642 }
17643 
17644 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17645                              SourceLocation PragmaLoc,
17646                              SourceLocation NameLoc) {
17647   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17648 
17649   if (PrevDecl) {
17650     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17651   } else {
17652     (void)WeakUndeclaredIdentifiers.insert(
17653       std::pair<IdentifierInfo*,WeakInfo>
17654         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17655   }
17656 }
17657 
17658 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17659                                 IdentifierInfo* AliasName,
17660                                 SourceLocation PragmaLoc,
17661                                 SourceLocation NameLoc,
17662                                 SourceLocation AliasNameLoc) {
17663   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17664                                     LookupOrdinaryName);
17665   WeakInfo W = WeakInfo(Name, NameLoc);
17666 
17667   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17668     if (!PrevDecl->hasAttr<AliasAttr>())
17669       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17670         DeclApplyPragmaWeak(TUScope, ND, W);
17671   } else {
17672     (void)WeakUndeclaredIdentifiers.insert(
17673       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17674   }
17675 }
17676 
17677 Decl *Sema::getObjCDeclContext() const {
17678   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17679 }
17680 
17681 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17682   // Templates are emitted when they're instantiated.
17683   if (FD->isDependentContext())
17684     return FunctionEmissionStatus::TemplateDiscarded;
17685 
17686   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17687   if (LangOpts.OpenMPIsDevice) {
17688     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17689         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17690     if (DevTy.hasValue()) {
17691       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17692         OMPES = FunctionEmissionStatus::OMPDiscarded;
17693       else if (DeviceKnownEmittedFns.count(FD) > 0)
17694         OMPES = FunctionEmissionStatus::Emitted;
17695     }
17696   } else if (LangOpts.OpenMP) {
17697     // In OpenMP 4.5 all the functions are host functions.
17698     if (LangOpts.OpenMP <= 45) {
17699       OMPES = FunctionEmissionStatus::Emitted;
17700     } else {
17701       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17702           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17703       // In OpenMP 5.0 or above, DevTy may be changed later by
17704       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17705       // having no value does not imply host. The emission status will be
17706       // checked again at the end of compilation unit.
17707       if (DevTy.hasValue()) {
17708         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17709           OMPES = FunctionEmissionStatus::OMPDiscarded;
17710         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17711           OMPES = FunctionEmissionStatus::Emitted;
17712         }
17713       }
17714     }
17715   }
17716   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17717       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17718     return OMPES;
17719 
17720   if (LangOpts.CUDA) {
17721     // When compiling for device, host functions are never emitted.  Similarly,
17722     // when compiling for host, device and global functions are never emitted.
17723     // (Technically, we do emit a host-side stub for global functions, but this
17724     // doesn't count for our purposes here.)
17725     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17726     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17727       return FunctionEmissionStatus::CUDADiscarded;
17728     if (!LangOpts.CUDAIsDevice &&
17729         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17730       return FunctionEmissionStatus::CUDADiscarded;
17731 
17732     // Check whether this function is externally visible -- if so, it's
17733     // known-emitted.
17734     //
17735     // We have to check the GVA linkage of the function's *definition* -- if we
17736     // only have a declaration, we don't know whether or not the function will
17737     // be emitted, because (say) the definition could include "inline".
17738     FunctionDecl *Def = FD->getDefinition();
17739 
17740     if (Def &&
17741         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17742         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17743       return FunctionEmissionStatus::Emitted;
17744   }
17745 
17746   // Otherwise, the function is known-emitted if it's in our set of
17747   // known-emitted functions.
17748   return (DeviceKnownEmittedFns.count(FD) > 0)
17749              ? FunctionEmissionStatus::Emitted
17750              : FunctionEmissionStatus::Unknown;
17751 }
17752 
17753 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17754   // Host-side references to a __global__ function refer to the stub, so the
17755   // function itself is never emitted and therefore should not be marked.
17756   // If we have host fn calls kernel fn calls host+device, the HD function
17757   // does not get instantiated on the host. We model this by omitting at the
17758   // call to the kernel from the callgraph. This ensures that, when compiling
17759   // for host, only HD functions actually called from the host get marked as
17760   // known-emitted.
17761   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17762          IdentifyCUDATarget(Callee) == CFT_Global;
17763 }
17764